fix(config): auto-route test.db locally, posterg.db on production

- config.php: getDatabasePath() detects php built-in CLI server
  (php_sapi_name() === 'cli-server') and routes to test.db; all
  other SAPIs (nginx/fpm) get posterg.db. DB_ENV env-var still
  overrides either way.

- migrate.sh: auto-initialise the target DB from storage/schema.sql
  when the file is absent or has no tables yet. Existing DBs with
  data are left completely untouched (table_count check, no re-run
  of schema on populated DB). Idempotent: safe to run repeatedly.

- justfile: serve still calls migrate (which now handles init too),
  no DB_ENV prefix needed since sapi detection handles routing.
This commit is contained in:
Pontoporeia
2026-03-31 16:47:29 +02:00
parent 877e322568
commit a88e5562f8
5 changed files with 28 additions and 16 deletions

View File

@@ -8,27 +8,33 @@
// Database paths relative to repository root
define('DB_ROOT', __DIR__ . '/..');
// Test database (used in development)
// Local dev database (php -S, never committed)
define('DB_TEST_PATH', DB_ROOT . '/storage/test.db');
// Production database (used on server)
// Production database (nginx/php-fpm on server)
define('DB_PROD_PATH', DB_ROOT . '/storage/posterg.db');
/**
* Determine which database to use.
*
* Always defaults to the production database.
* Set DB_ENV=test explicitly to use the test database.
* - php built-in server (php -S …) → storage/test.db (local dev)
* - everything else (nginx/fpm) → storage/posterg.db (production)
*
* export DB_ENV=test # use storage/test.db
* export DB_ENV=prod # use storage/posterg.db (default)
*
* The old file-existence auto-detection has been removed: a leftover
* test.db on a developer machine no longer silently redirects all
* requests to test data.
* The DB_ENV env-var can still override either way:
* DB_ENV=test → force test.db
* DB_ENV=prod → force posterg.db
*/
function getDatabasePath(): string {
if (getenv('DB_ENV') === 'test') {
$env = getenv('DB_ENV');
if ($env === 'test') {
return DB_TEST_PATH;
}
if ($env === 'prod') {
return DB_PROD_PATH;
}
// Auto-detect: php built-in CLI server == local development
if (php_sapi_name() === 'cli-server') {
return DB_TEST_PATH;
}
@@ -36,8 +42,8 @@ function getDatabasePath(): string {
}
/**
* Check if running in test/development mode
* Check if running in local dev mode
*/
function isTestMode() {
function isTestMode(): bool {
return getDatabasePath() === DB_TEST_PATH;
}