diff --git a/docker/dev/docker-start b/docker/dev/docker-start index 25ba09f15..d5721125c 100755 --- a/docker/dev/docker-start +++ b/docker/dev/docker-start @@ -10,4 +10,17 @@ rm -f /tmp/.s.PGSQL.* rm -f /var/log/api-umbrella/trafficserver/error.log make + +# Wait for PostgreSQL to be ready before running database setup. +echo "Waiting for PostgreSQL to be ready..." +until PGPASSWORD=dev_password psql -h postgres -U postgres -c '\q' 2>/dev/null; do + echo "PostgreSQL is unavailable - sleeping" + sleep 1 +done +echo "PostgreSQL is ready" + +# Run database setup as postgres superuser to create the database and roles. +# This is idempotent and safe to run on every startup. +DB_USERNAME=postgres DB_PASSWORD=dev_password api-umbrella db-setup + api-umbrella run diff --git a/src/api-umbrella/cli.lua b/src/api-umbrella/cli.lua index b7c5ad1cd..00a830d8f 100644 --- a/src/api-umbrella/cli.lua +++ b/src/api-umbrella/cli.lua @@ -59,6 +59,11 @@ function _M.db_setup() db_setup() end +function _M.db_drop() + local db_drop = require "api-umbrella.cli.db_drop" + db_drop() +end + function _M.migrate() local migrate = require "api-umbrella.cli.migrate" migrate() @@ -140,6 +145,10 @@ parser:command("db-setup") :description("Run the initial database setup task.") :action(_M.db_setup) +parser:command("db-drop") + :description("Drop the database.") + :action(_M.db_drop) + parser:command("migrate") :description("Run the database migrations task.") :action(_M.migrate) diff --git a/src/api-umbrella/cli/db_drop.lua b/src/api-umbrella/cli/db_drop.lua new file mode 100644 index 000000000..fdf37c836 --- /dev/null +++ b/src/api-umbrella/cli/db_drop.lua @@ -0,0 +1,11 @@ +local pg_utils = require "api-umbrella.utils.pg_utils" + +return function() + local database = pg_utils.db_config["database"] + + pg_utils.db_config["database"] = "postgres" + pg_utils.db_config["user"] = os.getenv("DB_USERNAME") + pg_utils.db_config["password"] = os.getenv("DB_PASSWORD") + + pg_utils.query("DROP DATABASE IF EXISTS :database", { database = pg_utils.identifier(database) }, { verbose = true, fatal = true }) +end