Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
a665b91
Start managed PostgreSQL with foreground Wasp commands
infomiho Oct 5, 2026
51d4a4c
Remove redundant PostgreSQL ready message
infomiho Oct 6, 2026
e82f79e
Separate database lifecycle and shared options from command entry points
infomiho Oct 6, 2026
8961d91
Simplify database readiness and formatting and organize database tests
infomiho Oct 7, 2026
25c3309
Clarify database startup options and restore database guidance
infomiho Oct 7, 2026
279d1ff
Split database lifecycle scenarios into independent tests
infomiho Oct 7, 2026
00fae0b
Select development database before entering PostgreSQL session
infomiho Oct 7, 2026
6c9aa88
Clarify development database names and separate URL detection from er…
infomiho Oct 7, 2026
0569614
Keep explicit database startup behavior in its command module
infomiho Oct 7, 2026
2b7dae8
Keep short database message expressions together
infomiho Oct 7, 2026
5eda1a5
Separate Docker stop and remove handling from cleanup execution
infomiho Oct 7, 2026
3aaefc5
Ensure no database URL override before explicit startup
infomiho Oct 7, 2026
99badc1
Check Docker executable and daemon through one helper
infomiho Oct 7, 2026
9bcf0cd
Reuse the common executable check for Docker availability
infomiho Oct 7, 2026
c57d37d
Use retryUntil for database readiness checks
infomiho Oct 7, 2026
c917c0b
Order dev database functions by workflow
infomiho Oct 7, 2026
16e1869
Keep database startup behavior in the existing command module
infomiho Oct 19, 2026
07ba113
Group development database Docker operations in a helper module
infomiho Oct 19, 2026
25b54eb
Order database helpers from workflow to implementation details
infomiho Oct 19, 2026
b68ca49
Keep the database studio parser in its command module
infomiho Oct 20, 2026
67ac525
Name Docker job execution and output explicitly
infomiho Oct 20, 2026
415bffc
Clarify database startup and URL source names
infomiho Oct 20, 2026
df0bf3b
Allow Prisma to create missing managed databases
infomiho Oct 20, 2026
42c4a53
Clarify PostgreSQL readiness check names
infomiho Oct 20, 2026
c98e54c
Simplify managed PostgreSQL readiness checks
infomiho Oct 20, 2026
5dc4db8
Explain direct PostgreSQL shutdown in database tests
infomiho Oct 20, 2026
89d3925
Extract shared development database lifecycle and options
infomiho Oct 19, 2026
a0993d9
Merge remote-tracking branch 'origin/main' into issue-4479-foreground-db
infomiho Nov 2, 2026
07b1635
Merge branch 'issue-4479-foreground-db' into issue-4479-db-extraction
infomiho Nov 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions waspc/cli/exe/Main.hs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import Wasp.Cli.Command.Clean (clean)
import Wasp.Cli.Command.Compile (compileCommand)
import Wasp.Cli.Command.CreateNewProject (createNewProject)
import Wasp.Cli.Command.CreateNewProject.AvailableTemplates (availableStarterTemplates)
import Wasp.Cli.Command.Db (runCommandThatRequiresDbRunning)
import qualified Wasp.Cli.Command.Db.Migrate as Command.Db.Migrate
import qualified Wasp.Cli.Command.Db.Reset as Command.Db.Reset
import qualified Wasp.Cli.Command.Db.Seed as Command.Db.Seed
Expand All @@ -38,7 +39,6 @@ import qualified Wasp.Cli.Command.Telemetry as Telemetry
import Wasp.Cli.Command.Test (test)
import Wasp.Cli.Command.Uninstall (uninstall)
import Wasp.Cli.Terminal (title)
import Wasp.Cli.Util.Parser (ArgsParser (..), withArguments)
import Wasp.Util (indent)
import Wasp.Util.InstallMethod (getInstallationCommand, legacyVersionsNote)
import qualified Wasp.Util.Terminal as Term
Expand Down Expand Up @@ -157,7 +157,7 @@ printUsage =
cmd " completion Prints help on bash completion.",
cmd " uninstall [--force] Removes Wasp from your system.",
title " IN PROJECT",
cmd " start [--client-port <port>] [--server-port <port>] [--client-url <url>] [--server-url <url>]",
cmd " start [--client-port <port>] [--server-port <port>] [--client-url <url>] [--server-url <url>] [--db-port <port>] [--db-image <image>] [--db-volume-mount-path <path>]",
" Runs Wasp app in development mode, watching for file changes.",
" Optionally specify the ports the client and the server run on.",
" If not specified, Wasp picks the first free port when the default one is taken.",
Expand Down Expand Up @@ -218,10 +218,10 @@ dbCli args = case args of
-- These commands don't require an existing and running database.
"start" : optionalStartArgs -> runCommand $ Command.Start.Db.start optionalStartArgs
-- These commands require an existing and running database.
"reset" : resetArgs -> runCommand $ withArguments Command.Db.Reset.resetArgsParser Command.Db.Reset.reset resetArgs
"migrate-dev" : optionalMigrateArgs -> runCommand $ withArguments Command.Db.Migrate.migrateArgsParser Command.Db.Migrate.migrateDev optionalMigrateArgs
"seed" : seedArgs -> runCommand $ withArguments Command.Db.Seed.seedArgsParser Command.Db.Seed.seed seedArgs
"studio" : studioArgs -> runCommand $ withArguments (ArgsParser "wasp db studio" (pure ())) (const Command.Db.Studio.studio) studioArgs
"reset" : resetArgs -> runCommandThatRequiresDbRunning Command.Db.Reset.resetArgsParser Command.Db.Reset.reset resetArgs
"migrate-dev" : optionalMigrateArgs -> runCommandThatRequiresDbRunning Command.Db.Migrate.migrateArgsParser Command.Db.Migrate.migrateDev optionalMigrateArgs
"seed" : seedArgs -> runCommandThatRequiresDbRunning Command.Db.Seed.seedArgsParser Command.Db.Seed.seed seedArgs
"studio" : studioArgs -> runCommandThatRequiresDbRunning Command.Db.Studio.studioArgsParser (const Command.Db.Studio.studio) studioArgs
_unknownDbCommand -> printDbUsage >> exitFailure

{- ORMOLU_DISABLE -}
Expand All @@ -236,7 +236,7 @@ printDbUsage =
cmd $ intercalate "\n" [
" start [--db-port <port>] [--db-image <image>] [--db-volume-mount-path <path>]",
" Alias for `wasp start db`.",
" Starts managed development database for you.",
" Runs a development database and streams its logs until Ctrl+C.",
" Optionally specify a custom port, Docker image, or Docker volume mount path.",
" If the port is not specified, Wasp picks the first free port when the default one is taken."
],
Expand All @@ -251,10 +251,20 @@ printDbUsage =
" supplied migration name or asking for one.",
" OPTIONS:",
" --name [migration-name]",
" --create-only"
" --create-only",
" --db-port <port>",
" --db-image <image>",
" --db-volume-mount-path <path>"
],
cmd " studio GUI for inspecting your database.",
"",
title "DATABASE OPTIONS",
" --db-port <port> Host port when starting managed PostgreSQL.",
" --db-image <image> Docker image when starting managed PostgreSQL.",
" --db-volume-mount-path <path>",
" Data path inside a new PostgreSQL container.",
" These options also work with reset, seed, migrate-dev, and studio.",
"",
title "EXAMPLES",
" wasp db migrate-dev",
" wasp db migrate-dev --name \"Added User entity\"",
Expand Down
17 changes: 15 additions & 2 deletions waspc/cli/src/Wasp/Cli/Command/Db.hs
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
module Wasp.Cli.Command.Db
( makeDbCommand,
( runCommandThatRequiresDbRunning,
makeDbCommand,
)
where

import qualified Wasp.AppSpec as AS
import Wasp.Cli.Command (Command, require)
import Wasp.Cli.Command (Command, require, runCommand)
import Wasp.Cli.Command.Call (Arguments)
import Wasp.Cli.Command.Compile (defaultCompileOptions, withSetupGoals)
import qualified Wasp.Cli.Command.Db.DevDb as DevDb
import Wasp.Cli.Command.Db.StartOptions (dbStartOptionsParser)
import Wasp.Cli.Command.Require.DbConnectionEstablished (DbConnectionEstablished (DbConnectionEstablished))
import Wasp.Cli.Command.Require.InWaspProject (InWaspProject (InWaspProject))
import Wasp.Cli.Command.Require.WaspSpecAvailable (WaspSpecAvailable (WaspSpecAvailable))
import Wasp.Cli.Compile (waitEnsureCompile)
import Wasp.Cli.Util.Parser (ArgsParser (..), withArguments)
import Wasp.Generator.Setup (SetupGoal)

runCommandThatRequiresDbRunning :: ArgsParser a -> (a -> Command ()) -> Arguments -> IO ()
runCommandThatRequiresDbRunning parser command args =
runCommand $ withArguments databaseArgsParser run args
where
databaseArgsParser = parser {optParser = (,) <$> dbStartOptionsParser <*> parser.optParser}
run (dbStartOptions, commandArgs) =
DevDb.withDevDb dbStartOptions $ \_ -> command commandArgs

-- | Prepares what a db command needs before it runs: a compile,
-- post-compile setup, and a reachable database.
--
Expand Down
206 changes: 206 additions & 0 deletions waspc/cli/src/Wasp/Cli/Command/Db/DevDb.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
module Wasp.Cli.Command.Db.DevDb
( withDevDb,
withPostgresSession,
DatabaseStartPolicy (..),
DatabaseSession (..),
DatabaseUrlSource (..),
findDatabaseUrlSource,
)
where

import Control.Concurrent.Async (Async, async, cancel, race, wait)
import Control.Exception (IOException, try)
import Control.Monad (unless, when)
import Control.Monad.Catch (bracket, bracketOnError, finally)
import qualified Control.Monad.Except as E
import Control.Monad.IO.Class (liftIO)
import Data.List (intercalate)
import Data.Maybe (fromMaybe, isJust)
import Network.Socket (PortNumber)
import StrongPath (Abs, Dir, Path')
import System.Environment (lookupEnv)
import System.Exit (ExitCode)
import System.IO.Error (ioeGetErrorString)
import Text.Printf (printf)
import qualified Wasp.AppSpec as AS
import qualified Wasp.AppSpec.App as AS.App
import qualified Wasp.AppSpec.App.Db as AS.App.Db
import qualified Wasp.AppSpec.Valid as ASV
import Wasp.Cli.Command (Command, CommandError (CommandError), require)
import Wasp.Cli.Command.Compile (analyze)
import qualified Wasp.Cli.Command.Db.Docker as Docker
import Wasp.Cli.Command.Db.StartOptions (DbStartOptions (..))
import Wasp.Cli.Command.Message (cliSendMessageC)
import Wasp.Cli.Command.Require.InWaspProject (InWaspProject (InWaspProject))
import Wasp.Cli.Command.Require.WaspSpecAvailable (WaspSpecAvailable (WaspSpecAvailable))
import Wasp.Cli.Port (resolvePort)
import Wasp.Db.Postgres (defaultPostgresDockerImageSpec, defaultPostgresPort)
import qualified Wasp.Message as Msg
import Wasp.Project.Common (WaspProjectDir)
import Wasp.Project.Db (databaseUrlEnvVarName)
import qualified Wasp.Project.Db.Dev.Postgres as Dev.Postgres
import Wasp.Util.Docker (DockerImageName, DockerVolumeMountPath)

withDevDb :: DbStartOptions -> (Maybe Dev.Postgres.DevDbSpec -> Command a) -> Command a
withDevDb options action = do
InWaspProject waspProjectDir <- require
WaspSpecAvailable <- require
appSpec <- analyze waspProjectDir
databaseUrlSource <- liftIO $ findDatabaseUrlSource appSpec
case databaseUrlSource of
Just _ -> do
throwIfDbStartOptionsSupplied "DATABASE_URL is set." options
action Nothing
Nothing -> case ASV.getValidDbSystem appSpec of
AS.App.Db.SQLite -> do
throwIfDbStartOptionsSupplied "This project uses SQLite." options
action Nothing
AS.App.Db.PostgreSQL ->
withPostgresSession waspProjectDir (ASV.getApp appSpec).name options AllowExistingDatabase $
action . Just . getDatabaseForSession

data DatabaseStartPolicy = RequireNewDatabase | AllowExistingDatabase
deriving (Eq)

data DatabaseSession
= ReusedDatabase Dev.Postgres.DevDbSpec
| StartedDatabase Dev.Postgres.DevDbSpec String (Async ExitCode)

withPostgresSession :: Path' Abs (Dir WaspProjectDir) -> String -> DbStartOptions -> DatabaseStartPolicy -> (DatabaseSession -> Command a) -> Command a
withPostgresSession waspProjectDir appName options policy action = do
startupPlan <- prepareDatabaseStartup waspProjectDir appName options policy
bracket (acquire startupPlan) release use
where
acquire (ReuseDatabase session) = return session
acquire (CreateDatabase db image mountPath) =
bracketOnError
(withDatabaseError "Could not start PostgreSQL" $ Dev.Postgres.createDevPostgresContainer db image mountPath)
Docker.removeContainer
( \containerId -> do
databaseJob <- liftIO $ async $ Docker.runDockerJobAndPrintOutput ["start", "--attach", containerId]
return $ StartedDatabase db containerId databaseJob
)

use session = do
case session of
StartedDatabase db _ databaseJob -> do
result <-
withDatabaseError "Could not start PostgreSQL" $
race (wait databaseJob) (Dev.Postgres.waitForDevDbReady db)
case result of
Left _ -> E.throwError $ CommandError "Could not start PostgreSQL" "The Docker process exited before PostgreSQL was ready. Check the database output above."
Right () -> return ()
when (policy == RequireNewDatabase) $ cliSendMessageC $ Msg.Info $ unlines $ additionalInfoLines db
_ -> return ()
action session

release (StartedDatabase _ containerId databaseJob) =
Docker.stopDatabase containerId `finally` (liftIO (cancel databaseJob) `finally` Docker.removeContainer containerId)
release _ = return ()

data DatabaseStartupPlan
= ReuseDatabase DatabaseSession
| CreateDatabase Dev.Postgres.DevDbSpec DockerImageName DockerVolumeMountPath

prepareDatabaseStartup :: Path' Abs (Dir WaspProjectDir) -> String -> DbStartOptions -> DatabaseStartPolicy -> Command DatabaseStartupPlan
prepareDatabaseStartup waspProjectDir appName options policy = do
Docker.ensureDockerDaemonAvailable

liftIO (Dev.Postgres.discoverProjectsRunningDevDb waspProjectDir appName) >>= \case
Just runningDb -> case policy of
RequireNewDatabase ->
E.throwError $
CommandError
"PostgreSQL already running"
( printf
"This project's database is already running on port %s. Stop the command that started it, or run `docker stop %s` before starting it again.\n%s"
(show runningDb.port)
runningDb.dockerContainerName
(unlines $ additionalInfoLines runningDb)
)
AllowExistingDatabase -> ReuseDatabase <$> prepareExistingDatabase runningDb
Nothing -> prepareStartupOnPort =<< resolveDevDbPort
where
dbDockerImage = fromMaybe (fst defaultPostgresDockerImageSpec) options.dbImage
dbDockerVolumeMountPath = fromMaybe (snd defaultPostgresDockerImageSpec) options.dbVolumeMountPath

resolveDevDbPort :: Command PortNumber
resolveDevDbPort =
resolvePort
options.dbPort
defaultPostgresPort
[]
"Choose a different port with --db-port, or free up this one."
"Free at least one of those ports by exiting the program listening on it, or choose the port yourself with --db-port."

prepareExistingDatabase :: Dev.Postgres.DevDbSpec -> Command DatabaseSession
prepareExistingDatabase devDbSpec = do
withDatabaseError "PostgreSQL is not ready" $ Dev.Postgres.waitForDevDbReady devDbSpec
cliSendMessageC $ Msg.Info "PostgreSQL was already running for this project. Wasp did not start it and will not stop it."
unless (null $ suppliedOptionNames options) $ cliSendMessageC $ Msg.Warning "Database options not used" (printf "These options only apply when starting a new container: %s. Stop the running database before changing them." (intercalate ", " (suppliedOptionNames options)))
return $ ReusedDatabase devDbSpec

prepareStartupOnPort :: PortNumber -> Command DatabaseStartupPlan
prepareStartupOnPort port = do
let devDbSpec = Dev.Postgres.makeDevPostgresDbSpec waspProjectDir appName port
Docker.ensureImageAvailable dbDockerImage
cliSendMessageC $ Msg.Start "Starting PostgreSQL..."
cliSendMessageC $ Msg.Info $ unlines dockerRunInfoLines
return $ CreateDatabase devDbSpec dbDockerImage dbDockerVolumeMountPath

-- These lines describe what Docker is about to use, so we print them
-- only when starting the database: an already running container might have
-- been started with a different image or mount path than the current
-- invocation's arguments.
dockerRunInfoLines :: [String]
dockerRunInfoLines =
[ " ℹ Using Docker image: " <> dbDockerImage,
" with the data volume mounted at: " <> dbDockerVolumeMountPath
]

getDatabaseForSession :: DatabaseSession -> Dev.Postgres.DevDbSpec
getDatabaseForSession (ReusedDatabase db) = db
getDatabaseForSession (StartedDatabase db _ _) = db

data DatabaseUrlSource = EnvironmentVariable | ServerDotEnvFile

findDatabaseUrlSource :: AS.AppSpec -> IO (Maybe DatabaseUrlSource)
findDatabaseUrlSource appSpec = do
envUrl <- lookupEnv databaseUrlEnvVarName
return $
if isJust envUrl
then Just EnvironmentVariable
else
if any ((== databaseUrlEnvVarName) . fst) appSpec.devEnvVarsServer
then Just ServerDotEnvFile
else Nothing

throwIfDbStartOptionsSupplied :: String -> DbStartOptions -> Command ()
throwIfDbStartOptionsSupplied reason options =
unless (null optionNames) $ E.throwError $ CommandError "Database options do not apply" (printf "%s These options only apply to Wasp-managed PostgreSQL: %s. Remove them to continue." reason (intercalate ", " optionNames))
where
optionNames = suppliedOptionNames options

suppliedOptionNames :: DbStartOptions -> [String]
suppliedOptionNames options =
["--db-port" | isJust options.dbPort]
++ ["--db-image" | isJust options.dbImage]
++ ["--db-volume-mount-path" | isJust options.dbVolumeMountPath]

additionalInfoLines :: Dev.Postgres.DevDbSpec -> [String]
additionalInfoLines devDbSpec =
[ "",
"Additional info:",
" ℹ Connection URL, in case you might want to connect with external tools:",
" " <> Dev.Postgres.getDevConnectionUrl devDbSpec,
" ℹ Database data is persisted in a Docker volume with the following name"
<> " (useful to know if you will want to delete it at some point):",
" " <> devDbSpec.dockerVolumeName
]

withDatabaseError :: String -> IO a -> Command a
withDatabaseError title action = do
result <- liftIO $ try action
case result of
Left (err :: IOException) -> E.throwError $ CommandError title $ ioeGetErrorString err
Right value -> return value
Loading