Skip to content

Commit 87d52d5

Browse files
committed
fix index creation when close to tip
1 parent e84e72f commit 87d52d5

File tree

9 files changed

+120
-158
lines changed

9 files changed

+120
-158
lines changed

cardano-db-sync/src/Cardano/DbSync.hs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ runDbSync metricsSetters iomgr trce params syncNodeConfigFromFile abortOnPanic =
145145
void $ unsafeRollback trce (txOutConfigToTableType txOutConfig) pgConfig slotNo
146146

147147
-- This runMigration is ONLY for delayed migrations during sync (like indexes)
148-
let runDelayedMigration mode = do
148+
let runIndexesMigration mode = do
149149
msg <- DB.getMaintenancePsqlConf pgConfig
150150
logInfo trce $ "Running database migrations in mode " <> textShow mode
151151
logInfo trce msg
@@ -157,7 +157,7 @@ runDbSync metricsSetters iomgr trce params syncNodeConfigFromFile abortOnPanic =
157157
trce
158158
iomgr
159159
dbConnectionSetting
160-
(void . runDelayedMigration)
160+
(void . runIndexesMigration)
161161
syncNodeConfigFromFile
162162
params
163163
syncOpts
@@ -188,7 +188,7 @@ runSyncNode ::
188188
SyncNodeParams ->
189189
SyncOptions ->
190190
IO ()
191-
runSyncNode metricsSetters trce iomgr dbConnSetting runDelayedMigrationFnc syncNodeConfigFromFile syncNodeParams syncOptions = do
191+
runSyncNode metricsSetters trce iomgr dbConnSetting runIndexesMigrationFnc syncNodeConfigFromFile syncNodeParams syncOptions = do
192192
whenJust maybeLedgerDir $
193193
\enpLedgerStateDir -> do
194194
createDirectoryIfMissing True (unLedgerStateDir enpLedgerStateDir)
@@ -220,7 +220,7 @@ runSyncNode metricsSetters trce iomgr dbConnSetting runDelayedMigrationFnc syncN
220220
genCfg
221221
syncNodeConfigFromFile
222222
syncNodeParams
223-
runDelayedMigrationFnc
223+
runIndexesMigrationFnc
224224

225225
-- Warn the user that jsonb datatypes are being removed from the database schema.
226226
when (isJsonbInSchema && removeJsonbFromSchemaConfig) $ do

cardano-db-sync/src/Cardano/DbSync/Api.hs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ module Cardano.DbSync.Api (
1515
getIsConsumedFixed,
1616
getDisableInOutState,
1717
getRanIndexes,
18-
runIndexMigrations,
18+
runIndexesMigrations,
1919
initPruneConsumeMigration,
2020
runConsumedTxOutMigrationsMaybe,
2121
runAddJsonbToSchema,
@@ -131,11 +131,11 @@ getRanIndexes :: SyncEnv -> IO Bool
131131
getRanIndexes env = do
132132
readTVarIO $ envIndexes env
133133

134-
runIndexMigrations :: SyncEnv -> IO ()
135-
runIndexMigrations env = do
134+
runIndexesMigrations :: SyncEnv -> IO ()
135+
runIndexesMigrations env = do
136136
haveRan <- readTVarIO $ envIndexes env
137137
unless haveRan $ do
138-
envRunDelayedMigration env DB.Indexes
138+
envRunIndexesMigration env DB.Indexes
139139
logInfo (getTrace env) "Indexes were created"
140140
atomically $ writeTVar (envIndexes env) True
141141

@@ -318,7 +318,7 @@ mkSyncEnvFromConfig ::
318318
-- | run migration function
319319
RunMigration ->
320320
IO (Either SyncNodeError SyncEnv)
321-
mkSyncEnvFromConfig trce dbEnv syncOptions genCfg syncNodeConfigFromFile syncNodeParams runDelayedMigrationFnc =
321+
mkSyncEnvFromConfig trce dbEnv syncOptions genCfg syncNodeConfigFromFile syncNodeParams runIndexesMigrationFnc =
322322
case genCfg of
323323
GenesisCardano _ bCfg sCfg _ _
324324
| unProtocolMagicId (Byron.configProtocolMagicId bCfg) /= Shelley.sgNetworkMagic (scConfig sCfg) ->
@@ -353,7 +353,7 @@ mkSyncEnvFromConfig trce dbEnv syncOptions genCfg syncNodeConfigFromFile syncNod
353353
(SystemStart . Byron.gdStartTime $ Byron.configGenesisData bCfg)
354354
syncNodeConfigFromFile
355355
syncNodeParams
356-
runDelayedMigrationFnc
356+
runIndexesMigrationFnc
357357

358358
mkSyncEnv ::
359359
Trace IO Text ->
@@ -367,7 +367,7 @@ mkSyncEnv ::
367367
SyncNodeParams ->
368368
RunMigration ->
369369
IO SyncEnv
370-
mkSyncEnv trce dbEnv syncOptions protoInfo nw nwMagic systemStart syncNodeConfigFromFile syncNP runDelayedMigrationFnc = do
370+
mkSyncEnv trce dbEnv syncOptions protoInfo nw nwMagic systemStart syncNodeConfigFromFile syncNP runIndexesMigrationFnc = do
371371
dbCNamesVar <- newTVarIO =<< DB.runDbActionIO dbEnv DB.queryRewardAndEpochStakeConstraints
372372
cache <-
373373
if soptCache syncOptions
@@ -429,7 +429,7 @@ mkSyncEnv trce dbEnv syncOptions protoInfo nw nwMagic systemStart syncNodeConfig
429429
, envOffChainVoteResultQueue = oarq
430430
, envOffChainVoteWorkQueue = oawq
431431
, envOptions = syncOptions
432-
, envRunDelayedMigration = runDelayedMigrationFnc
432+
, envRunIndexesMigration = runIndexesMigrationFnc
433433
, envSyncNodeConfig = syncNodeConfigFromFile
434434
, envSystemStart = systemStart
435435
}

cardano-db-sync/src/Cardano/DbSync/Api/Types.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ data SyncEnv = SyncEnv
5757
, envOffChainVoteWorkQueue :: !(StrictTBQueue IO OffChainVoteWorkQueue)
5858
, envOptions :: !SyncOptions
5959
, envSyncNodeConfig :: !SyncNodeConfig
60-
, envRunDelayedMigration :: RunMigration
60+
, envRunIndexesMigration :: RunMigration
6161
, envSystemStart :: !SystemStart
6262
}
6363

cardano-db-sync/src/Cardano/DbSync/Default.hs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -205,9 +205,11 @@ insertBlock syncEnv cblk applyRes firstAfterRollback tookSnapshot = do
205205
bootStrapMaybe syncEnv
206206
ranIndexes <- liftIO $ getRanIndexes syncEnv
207207
addConstraintsIfNotExist syncEnv tracer
208-
unless ranIndexes $
209-
liftIO $
210-
runIndexMigrations syncEnv
208+
209+
unless ranIndexes $ do
210+
-- We need to commit the transaction as we are going to run indexes migrations
211+
DB.commitCurrentTransaction
212+
liftIO $ runIndexesMigrations syncEnv
211213

212214
blkNo = headerFieldBlockNo $ getHeaderFields cblk
213215

cardano-db/cardano-db.cabal

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ library
3030
-Wunused-packages
3131

3232
exposed-modules: Cardano.Db
33+
Cardano.Db.Progress
3334
Cardano.Db.Schema.Core
3435
Cardano.Db.Schema.Variants
3536
Cardano.Db.Schema.Variants.TxOutAddress
@@ -85,7 +86,6 @@ library
8586
, cardano-crypto-class
8687
, cardano-ledger-core
8788
, cardano-prelude
88-
, conduit-extra
8989
, containers
9090
, contra-tracer
9191
, contravariant-extras

cardano-db/src/Cardano/Db/Migration.hs

Lines changed: 43 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,12 @@ module Cardano.Db.Migration (
2525
) where
2626

2727
import Cardano.Prelude (textShow)
28-
import Control.Exception (Exception, SomeException, handle)
28+
import Control.Exception (Exception)
2929
import Control.Monad.Extra
3030
import Control.Monad.IO.Class (MonadIO, liftIO)
3131
import Control.Monad.Logger (NoLoggingT)
32-
import Control.Monad.Trans.Resource (runResourceT)
3332
import qualified Data.ByteString.Char8 as BS
3433
import Data.Char (isDigit)
35-
import Data.Conduit.Binary (sinkHandle)
36-
import Data.Conduit.Process (sourceCmdWithConsumer)
3734
import Data.Either (partitionEithers)
3835
import Data.List ((\\))
3936
import qualified Data.List as List
@@ -53,7 +50,6 @@ import System.FilePath (takeExtension, takeFileName, (</>))
5350
import System.IO (
5451
Handle,
5552
IOMode (AppendMode),
56-
hFlush,
5753
hPrint,
5854
hPutStrLn,
5955
stdout,
@@ -63,13 +59,14 @@ import Text.Read (readMaybe)
6359

6460
import Cardano.BM.Trace (Trace)
6561
import Cardano.Crypto.Hash (Blake2b_256, ByteString, Hash, hashToStringAsHex, hashWith)
66-
import Cardano.Db.Migration.Haskell
6762
import Cardano.Db.Migration.Version
6863
import Cardano.Db.PGConfig
6964
import Cardano.Db.Run
7065
import Cardano.Db.Schema.Variants (TxOutVariantType (..))
7166
import qualified Cardano.Db.Statement.Function.Core as DB
7267
import qualified Cardano.Db.Types as DB
68+
import System.Process (readProcessWithExitCode)
69+
import Cardano.Db.Progress (withProgress, updateProgress)
7370

7471
newtype MigrationDir
7572
= MigrationDir FilePath
@@ -104,19 +101,32 @@ runMigrations pgconfig quiet migrationDir mLogfiledir mToRun txOutVariantType =
104101
(_, []) ->
105102
error $ "Empty schema dir " ++ show migrationDir
106103
(Nothing, scripts) -> do
107-
-- Remove the pattern match that separates first script
108104
putStrLn "Running:"
109-
(scripts', ranAll) <- filterMigrations scripts -- Filter ALL scripts including first
110-
forM_ scripts' $ applyMigration' Nothing stdout
105+
(scripts', ranAll) <- filterMigrations scripts
106+
107+
-- Replace just this forM_ with progress bar
108+
withProgress (length scripts') "Database migrations" $ \progressRef -> do
109+
forM_ (zip [1 :: Integer ..] scripts') $ \(i, script) -> do
110+
updateProgress progressRef (fromIntegral i) $
111+
"Migration " <> Text.pack (show i) <> "/" <> Text.pack (show (length scripts'))
112+
applyMigration' Nothing stdout script
113+
111114
putStrLn "Success!"
112115
pure ranAll
116+
113117
(Just logfiledir, scripts) -> do
114-
-- Remove the pattern match here too
115118
logFilename <- genLogFilename logfiledir
116119
withFile logFilename AppendMode $ \logHandle -> do
117120
unless quiet $ putStrLn "Running:"
118-
(scripts', ranAll) <- filterMigrations scripts -- Filter ALL scripts including first
119-
forM_ scripts' $ applyMigration' (Just logFilename) logHandle
121+
(scripts', ranAll) <- filterMigrations scripts
122+
123+
-- Replace just this forM_ with progress bar
124+
withProgress (length scripts') "Database migrations" $ \progressRef -> do
125+
forM_ (zip [1 :: Integer ..] scripts') $ \(i, script) -> do
126+
updateProgress progressRef (fromIntegral i) $
127+
"Migration " <> Text.pack (show i) <> "/" <> Text.pack (show (length scripts'))
128+
applyMigration' (Just logFilename) logHandle script
129+
120130
unless quiet $ putStrLn "Success!"
121131
pure ranAll
122132
pure (ranAll, map (takeFileName . snd) (filter isUnofficialMigration allScripts))
@@ -169,37 +179,32 @@ validateMigrations migrationDir knownMigrations = do
169179
stage3or4 = flip elem [3, 4] . readStageFromFilename . Text.unpack . mvFilepath
170180

171181
applyMigration :: MigrationDir -> Bool -> PGConfig -> Maybe FilePath -> Handle -> (MigrationVersion, FilePath) -> IO ()
172-
applyMigration (MigrationDir location) quiet pgconfig mLogFilename logHandle (version, script) = do
173-
-- This assumes that the credentials for 'psql' are already sorted out.
174-
-- One way to achive this is via a 'PGPASSFILE' environment variable
175-
-- as per the PostgreSQL documentation.
176-
let command =
177-
List.unwords
178-
[ "psql"
179-
, Text.unpack (pgcDbname pgconfig)
180-
, "--no-password"
181-
, "--quiet"
182-
, "--username=" <> Text.unpack (pgcUser pgconfig)
183-
, "--host=" <> Text.unpack (pgcHost pgconfig)
184-
, "--port=" <> Text.unpack (pgcPort pgconfig)
185-
, "--no-psqlrc" -- Ignore the ~/.psqlrc file.
186-
, "--single-transaction" -- Run the file as a transaction.
187-
, "--set ON_ERROR_STOP=on" -- Exit with non-zero on error.
188-
, "--file='" ++ location </> script ++ "'"
189-
, "2>&1" -- Pipe stderr to stdout.
190-
]
182+
applyMigration (MigrationDir location) quiet pgconfig mLogFilename logHandle (_, script) = do
191183
hPutStrLn logHandle $ "Running : " ++ script
192184
unless quiet $ putStr (" " ++ script ++ " ... ")
193-
hFlush stdout
194-
exitCode <-
195-
fst
196-
<$> handle
197-
(errorExit :: SomeException -> IO a)
198-
(runResourceT $ sourceCmdWithConsumer command (sinkHandle logHandle))
185+
-- hFlush stdout
186+
187+
let psqlArgs = [ Text.unpack (pgcDbname pgconfig)
188+
, "--no-password"
189+
, "--quiet"
190+
, "--username=" <> Text.unpack (pgcUser pgconfig)
191+
, "--host=" <> Text.unpack (pgcHost pgconfig)
192+
, "--port=" <> Text.unpack (pgcPort pgconfig)
193+
, "--no-psqlrc"
194+
, "--single-transaction"
195+
, "--set", "ON_ERROR_STOP=on"
196+
, "--file=" ++ location </> script
197+
]
198+
199+
hPutStrLn logHandle $ "DEBUG: About to execute psql with args: " ++ show psqlArgs
200+
(exitCode, stdt, stderr) <- readProcessWithExitCode "psql" psqlArgs ""
201+
hPutStrLn logHandle $ "DEBUG: Command completed with exit code: " ++ show exitCode
202+
hPutStrLn logHandle $ "Command output: " ++ stdt
203+
unless (null stderr) $ hPutStrLn logHandle $ "Command stderr: " ++ stderr
204+
199205
case exitCode of
200206
ExitSuccess -> do
201207
unless quiet $ putStrLn "ok"
202-
runHaskellMigration (PGPassCached pgconfig) logHandle version
203208
ExitFailure _ -> errorExit exitCode
204209
where
205210
errorExit :: Show e => e -> IO a
@@ -212,8 +217,6 @@ applyMigration (MigrationDir location) quiet pgconfig mLogFilename logHandle (ve
212217
exitFailure
213218

214219
-- | Create a database migration.
215-
-- TODO: Cmdv - This functionality will need to be reimplemented without Persistent.
216-
-- For now, this serves as a placeholder.
217220
createMigration :: PGPassSource -> MigrationDir -> TxOutVariantType -> IO (Maybe FilePath)
218221
createMigration _source (MigrationDir _migdir) _txOutVariantType = do
219222
-- This would need to be completely rewritten to generate migrations manually

cardano-db/src/Cardano/Db/Run.hs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ import Cardano.Db.Error (DbCallStack (..), DbError (..), runOrThrowIO)
4242
import Cardano.Db.PGConfig
4343
import Cardano.Db.Statement.Function.Core (mkDbCallStack)
4444
import Cardano.Db.Types (DbAction (..), DbEnv (..))
45+
import Cardano.Db.Statement (runDbSession)
46+
import qualified Hasql.Session as HsqlSess
4547

4648
-----------------------------------------------------------------------------------------
4749
-- Transaction Management
@@ -73,6 +75,11 @@ commitTransactionStmt :: HsqlStmt.Statement () ()
7375
commitTransactionStmt =
7476
HsqlStmt.Statement "COMMIT" HsqlE.noParams HsqlD.noResult True
7577

78+
commitCurrentTransaction :: MonadIO m => DbAction m ()
79+
commitCurrentTransaction = do
80+
runDbSession (mkDbCallStack "commitCurrentTransaction") $
81+
HsqlSess.statement () commitTransactionStmt
82+
7683
-- | Rollback transaction
7784
rollbackTransactionStmt :: HsqlStmt.Statement () ()
7885
rollbackTransactionStmt =

0 commit comments

Comments
 (0)