Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

Merge remote-tracking branch 'origin/next' into feat/add-sqlite-database

peaklabs-dev5261785c6908
diff --cc app/Actions/Database/StartDatabase.php
index c416ce2565,af2b48e893..4ed70adffc
--- a/app/Actions/Database/StartDatabase.php
+++ b/app/Actions/Database/StartDatabase.php
@@@ -13,7 -14,7 +14,8 @@@ use App\Models\StandaloneMongodb
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
+use App\Models\StandaloneSqlite;
+ use App\Support\ResourceStartActivity;
use Lorisleiva\Actions\Concerns\AsAction;
use Lorisleiva\Actions\Decorators\JobDecorator;
use Spatie\Activitylog\Models\Activity;
diff --cc app/Jobs/DatabaseStartJob.php
index def6b5d470,e520c79dfe..5bbd35b9c7
--- a/app/Jobs/DatabaseStartJob.php
+++ b/app/Jobs/DatabaseStartJob.php
@@@ -10,9 -10,9 +10,10 @@@ use App\Actions\Database\StartMongodb
use App\Actions\Database\StartMysql;
use App\Actions\Database\StartPostgresql;
use App\Actions\Database\StartRedis;
+use App\Actions\Database\StartSqlite;
use App\Enums\ProcessStatus;
use App\Events\DatabaseStatusChanged;
+ use App\Exceptions\DatabaseStartException;
use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDragonfly;
use App\Models\StandaloneKeydb;
@@@ -21,7 -21,7 +22,8 @@@ use App\Models\StandaloneMongodb
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
+use App\Models\StandaloneSqlite;
+ use App\Support\ResourceStartActivity;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldQueue;
@@@ -64,9 -64,12 +66,13 @@@ class DatabaseStartJob implements Shoul
StandaloneKeydb::class => StartKeydb::run($database, $activity),
StandaloneDragonfly::class => StartDragonfly::run($database, $activity),
StandaloneClickhouse::class => StartClickhouse::run($database, $activity),
+ StandaloneSqlite::class => StartSqlite::run($database, $activity),
};
+ if (! $result instanceof Activity || data_get($result, 'properties.status') !== ProcessStatus::FINISHED->value) {
+ throw DatabaseStartException::startCommandsDidNotRun();
+ }
+
event(new DatabaseStatusChanged($this->userId));
}
diff --cc app/Support/DatabaseImport/DatabaseImportCommandBuilder.php
index 4c367b0761,ffb28ba6fd..3568fe3e22
--- a/app/Support/DatabaseImport/DatabaseImportCommandBuilder.php
+++ b/app/Support/DatabaseImport/DatabaseImportCommandBuilder.php
@@@ -7,31 -7,60 +7,61 @@@ use InvalidArgumentException
class DatabaseImportCommandBuilder
{
+ /**
+ * Shell helpers shared by every restore script. The backup inside the database
+ * container is plain or gzip-compressed (bz2, xz and zip are decompressed by
+ * {@see self::buildNormalizeScript()} before it arrives). Every script decides the
+ * backup format before it changes anything in the database.
+ */
+ private const PRELUDE = <<<'SH'
+ fail() { echo "$1" >&2; exit 1; }
+ is_gzip() { [ "$(head -c 2 "$backup" | od -An -tx1 | tr -d ' \n')" = 1f8b ]; }
+ stream() { if is_gzip; then gunzip -c "$backup"; else cat "$backup"; fi; }
+ header() { stream | head -c "$1" | od -An -tx1 | tr -d ' \n'; }
+ is_tar() { [ "$(stream | head -c 262 | tail -c 5)" = ustar ]; }
+ is_text() { [ "$(stream | head -c 65536 | tr -d '\000' | wc -c | tr -d ' ')" = "$(stream | head -c 65536 | wc -c | tr -d ' ')" ]; }
+ extract_tar() { work=$(mktemp -d) && trap 'rm -rf "$work"' EXIT && stream | tar -xf - -C "$work" || fail 'The tar backup cannot be extracted.'; }
+ use_single_tar_member() { [ "$(find "$work" -type f | wc -l | tr -d ' ')" = 1 ] && backup=$(find "$work" -type f); }
+
+ SH;
+
public function buildRestoreCommand(object $resource, string $path, bool $dumpAll, bool $replaceExisting = false): string
{
- $path = escapeshellarg($path);
-
- return match ($this->databaseType($resource)) {
- 'postgresql' => $dumpAll
- ? 'psql -U ${POSTGRES_USER} -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname IS NOT NULL AND pid <> pg_backend_pid()" && psql -U ${POSTGRES_USER} -t -c "SELECT datname FROM pg_database WHERE NOT datistemplate" | xargs -I {} dropdb -U ${POSTGRES_USER} --if-exists {} && createdb -U ${POSTGRES_USER} ${POSTGRES_DB:-${POSTGRES_USER:-postgres}} && (gunzip -cf '.$path.' 2>/dev/null || cat '.$path.') | psql -U ${POSTGRES_USER} -d ${POSTGRES_DB:-${POSTGRES_USER:-postgres}}'
- : 'pg_restore --exit-on-error'.($replaceExisting ? ' --clean --if-exists' : '').' -U $POSTGRES_USER -d ${POSTGRES_DB:-${POSTGRES_USER:-postgres}} '.$path,
- 'mysql' => $dumpAll
- ? $this->mysqlDumpAll('mysql', 'MYSQL', $path)
- : '(gunzip -cf '.$path.' 2>/dev/null || cat '.$path.') | mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE',
- 'mariadb' => $dumpAll
- ? $this->mysqlDumpAll('mariadb', 'MARIADB', $path)
- : '(gunzip -cf '.$path.' 2>/dev/null || cat '.$path.') | mariadb -u $MARIADB_USER -p$MARIADB_PASSWORD $MARIADB_DATABASE',
- 'mongodb' => 'mongorestore --authenticationDatabase=admin --username $MONGO_INITDB_ROOT_USERNAME --password $MONGO_INITDB_ROOT_PASSWORD --uri mongodb://localhost:27017 --gzip --archive='.$path,
- 'sqlite' => $this->sqliteRestore($resource->databaseFilePath(), $path),
+ $script = match ($this->databaseType($resource)) {
+ 'postgresql' => $dumpAll ? $this->postgresqlDumpAll() : $this->postgresqlSingle($replaceExisting),
+ 'mysql' => $this->mysql('mysql', 'MYSQL', $dumpAll),
+ 'mariadb' => $this->mysql('mariadb', 'MARIADB', $dumpAll),
+ 'mongodb' => $this->mongodb($replaceExisting),
++ 'sqlite' => $this->sqlite($resource->databaseFilePath()),
default => throw new InvalidArgumentException('Database import is not supported for this database type.'),
};
+
+ return 'backup='.escapeshellarg($path)."\n".self::PRELUDE.$script;
}
- private function sqliteRestore(string $file, string $path): string
+ /**
+ * Prepares a backup inside the Coolify helper image. bz2, xz and single-file zip
+ * backups are decompressed because database images do not ship those tools;
+ * plain and gzip backups are moved unchanged. Exits non-zero on any failure.
+ */
+ public function buildNormalizeScript(string $source, string $target): string
{
- $file = escapeshellarg($file);
+ $source = escapeshellarg($source);
+ $target = escapeshellarg($target);
- return "backup={$path}; gunzip -c \"\$backup\" > \"\$backup.db\" && sqlite3 -bail {$file} '.timeout 10000' \".restore \$backup.db\"; status=\$?; rm -f \"\$backup.db\"; exit \$status";
+ return <<<SH
+ f={$source}
+ out={$target}
+ case "\$(head -c 6 "\$f" | od -An -tx1 | tr -d ' \\n')" in
+ 425a68*) bunzip2 -c "\$f" > "\$out" || { echo 'The bz2 backup cannot be decompressed.' >&2; exit 1; } ;;
+ fd377a585a00) unxz -c "\$f" > "\$out" || { echo 'The xz backup cannot be decompressed.' >&2; exit 1; } ;;
+ 504b0304*)
+ d=\$(mktemp -d) && unzip -q "\$f" -d "\$d" || { echo 'The zip backup cannot be extracted.' >&2; exit 1; }
+ [ "\$(find "\$d" -type f | wc -l | tr -d ' ')" = 1 ] || { echo 'A zip backup must contain exactly one file.' >&2; exit 1; }
+ mv "\$(find "\$d" -type f)" "\$out" ;;
+ *) mv "\$f" "\$out" ;;
+ esac
+ SH;
}
public function buildPostgresRestoreScanScript(object $resource, string $path): ?string
@@@ -110,11 -139,120 +141,134 @@@ SH
};
}
- private function mysqlDumpAll(string $binary, string $prefix, string $path): string
+ /**
+ * pg_dump custom and tar archives are restored with pg_restore, SQL dumps with psql.
+ * pg_restore cannot read gzip files, so both clients receive the backup on stdin.
+ * SQL cannot replace single objects, so replacing recreates the target database.
+ */
+ private function postgresqlSingle(bool $replaceExisting): string
{
- $rootPassword = '${'.$prefix.'_ROOT_PASSWORD}';
- $database = '${'.$prefix.'_DATABASE:-default}';
+ $clean = $replaceExisting ? ' --clean --if-exists' : '';
+ $sqlNotice = $replaceExisting ? <<<'SH'
+
+ echo 'SQL backups cannot replace single objects. The database is recreated before the restore.'
+ echo "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = :'db' AND pid <> pg_backend_pid();" | psql -v db="$db" -U $POSTGRES_USER -d template1 >/dev/null || exit 1
+ dropdb --maintenance-db=template1 -U $POSTGRES_USER --if-exists "$db" || exit 1
+ createdb -U $POSTGRES_USER "$db" || exit 1
+ SH : '';
- return "for pid in \$({$binary} -u root -p{$rootPassword} -N -e \"SELECT id FROM information_schema.processlist WHERE user != 'root';\"); do {$binary} -u root -p{$rootPassword} -e \"KILL \$pid\" 2>/dev/null || true; done && {$binary} -u root -p{$rootPassword} -N -e \"SELECT CONCAT('DROP DATABASE IF EXISTS \\`',schema_name,'\\`;') FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema','mysql','performance_schema','sys');\" | {$binary} -u root -p{$rootPassword} && {$binary} -u root -p{$rootPassword} -e \"CREATE DATABASE IF NOT EXISTS \\`{$database}\\`;\" && (gunzip -cf {$path} 2>/dev/null || cat {$path}) | {$binary} -u root -p{$rootPassword} {$database}";
+ return <<<SH
+ db=\${POSTGRES_DB:-\${POSTGRES_USER:-postgres}}
+ if [ "\$(stream | head -c 5)" = PGDMP ] || is_tar; then
+ stream | pg_restore --exit-on-error{$clean} -U \$POSTGRES_USER -d "\$db"
+ elif ! is_text; then
+ fail 'Unsupported PostgreSQL backup format. Use a pg_dump archive (custom or tar format) or an SQL file.'
+ elif stream | head -c 4096 | grep -q 'PostgreSQL database cluster dump'; then
+ fail 'This backup contains all databases. Select "Backup contains all databases" to restore it.'
+ else{$sqlNotice}
+ stream | psql -v ON_ERROR_STOP=1 -U \$POSTGRES_USER -d "\$db"
+ fi
+ SH;
+ }
+
+ /**
+ * Checks the backup format before any database is dropped, then recreates the
+ * target database and restores archives with pg_restore and SQL with psql.
+ */
+ private function postgresqlDumpAll(): string
+ {
+ return <<<'SH'
+ db=${POSTGRES_DB:-${POSTGRES_USER:-postgres}}
+ if [ "$(stream | head -c 5)" = PGDMP ] || is_tar; then
+ kind=archive
+ stream | pg_restore -l >/dev/null 2>&1 || fail 'pg_restore cannot read this backup archive. Nothing was changed.'
+ elif is_text; then
+ kind=sql
+ else
+ fail 'Unsupported PostgreSQL backup format. Use a pg_dump archive (custom or tar format) or an SQL file. Nothing was changed.'
+ fi
+ psql -U ${POSTGRES_USER} -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname IS NOT NULL AND pid <> pg_backend_pid()" || exit 1
+ psql -U ${POSTGRES_USER} -t -c "SELECT datname FROM pg_database WHERE NOT datistemplate" | xargs -I {} dropdb -U ${POSTGRES_USER} --if-exists {} || exit 1
+ createdb -U ${POSTGRES_USER} "$db" || exit 1
+ if [ "$kind" = archive ]; then
+ stream | pg_restore -U ${POSTGRES_USER} -d "$db"
+ else
+ stream | psql -U ${POSTGRES_USER} -d "$db"
+ fi
+ SH;
+ }
+
+ /**
+ * MySQL and MariaDB restore SQL dumps. A tar backup must wrap exactly one dump.
+ * The all-databases mode checks the backup before it drops any database.
+ */
+ private function mysql(string $binary, string $prefix, bool $dumpAll): string
+ {
+ $preflight = <<<'SH'
+ if is_tar; then
+ extract_tar
+ use_single_tar_member || fail 'A tar backup must contain exactly one SQL dump. Nothing was changed.'
+ fi
+ is_text || fail 'Unsupported backup format. Use an SQL dump. Nothing was changed.'
+
+ SH;
+
+ if (! $dumpAll) {
+ return $preflight.<<<SH
+ if [ "$(stream | grep -c '^USE `')" -gt 1 ]; then
+ fail 'This backup contains more than one database. Select "Backup contains all databases" to restore it. Nothing was changed.'
+ fi
+ stream | {$binary} -u \${$prefix}_USER -p\${$prefix}_PASSWORD \${$prefix}_DATABASE
+ SH;
+ }
+
+ $root = "{$binary} -u root -p\${{$prefix}_ROOT_PASSWORD}";
+ $database = "\${{$prefix}_DATABASE:-default}";
+
+ return $preflight.<<<SH
+ for pid in \$({$root} -N -e "SELECT id FROM information_schema.processlist WHERE user != 'root';"); do {$root} -e "KILL \$pid" 2>/dev/null || true; done
+ {$root} -N -e "SELECT CONCAT('DROP DATABASE IF EXISTS \\`',schema_name,'\\`;') FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema','mysql','performance_schema','sys');" | {$root} || exit 1
+ {$root} -e "CREATE DATABASE IF NOT EXISTS \\`{$database}\\`;" || exit 1
+ stream | {$root} {$database}
+ SH;
+ }
+
+ /**
+ * MongoDB restores mongodump archives (plain or gzip) and dump directories packed
+ * as tar. Replacing existing data drops each restored collection first.
+ */
+ private function mongodb(bool $replaceExisting): string
+ {
+ $drop = $replaceExisting ? ' --drop' : '';
+
+ return <<<SH
+ restore() { mongorestore --authenticationDatabase=admin --username \$MONGO_INITDB_ROOT_USERNAME --password \$MONGO_INITDB_ROOT_PASSWORD --uri mongodb://localhost:27017{$drop} "\$@"; }
+ if is_tar; then
+ extract_tar
+ if ! use_single_tar_member; then
+ bson=\$(find "\$work" -type f \\( -name '*.bson' -o -name '*.bson.gz' \\) | head -n 1)
+ [ -n "\$bson" ] || fail 'The tar backup does not contain a mongodump directory. Nothing was changed.'
+ root=\$(dirname "\$(dirname "\$bson")")
+ if find "\$root" -type f -name '*.bson.gz' | grep -q .; then restore --gzip --dir="\$root"; else restore --dir="\$root"; fi
+ exit \$?
+ fi
+ fi
+ [ "\$(header 4)" = 6de29981 ] || fail 'Unsupported MongoDB backup format. Use a mongodump archive or a dump directory packed as tar. Single .bson files are not supported. Nothing was changed.'
+ if is_gzip; then restore --gzip --archive="\$backup"; else restore --archive="\$backup"; fi
++SH;
++ }
++
++ /**
++ * SQLite restores a plain or gzip-compressed database file into the first database
++ * file with .restore, which replaces its contents.
++ */
++ private function sqlite(string $file): string
++ {
++ $file = escapeshellarg($file);
++
++ return <<<SH
++stream > "\$backup.db" || fail 'The backup cannot be read. Nothing was changed.'
++sqlite3 -bail {$file} '.timeout 10000' ".restore \$backup.db"; status=\$?; rm -f "\$backup.db"; exit \$status
+ SH;
}
}
diff --cc resources/views/livewire/project/database/import-form.blade.php
index dd2535a3a5,6c13fbbbcb..9dc671247b
--- a/resources/views/livewire/project/database/import-form.blade.php
+++ b/resources/views/livewire/project/database/import-form.blade.php
@@@ -61,38 -60,11 +60,12 @@@
The backup replaces PostgreSQL administrator role passwords, including the destination administrator password.
<span class="mt-1 block">If the administrator password changes, update it in Coolify's database configuration after the restore.</span>
</x-callout>
- <x-forms.textarea rows="6" readonly label="Import command"
- wire:model="restoreCommandText" canGate="update"
- :canResource="$this->resource" />
- @else
- <x-forms.input label="Import command" readonly
- helper="Enable replacement below to drop and recreate matching objects from the archive."
- wire:model="postgresqlRestoreCommand" canGate="update"
- :canResource="$this->resource" />
- @endif
- @elseif ($resourceDbType === 'standalone-mysql')
- @if ($dumpAll)
- <x-forms.textarea rows="10" readonly label="Import command"
- wire:model="restoreCommandText" canGate="update"
- :canResource="$this->resource" />
- @else
- <x-forms.input label="Import command" wire:model="mysqlRestoreCommand"
- canGate="update" :canResource="$this->resource" />
- @endif
- @elseif ($resourceDbType === 'standalone-mariadb')
- @if ($dumpAll)
+ @endif
<x-forms.textarea rows="10" readonly label="Import command"
+ helper="Coolify detects the backup format (SQL, archive, gzip, bz2, xz, zip, or tar) before it changes the database."
wire:model="restoreCommandText" canGate="update"
:canResource="$this->resource" />
- @else
- <x-forms.input label="Import command" wire:model="mariadbRestoreCommand"
- canGate="update" :canResource="$this->resource" />
- @endif
- @elseif ($resourceDbType === 'standalone-sqlite')
- <x-forms.input label="Import command" readonly wire:model="sqliteRestoreCommand"
- canGate="update" :canResource="$this->resource" />
- @endif
+ @if ($resourceDbType !== 'standalone-sqlite')
<div class="max-w-sm">
<x-forms.listbox id="dumpAll" label="Backup contents" live :options="[
['value' => true, 'label' => 'Backup contains all databases'],
diff --cc tests/Feature/StandaloneSqliteTest.php
index 31b1d6735b,0000000000..5e7b95f475
mode 100644,000000..100644
--- a/tests/Feature/StandaloneSqliteTest.php
+++ b/tests/Feature/StandaloneSqliteTest.php
@@@ -1,133 -1,0 +1,136 @@@
+<?php
+
+use App\Actions\Database\StartSqlite;
+use App\Livewire\Project\Database\Sqlite\General;
+use App\Models\Environment;
+use App\Models\InstanceSettings;
+use App\Models\Project;
+use App\Models\Server;
+use App\Models\StandaloneDocker;
+use App\Models\StandaloneSqlite;
+use App\Models\Team;
+use App\Models\User;
+use App\Services\DatabaseStartCommandExecutor;
+use App\Support\DatabaseImport\DatabaseImportCommandBuilder;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Livewire\Livewire;
+use Spatie\Activitylog\Models\Activity;
+use Symfony\Component\Yaml\Yaml;
+
+uses(RefreshDatabase::class);
+
+beforeEach(function () {
+ $this->team = Team::factory()->create();
+ $this->user = User::factory()->create();
+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);
+ session(['currentTeam' => $this->team]);
+ $this->server = Server::factory()->create(['team_id' => $this->team->id]);
+ $project = Project::factory()->create(['team_id' => $this->team->id]);
+ $this->environment = Environment::factory()->create(['project_id' => $project->id]);
+ $destination = StandaloneDocker::where('server_id', $this->server->id)->first();
+
+ $this->database = create_standalone_sqlite($this->environment->id, $destination, ['sqlite_databases' => 'app.db,jobs.db']);
+});
+
+function sqliteApiHeaders(): array
+{
+ InstanceSettings::forceCreate(['id' => 0, 'is_api_enabled' => true]);
+
+ return ['Authorization' => 'Bearer '.test()->user->createToken('test-token', ['*'])->plainTextToken];
+}
+
+it('creates the data volume and restores into the first configured file', function () {
+ expect($this->database->image)->toBe('peakimages/sqlite:3.53.4-v0.1.0')
+ ->and($this->database->databaseFilePath())->toBe('/var/lib/sqlite/app.db')
+ ->and($this->database->persistentStorages()->first()->mount_path)->toBe('/var/lib/sqlite');
+});
+
+it('only accepts plain comma-separated file names', function (string $value, bool $valid) {
+ expect((bool) preg_match(StandaloneSqlite::DATABASES_PATTERN, $value))->toBe($valid);
+})->with([
+ 'single file' => ['app.db', true],
+ 'several files' => ['app.db,jobs.sqlite', true],
+ 'path traversal' => ['../escape.db', false],
+ 'hidden file' => ['.app.db', false],
+ 'shell metacharacters' => ['app.db;id', false],
+ 'trailing comma' => ['app.db,', false],
+]);
+
+it('generates a compose file that passes the database files to the image', function () {
+ $commands = [];
+ $executor = Mockery::mock(DatabaseStartCommandExecutor::class);
+ $executor->shouldReceive('execute')->once()->withArgs(function (array $captured) use (&$commands) {
+ $commands = $captured;
+
+ return true;
+ })->andReturn(new Activity);
+ app()->instance(DatabaseStartCommandExecutor::class, $executor);
+
+ (new StartSqlite)->handle($this->database, new Activity);
+
+ preg_match("/^echo '([^']+)' \| base64 -d/", collect($commands)->first(fn (string $command) => str_contains($command, 'docker-compose.yml')), $matches);
+ $service = Yaml::parse(base64_decode($matches[1]))['services'][$this->database->uuid];
+
+ expect($service)->not->toHaveKey('command')
+ ->and($service['environment'])->toBe(['SQLITE_DATABASES=app.db,jobs.db'])
+ ->and($service['healthcheck']['test'])->toBe(['CMD', 'healthcheck.sh'])
+ ->and($service['volumes'])->toBe(['sqlite-data-'.$this->database->uuid.':/var/lib/sqlite']);
+});
+
+it('backs up with a read-only VACUUM INTO snapshot instead of a SQL dump', function () {
+ expect(file_get_contents(app_path('Jobs/DatabaseBackupJob.php')))
+ ->toContain('sqlite3 -readonly')
+ ->toContain('VACUUM INTO')
+ ->not->toContain('.dump');
+});
+
+it('restores a gzipped backup with .restore into the first database file', function () {
+ $command = app(DatabaseImportCommandBuilder::class)->buildRestoreCommand($this->database, '/tmp/restore_1', false);
+
- expect($command)->toBe('backup=\'/tmp/restore_1\'; gunzip -c "$backup" > "$backup.db" && sqlite3 -bail \'/var/lib/sqlite/app.db\' \'.timeout 10000\' ".restore $backup.db"; status=$?; rm -f "$backup.db"; exit $status');
++ expect($command)
++ ->toStartWith("backup='/tmp/restore_1'\n")
++ ->toContain('stream() { if is_gzip; then gunzip -c "$backup"; else cat "$backup"; fi; }')
++ ->toEndWith("stream > \"\$backup.db\" || fail 'The backup cannot be read. Nothing was changed.'\nsqlite3 -bail '/var/lib/sqlite/app.db' '.timeout 10000' \".restore \$backup.db\"; status=\$?; rm -f \"\$backup.db\"; exit \$status");
+});
+
+it('normalises the file list when saved from the general page', function () {
+ Livewire::actingAs($this->user)
+ ->test(General::class, ['database' => $this->database])
+ ->set('sqliteDatabases', 'app.db, cache.db')
+ ->call('submit')
+ ->assertHasNoErrors();
+
+ expect($this->database->refresh()->sqlite_databases)->toBe('app.db,cache.db');
+});
+
+it('creates a sqlite database through the API without public access fields', function () {
+ $headers = sqliteApiHeaders();
+ $payload = [
+ 'server_uuid' => $this->server->uuid,
+ 'project_uuid' => $this->environment->project->uuid,
+ 'environment_uuid' => $this->environment->uuid,
+ 'sqlite_databases' => 'main.db',
+ ];
+
+ $response = $this->withHeaders($headers)->postJson('/api/v1/databases/sqlite', $payload)->assertStatus(201);
+
+ expect(StandaloneSqlite::where('uuid', $response->json('uuid'))->value('sqlite_databases'))->toBe('main.db');
+
+ $this->withHeaders($headers)
+ ->postJson('/api/v1/databases/sqlite', $payload + ['is_public' => true, 'public_port' => 5432])
+ ->assertStatus(422);
+});
+
+it('updates the database files through the API and rejects unsafe names', function () {
+ $headers = sqliteApiHeaders();
+
+ $this->withHeaders($headers)
+ ->patchJson("/api/v1/databases/{$this->database->uuid}", ['sqlite_databases' => 'jobs.sqlite'])
+ ->assertStatus(200);
+
+ expect($this->database->refresh()->sqlite_databases)->toBe('jobs.sqlite');
+
+ $this->withHeaders($headers)
+ ->patchJson("/api/v1/databases/{$this->database->uuid}", ['sqlite_databases' => '../escape.db'])
+ ->assertStatus(422);
+});