From 06f96661af7f756f6e0289c67c55247d4ec36b4b Mon Sep 17 00:00:00 2001 From: bholmesdev Date: Thu, 1 Feb 2024 18:07:45 -0500 Subject: [PATCH] chore: enable foreign keys in local mode only --- packages/db/src/core/integration/index.ts | 1 + packages/db/src/core/queries.ts | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/db/src/core/integration/index.ts b/packages/db/src/core/integration/index.ts index 995f7863e9..7679d0f643 100644 --- a/packages/db/src/core/integration/index.ts +++ b/packages/db/src/core/integration/index.ts @@ -71,6 +71,7 @@ function astroDBIntegration(): AstroIntegration { data: configWithDb.db?.data, logger, mode: command === 'dev' ? 'dev' : 'build', + useForeignKeys: true, }); logger.info('Collections set up 🚀'); diff --git a/packages/db/src/core/queries.ts b/packages/db/src/core/queries.ts index 28e155206d..280a2339e2 100644 --- a/packages/db/src/core/queries.ts +++ b/packages/db/src/core/queries.ts @@ -25,17 +25,20 @@ export async function setupDbTables({ collections, logger, mode, + // TODO: Remove once Turso has foreign key PRAGMA support + useForeignKeys = false, }: { db: SqliteRemoteDatabase; data?: DBUserConfig['data']; collections: DBCollections; logger?: AstroIntegrationLogger; mode: 'dev' | 'build'; + useForeignKeys?: boolean; }) { const setupQueries: SQL[] = []; for (const [name, collection] of Object.entries(collections)) { const dropQuery = sql.raw(`DROP TABLE IF EXISTS ${name}`); - const createQuery = sql.raw(getCreateTableQuery(name, collection)); + const createQuery = sql.raw(getCreateTableQuery(name, collection, useForeignKeys)); const indexQueries = getCreateIndexQueries(name, collection); setupQueries.push(dropQuery, createQuery, ...indexQueries.map((s) => sql.raw(s))); } @@ -70,7 +73,12 @@ export async function setupDbTables({ } } -export function getCreateTableQuery(collectionName: string, collection: DBCollection) { +export function getCreateTableQuery( + collectionName: string, + collection: DBCollection, + // TODO: Remove once Turso has foreign key PRAGMA support + useForeignKeys = false +) { let query = `CREATE TABLE ${sqlite.escapeName(collectionName)} (`; const colQueries = []; @@ -87,7 +95,9 @@ export function getCreateTableQuery(collectionName: string, collection: DBCollec colQueries.push(colQuery); } - colQueries.push(...getCreateForeignKeyQueries(collectionName, collection)); + if (useForeignKeys) { + colQueries.push(...getCreateForeignKeyQueries(collectionName, collection)); + } query += colQueries.join(', ') + ')'; return query;