Skip to content

Commit

Permalink
fix(schema): improve json default diffing for down migrations
Browse files Browse the repository at this point in the history
  • Loading branch information
B4nan committed Dec 15, 2023
1 parent 84d42a7 commit 5bc19ba
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
16 changes: 14 additions & 2 deletions packages/knex/src/schema/SchemaComparator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,18 @@ export class SchemaComparator {
return simplify(check1.expression as string) !== simplify(check2.expression as string);
}

parseJsonDefault(defaultValue?: string | null): Dictionary | string | null {
if (!defaultValue) {
return null;
}

const val = defaultValue
.replace(/^(_\w+\\)?'(.*?)\\?'$/, '$2')
.replace(/^\(?'(.*?)'\)?$/, '$1');

return parseJsonSafe(val);
}

hasSameDefaultValue(from: Column, to: Column): boolean {
if (from.default == null || from.default.toString().toLowerCase() === 'null' || from.default.toString().startsWith('nextval(')) {
return to.default == null || to.default!.toLowerCase() === 'null';
Expand All @@ -562,8 +574,8 @@ export class SchemaComparator {
}

if (to.mappedType instanceof JsonType) {
const defaultValueFrom = parseJsonSafe(from.default.replace(/^(_\w+\\)?'(.*?)\\?'$/, '$2'));
const defaultValueTo = parseJsonSafe(to.default?.replace(/^\(?'(.*?)'\)?$/, '$1'));
const defaultValueFrom = this.parseJsonDefault(from.default);
const defaultValueTo = this.parseJsonDefault(to.default);

return Utils.equals(defaultValueFrom, defaultValueTo);
}
Expand Down
7 changes: 5 additions & 2 deletions tests/features/schema-generator/json-diffing.mysql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ beforeAll(async () => {
afterAll(() => orm.close(true));

test('default values on json columns', async () => {
const diff1 = await orm.schema.getUpdateSchemaSQL({ wrap: false });
expect(diff1).toBe('');
const diff1 = await orm.schema.getUpdateSchemaMigrationSQL({ wrap: false });
expect(diff1).toEqual({
up: '',
down: '',
});
});

0 comments on commit 5bc19ba

Please sign in to comment.