Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow adding and updating fields with expressions in default values #60

Merged
merged 6 commits into from
Feb 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/utils/field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ export const diffFields = async (
fieldsToAdd,
modelSlug,
definedFields,
existingFields,
options,
);

Expand Down Expand Up @@ -352,6 +353,7 @@ export const createFields = async (
fields: Array<ModelField>,
modelSlug: string,
definedFields?: Array<ModelField>,
existingFields?: Array<ModelField>,
options?: MigrationOptions,
): Promise<Array<string>> => {
const diff: Array<string> = [];
Expand Down Expand Up @@ -401,6 +403,7 @@ export const createFields = async (
},
);
}

// Handle required fields by prompting for default value since SQLite doesn't allow
// adding NOT NULL columns without defaults.
if (fieldToAdd.required && !fieldToAdd.defaultValue) {
Expand All @@ -425,9 +428,25 @@ export const createFields = async (
);
return diff;
}

// If the field contains an expression as default value, we need to create a temporary
// model with the existing fields and the new field.
if (fieldToAdd.defaultValue && typeof fieldToAdd.defaultValue === 'object') {
diff.push(
...createTempModelQuery(
{
slug: modelSlug,
// @ts-expect-error This will work once the types are fixed.
fields: convertArrayToObject(definedFields),
},
{ includeFields: existingFields },
),
);
return diff;
}

diff.push(createFieldQuery(modelSlug, fieldToAdd));
}

return diff;
};

Expand Down
4 changes: 2 additions & 2 deletions src/utils/migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ import type { Model } from '@ronin/compiler';
/**
* Options for migration operations.
*/
export type MigrationOptions = {
export interface MigrationOptions {
rename?: boolean;
requiredDefault?: boolean | string;
name?: string;
pluralName?: string;
};
}

/**
* Fields to ignore.
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export const runMigration = async (
* @returns The number of records in the table.
*/
export const getRowCount = async (db: Database, modelSlug: string): Promise<number> => {
const res = await db.query([`SELECT COUNT(*) FROM ${modelSlug};`]);
const res = await db.query([`SELECT COUNT(*) FROM "${modelSlug}";`]);
return res[0].rows[0]['COUNT(*)'];
};

Expand Down
99 changes: 95 additions & 4 deletions tests/utils/apply.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import {
import { getRowCount, getSQLTables, getTableRows, runMigration } from '@/fixtures/utils';
import { getLocalPackages } from '@/src/utils/misc';
import type { Model } from 'ronin/schema';
import { model, string } from 'ronin/schema';
import { model, number, random, string } from 'ronin/schema';
const packages = await getLocalPackages();
const { Transaction } = packages.compiler;

Expand Down Expand Up @@ -348,6 +348,48 @@ describe('apply', () => {
tests: 0,
});
});

test('add field with expression as default value', async () => {
const ModelA = model({
slug: 'a',
fields: {
name: string(),
},
}) as unknown as Model;

const ModelB = model({
slug: 'a',
fields: {
name: string(),
age: number().defaultValue(() => random()),
},
}) as unknown as Model;

// @ts-expect-error This works once the types are fixed.
const { models, db, modelDiff } = await runMigration([ModelB], [ModelA], {
requiredDefault: 'RONIN_TEST_VALUE',
});

const rowCounts: Record<string, number> = {};
for (const model of models) {
if (model.pluralSlug) {
rowCounts[model.pluralSlug] = await getRowCount(db, model.pluralSlug);
}
}

expect(modelDiff[0]).toContain(
'create.model({"slug":"RONIN_TEMP_a","fields":{"name":{"type":"string"},"age":{"type":"number","defaultValue":{"__RONIN_EXPRESSION":"random()"}}}})',
);

expect(models).toHaveLength(1);
// @ts-expect-error This is defined!
expect(models[0]?.fields[1].defaultValue).toEqual({
__RONIN_EXPRESSION: 'random()',
});
expect(rowCounts).toEqual({
as: 0,
});
});
});

describe('drop', () => {
Expand Down Expand Up @@ -426,6 +468,49 @@ describe('apply', () => {
tests: 0,
});
});

test('update field with expression as default value', async () => {
const ModelA = model({
slug: 'a',
fields: {
name: string(),
age: number().defaultValue(() => 25),
},
}) as unknown as Model;

const ModelB = model({
slug: 'a',
fields: {
name: string(),
age: number().defaultValue(() => random()),
},
}) as unknown as Model;

// @ts-expect-error This works once the types are fixed.
const { models, db, modelDiff } = await runMigration([ModelB], [ModelA], {
requiredDefault: 'RONIN_TEST_VALUE',
});

const rowCounts: Record<string, number> = {};
for (const model of models) {
if (model.pluralSlug) {
rowCounts[model.pluralSlug] = await getRowCount(db, model.pluralSlug);
}
}

expect(modelDiff[0]).toContain(
'alter.model(\'a\').create.field({"slug":"RONIN_TEMP_age","type":"number","defaultValue":{"__RONIN_EXPRESSION":"random()"}})',
);

expect(models).toHaveLength(1);
// @ts-expect-error This is defined!
expect(models[0]?.fields[1].defaultValue).toEqual({
__RONIN_EXPRESSION: 'random()',
});
expect(rowCounts).toEqual({
as: 0,
});
});
});
});

Expand Down Expand Up @@ -503,6 +588,7 @@ describe('apply', () => {
expect(rowCounts).toEqual({
accounts: 1,
});

expect(rows[0].email).toBe('RONIN_TEST_VALUE');
});

Expand All @@ -522,24 +608,29 @@ describe('apply', () => {
inlineParams: true,
});

const { models, db } = await runMigration(
const { models, db, modelDiff } = await runMigration(
[AccountWithRequiredDefault],
[Account],
{ rename: false, requiredDefault: 'RONIN_TEST_VALUE' },
transaction.statements.map((statement) => statement),
);

const rows = await getTableRows(db, Account3);
await db.query(transaction.statements);

const rows = await getTableRows(db, AccountWithRequiredDefault);

const rowCounts: Record<string, number> = {};
for (const model of models) {
if (model.pluralSlug) {
rowCounts[model.pluralSlug] = await getRowCount(db, model.pluralSlug);
}
}

expect(modelDiff).toHaveLength(1);
expect(rowCounts).toEqual({
accounts: 1,
accounts: 2,
});

expect(rows[0].email).toBe('RONIN_TEST_VALUE_REQUIRED_DEFAULT');
});

Expand Down
Loading