sqint 0.1.0.2 → 0.1.1.0
raw patch · 7 files changed
+214/−28 lines, 7 files
Files
- CHANGELOG.md +11/−0
- README.md +4/−1
- sqint.cabal +1/−1
- src/Sqint/Cumulative.hs +113/−23
- src/Sqint/Deploy.hs +29/−0
- src/Sqint/Rule.hs +2/−0
- test/Sqint/CumulativeSpec.hs +54/−3
CHANGELOG.md view
@@ -1,5 +1,16 @@ # Changelog +## 0.1.1.0++* The dynamic pass handles reworked changes. A baseline whose name the branch+ reworks again is placed at the occurrence the database has deployed up to,+ read from the sqitch registry; before, it resolved to the branch's own+ occurrence and the pass checked nothing, without saying so. When the+ registry cannot be read it reports the new `setup/baseline-ambiguous`.+* A change reworked more than once after the baseline is deployed as+ `change@tag` and observed from its snapshot script; before, the pass+ stopped with sqitch's "is ambiguous" error.+ ## 0.1.0.2 * Accept string-interpolate 0.3.4, which sqint builds with; 0.1.0.1 asked
README.md view
@@ -81,7 +81,7 @@ sqint --database-root db $(git diff --name-only main -- db/deploy) ``` -That is the static pass. For the dynamic pass, deploy the target branch to a scratch database first, then run sqint on the branch under review from the directory holding `sqitch.conf`. sqint runs `sqitch deploy --to-change <change> --verify` for each new change, so give sqitch the same database through the `PG*` variables:+That is the static pass. For the dynamic pass, deploy the target branch to a scratch database first, then run sqint on the branch under review from the directory holding `sqitch.conf`. sqint runs `sqitch deploy --to-change <change> --verify` for each new change, so give sqitch the same database through the `PG*` variables, or through `SQITCH_TARGET` when `sqitch.conf` names a default target with its own database (a database in the target's URI wins over `PGDATABASE`): ```bash git switch main@@ -98,6 +98,8 @@ Every change after the baseline is deployed for real, one at a time, so use a database you can throw away. +The baseline may be a reworked change, which is what a table changed with sqiff leaves at the end of the plan, and the branch may rework it again. Its name then occurs more than once, and sqint takes the occurrence the database has deployed up to, from the sqitch registry. If it cannot read the registry it reports `setup/baseline-ambiguous` and skips the dynamic pass rather than guess. A change reworked several times after the baseline is deployed by its tag-qualified name (`change@tag`), from its snapshot script.+ ## What it catches Every example below is sqint's own output for the SQL above it.@@ -389,6 +391,7 @@ | `setup/unparsable-domain-file` | static | INFO | A deploy file sqint could not read for domains. | | `setup/unparsable-plan` | dynamic | INFO | A `sqitch.plan` sqint could not read. | | `setup/baseline-missing` | dynamic | INFO | A `--baseline-change` that is not in the plan. |+| `setup/baseline-ambiguous` | dynamic | INFO | A reworked `--baseline-change` whose deployed occurrence the sqitch registry could not tell. | ## Limits
sqint.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.4 name: sqint-version: 0.1.0.2+version: 0.1.1.0 synopsis: Lint sqitch migrations for PostgreSQL lock and rewrite hazards
src/Sqint/Cumulative.hs view
@@ -39,6 +39,8 @@ -- * Internals exposed for the test-suite newChangesAfter,+ PendingChange (..),+ BaselineProblem (..), BrokenFunction (..), FunctionCheck (..), recordCheck,@@ -79,24 +81,113 @@ planSrc <- readFileUtf8 planPath case Plan.parsePlan planSrc of Left err -> pure [planParseFinding planPath (Plan.renderParseError err)]- Right plan -> case newChangesAfter plan baseline of- Nothing -> pure [baselineMissingFinding planPath baseline]- Just changes -> observeAndDeploy settings topDir planPath changes+ Right plan -> do+ deployed <- deployedOccurrence settings plan baseline+ case newChangesAfter plan baseline deployed of+ Left BaselineMissing -> pure [baselineMissingFinding planPath baseline]+ Left (BaselineAmbiguous occurrenceLines) -> pure [baselineAmbiguousFinding planPath baseline occurrenceLines]+ Right changes -> observeAndDeploy settings topDir planPath changes +-- | A change the pass deploys: what sqitch calls it, and the script that+-- holds it.+data PendingChange = PendingChange+ { name :: Text+ , target :: Text+ -- ^ The @--to-change@ specifier. A reworked change shares its name+ -- with its other occurrences, so a bare name is ambiguous to sqitch:+ -- an occurrence reworked again later is @name\@tag@, for the tag its+ -- next occurrence was reworked at; the latest occurrence is+ -- @name\@HEAD@; a change that occurs once is its bare name.+ , script :: FilePath+ -- ^ Relative to the sqitch top directory. An occurrence reworked again+ -- later is deployed from its snapshot, @deploy/name\@tag.sql@.+ }+ deriving stock (Eq, Show)+++-- | Why the baseline change could not be placed in the plan.+data BaselineProblem+ = -- | The plan has no change of that name.+ BaselineMissing+ | -- | The name occurs more than once and the database did not say+ -- which occurrence it has reached. The lines of each occurrence.+ BaselineAmbiguous [Int]+ deriving stock (Eq, Show)++ -- | The changes that come strictly after the @baseline@ change, in--- plan (deploy) order. 'Nothing' when the baseline change is not in the--- plan at all — a configuration error the caller surfaces rather than--- silently treating every change as new (which would re-deploy the--- whole history).-newChangesAfter :: Plan.Plan -> Text -> Maybe [Plan.Change]-newChangesAfter plan baseline = map (.value) <$> Plan.changesAfter baseline plan+-- plan (deploy) order.+--+-- When the baseline is a reworked change, its name occurs more than once,+-- and the branch may have reworked it yet again after the baseline. The+-- database decides: the baseline is the occurrence at the position the+-- database has deployed up to (the third argument, a count of deployed+-- changes). Without that, an ambiguous baseline is a problem the caller+-- reports, never a guess: guessing the last occurrence would leave+-- nothing to check, and an earlier one would redeploy history.+newChangesAfter :: Plan.Plan -> Text -> Maybe Int -> Either BaselineProblem [PendingChange]+newChangesAfter plan baseline deployed = do+ base <- resolveBaseline plan baseline deployed+ pure (map (pendingChange plan) (Plan.changesAfterLine base.line plan)) +resolveBaseline :: Plan.Plan -> Text -> Maybe Int -> Either BaselineProblem (Plan.Located Plan.Change)+resolveBaseline plan baseline deployed = case Plan.occurrences baseline plan of+ [] -> Left BaselineMissing+ [only] -> Right only+ several -> case deployedHead of+ Just c | c.line `elem` map (.line) several -> Right c+ _ -> Left (BaselineAmbiguous (map (.line) several))+ where+ deployedHead = do+ n <- deployed+ guard (n >= 1)+ listToMaybe (drop (n - 1) (Plan.changes plan))+++-- | How sqitch names a change at this position, and where its script is.+pendingChange :: Plan.Plan -> Plan.Located Plan.Change -> PendingChange+pendingChange plan c =+ let name = c.value.name+ later = filter (\o -> o.line > c.line) (Plan.occurrences name plan)+ snapshot = case later of+ next : _ -> Plan.reworkTag next.value <|> listToMaybe [t.value.name | t <- Plan.tagsAfterLine c.line plan]+ [] -> Nothing+ current = "deploy" </> T.unpack name <> ".sql"+ in case snapshot of+ Just tag -> PendingChange{name, target = name <> "@" <> tag, script = "deploy" </> T.unpack (name <> "@" <> tag) <> ".sql"}+ Nothing+ | Plan.isReworked name plan -> PendingChange{name, target = name <> "@HEAD", script = current}+ | otherwise -> PendingChange{name, target = name, script = current}+++-- | How many changes the database has deployed, when the baseline's name+-- is ambiguous and that count is what places it. 'Nothing' when the name+-- is not ambiguous, or the count could not be read.+deployedOccurrence :: DeploySettings -> Plan.Plan -> Text -> IO (Maybe Int)+deployedOccurrence settings plan baseline+ | length (Plan.occurrences baseline plan) < 2 = pure Nothing+ | otherwise = case Plan.projectName plan of+ Nothing -> pure Nothing+ Just project -> do+ registry <- sqitchRegistry+ either (const Nothing) Just <$> tryAny (Deploy.deployedChangeCount settings registry project)+++-- | The registry schema sqitch uses: @engine.pg.registry@, or @sqitch@.+sqitchRegistry :: IO Text+sqitchRegistry = do+ (code, out, _err) <- readCreateProcessWithExitCode (proc "sqitch" ["config", "--get", "engine.pg.registry"]) ""+ pure case code of+ ExitSuccess | not (T.null (T.strip (T.pack out))) -> T.strip (T.pack out)+ _ -> "sqitch"++ -- | The observe-then-deploy loop. Stops at the first deploy failure -- (the schema would be desynced past that point, so later observations -- would be meaningless) and reports it.-observeAndDeploy :: DeploySettings -> FilePath -> FilePath -> [Plan.Change] -> IO [Finding]+observeAndDeploy :: DeploySettings -> FilePath -> FilePath -> [PendingChange] -> IO [Finding] observeAndDeploy settings topDir planPath changes = do baseline <- tryAny (Deploy.brokenSqlFunctions settings) case baseline of@@ -108,13 +199,13 @@ go functions acc [] = pure (reverse acc <> brokenFindings functions) go functions acc (change : rest) = do let name = change.name- script = topDir </> "deploy" </> T.unpack name <> ".sql"+ script = topDir </> change.script exists <- doesFileExist script observed <- if exists then Deploy.inspectFile settings script else pure []- deployed <- sqitchDeployTo (deployTarget change)+ deployed <- sqitchDeployTo change.target case deployed of Right () -> do (functions', skipped) <- checkFunctions functions name script@@ -239,17 +330,6 @@ [] -> 1 --- | The @--to-change@ specifier for a change. A reworked change shares--- its name with the earlier instance already on the database, so a bare--- name is ambiguous to sqitch ("matches multiple changes"); @\@HEAD@--- pins it to the latest instance — the rework we are deploying. Plain--- (non-reworked) changes have unique names, so no qualifier is needed.-deployTarget :: Plan.Change -> Text-deployTarget change =- let name = change.name- in if isJust (Plan.reworkTag change) then name <> "@HEAD" else name-- -- | @sqitch deploy --to-change <target> --verify@ from the working -- directory, where @sqitch.conf@ is. Connection parameters come from the -- inherited @PG*@ environment, which the caller sets to the same database@@ -296,6 +376,16 @@ SetupBaselineMissing "Baseline change not found in sqitch.plan" [i|The baseline change `#{baseline}` is not present in the plan, so the cumulative dynamic pass was skipped; static checks still applied.|]+++baselineAmbiguousFinding :: FilePath -> Text -> [Int] -> Finding+baselineAmbiguousFinding path baseline occurrenceLines =+ pointFinding+ path+ SeverityInfo+ SetupBaselineAmbiguous+ "Baseline change is reworked, and the database did not say which occurrence it is at"+ [i|`#{baseline}` occurs #{length occurrenceLines} times in the plan (lines #{T.intercalate ", " (map tshow occurrenceLines)}), and the sqitch registry on the database could not be read to tell which occurrence is deployed, so the cumulative dynamic pass was skipped; static checks still applied. Deploy the target branch's plan into the database before running sqint.|] deployFailedFinding :: FilePath -> Text -> Text -> Finding
src/Sqint/Deploy.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE NoFieldSelectors #-} -- | The dynamic pass: deploy each statement and observe its locks.@@ -27,6 +28,7 @@ module Sqint.Deploy ( inspectFile, brokenSqlFunctions,+ deployedChangeCount, -- * Internals exposed for the test-suite lockFindings,@@ -38,6 +40,7 @@ import Data.ByteString.Char8 qualified as BS8 import Data.Map.Strict qualified as Map import Data.Set qualified as Set+import Data.String.Interpolate (i) import Data.Text qualified as T import Data.Text.IO qualified as Text.IO import Hasql.Connection (Connection)@@ -547,6 +550,32 @@ pure (decodeUtf8Lenient signature, decodeUtf8Lenient err) rollback pq pure (Map.fromList broken)+++-- | How many changes of the project the sqitch registry records as deployed+-- on the database. Sqitch deploys in plan order and a revert removes the+-- row, so this is how far into the plan the database is, counting each+-- occurrence of a reworked change.+deployedChangeCount ::+ DeploySettings ->+ -- | The registry schema: sqitch's @engine.pg.registry@, @sqitch@ by default.+ Text ->+ -- | The plan's @%project@.+ Text ->+ IO Int+deployedChangeCount settings registry project =+ withConnection settings \conn ->+ withPqConnection conn \pq -> do+ result <-+ execTuplesOrThrow+ "deployedChangeCount"+ pq+ (encodeUtf8 [i|select count(*) from #{quoteIdent registry}.changes where project = #{quoteLiteral project}|])+ count <- getCellOrThrow "deployedChangeCount" result 0 0+ maybe (throwIO (DeployQueryError ("deployedChangeCount: not a number: " <> decodeUtf8Lenient count))) pure (readMaybe (BS8.unpack count))+ where+ quoteIdent name = let escaped = T.replace "\"" "\"\"" name in [i|"#{escaped}"|] :: Text+ quoteLiteral value = let escaped = T.replace "'" "''" value in [i|'#{escaped}'|] :: Text -- | A temporary function that re-creates every SQL function from its own
src/Sqint/Rule.hs view
@@ -51,6 +51,7 @@ | SetupUnparsableDomainFile | SetupUnparsablePlan | SetupBaselineMissing+ | SetupBaselineAmbiguous deriving stock (Eq, Show) @@ -79,6 +80,7 @@ SetupUnparsableDomainFile -> "setup/unparsable-domain-file" SetupUnparsablePlan -> "setup/unparsable-plan" SetupBaselineMissing -> "setup/baseline-missing"+ SetupBaselineAmbiguous -> "setup/baseline-ambiguous" -- | PostgreSQL's lock mode names (@ACCESS EXCLUSIVE@ and so on), in the
test/Sqint/CumulativeSpec.hs view
@@ -6,7 +6,7 @@ import Data.String.Interpolate (i) import Data.Text qualified as T import RIO-import Sqint.Cumulative (BrokenFunction (..), FunctionCheck (..), brokenFunctionFinding, firstStatementLine, newChangesAfter, recordCheck, trackBrokenFunctions)+import Sqint.Cumulative (BaselineProblem (..), BrokenFunction (..), FunctionCheck (..), PendingChange (..), brokenFunctionFinding, firstStatementLine, newChangesAfter, recordCheck, trackBrokenFunctions) import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..)) import Sqint.Rule (renderRule) import Sqitch.Plan qualified as Plan@@ -23,15 +23,30 @@ changeNamesAfter :: Text -> Text -> Maybe [Text] changeNamesAfter baseline body =- map (.name) <$> newChangesAfter (plan body) baseline+ either (const Nothing) (Just . map (.name)) (newChangesAfter (plan body) baseline Nothing) +-- | What the pass deploys after the baseline, given how many changes the+-- database has deployed: each change's sqitch target and script.+pendingAfter :: Text -> Maybe Int -> Text -> Either BaselineProblem [(Text, FilePath)]+pendingAfter baseline deployed body =+ map (\c -> (c.target, c.script)) <$> newChangesAfter (plan body) baseline deployed+++tag :: Text -> Text+tag name = [i|@#{name} 2024-01-01T00:00:00Z a <a@x> \# tag|] <> "\n"+++rework :: Text -> Text -> Text+rework name at = [i|#{name} [#{name}@#{at}] 2024-01-02T00:00:00Z a <a@x> \# reworked #{name}|] <> "\n"++ line :: Text -> Text line name = [i|#{name} 2024-01-01T00:00:00Z a <a@x> \# #{name}|] <> "\n" tests :: TestTree-tests = testGroup "Cumulative" [newChangesAfterTests, brokenFunctionTests]+tests = testGroup "Cumulative" [newChangesAfterTests, reworkedChangeTests, brokenFunctionTests] newChangesAfterTests :: TestTree@@ -61,6 +76,42 @@ <> line "z" ) @?= Just ["t", "z"]+ ]+++reworkedChangeTests :: TestTree+reworkedChangeTests =+ testGroup+ "Cumulative.newChangesAfter, reworked changes"+ [ testCase "a change reworked again later deploys from its snapshot, by tag"+ $ pendingAfter+ "a"+ Nothing+ (line "a" <> line "t" <> tag "v1" <> rework "t" "v1" <> tag "v2" <> rework "t" "v2")+ @?= Right+ [ ("t@v1", "deploy/t@v1.sql")+ , ("t@v2", "deploy/t@v2.sql")+ , ("t@HEAD", "deploy/t.sql")+ ]+ , testCase "a change that occurs once is deployed by its bare name"+ $ pendingAfter "a" Nothing (line "a" <> line "b")+ @?= Right [("b", "deploy/b.sql")]+ , testCase "a reworked baseline is placed where the database has deployed to"+ $+ -- The target branch ends with the second occurrence of `t`; this+ -- branch reworks it a third time. The database has deployed the+ -- target branch: three changes.+ pendingAfter "t" (Just 3) (line "a" <> line "t" <> tag "v1" <> rework "t" "v1" <> tag "v2" <> rework "t" "v2")+ @?= Right [("t@HEAD", "deploy/t.sql")]+ , testCase "a reworked baseline the database cannot place is ambiguous, not guessed"+ $ pendingAfter "t" Nothing (line "a" <> line "t" <> tag "v1" <> rework "t" "v1")+ @?= Left (BaselineAmbiguous [5, 7])+ , testCase "a deployed count that lands on another change does not place the baseline"+ $ pendingAfter "t" (Just 1) (line "a" <> line "t" <> tag "v1" <> rework "t" "v1")+ @?= Left (BaselineAmbiguous [5, 7])+ , testCase "a baseline that is not in the plan is missing"+ $ pendingAfter "nope" (Just 1) (line "a")+ @?= Left BaselineMissing ]