0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-02-03 22:29:08 -05:00

feat: add foreignkeys to create table

This commit is contained in:
bholmesdev 2024-02-01 17:01:35 -05:00
parent a016e67a3c
commit 338a1afb5c
2 changed files with 36 additions and 2 deletions

View file

@ -87,6 +87,8 @@ export function getCreateTableQuery(collectionName: string, collection: DBCollec
colQueries.push(colQuery);
}
colQueries.push(...getCreateForeignKeyQueries(collectionName, collection));
query += colQueries.join(', ') + ')';
return query;
}
@ -97,7 +99,7 @@ export function getCreateIndexQueries(
) {
let queries: string[] = [];
for (const [indexName, indexProps] of Object.entries(collection.indexes ?? {})) {
const onColNames = Array.isArray(indexProps.on) ? indexProps.on : [indexProps.on];
const onColNames = asArray(indexProps.on);
const onCols = onColNames.map((colName) => sqlite.escapeName(colName));
const unique = indexProps.unique ? 'UNIQUE ' : '';
@ -109,6 +111,37 @@ export function getCreateIndexQueries(
return queries;
}
export function getCreateForeignKeyQueries(collectionName: string, collection: DBCollection) {
let queries: string[] = [];
for (const foreignKey of collection.foreignKeys ?? []) {
const fields = asArray(foreignKey.fields);
const references = asArray(foreignKey.references());
if (fields.length !== references.length) {
throw new Error(
`Foreign key on ${collectionName} is misconfigured. \`fields\` and \`references\` must be the same length.`
);
}
const referencedCollection = references[0]?.collection;
if (!referencedCollection) {
throw new Error(
`Foreign key on ${collectionName} is misconfigured. \`references\` cannot be empty.`
);
}
const query = `FOREIGN KEY (${fields
.map((f) => sqlite.escapeName(f))
.join(', ')}) REFERENCES ${sqlite.escapeName(referencedCollection)}(${references
.map((r) => sqlite.escapeName(r.name!))
.join(', ')})`;
queries.push(query);
}
return queries;
}
function asArray<T>(value: T | T[]) {
return Array.isArray(value) ? value : [value];
}
export function schemaTypeToSqlType(type: FieldType): 'text' | 'integer' {
switch (type) {
case 'date':

View file

@ -14,11 +14,12 @@ const Ingredient = defineCollection({
id: field.number({ primaryKey: true }),
name: field.text(),
quantity: field.number(),
recipeId: field.text({ references: () => Recipe.fields.id }),
recipeId: field.number(),
},
indexes: {
recipeIdx: { on: 'recipeId' },
},
foreignKeys: [{ fields: 'recipeId', references: () => [Recipe.fields.id] }],
});
export default defineConfig({