Skip to content

Commit

Permalink
Merge pull request #2944 from drizzle-team/drizzle-kit/checks
Browse files Browse the repository at this point in the history
Drizzle kit/checks
  • Loading branch information
AndriiSherman authored Oct 14, 2024
2 parents 8c3e1b5 + 5168c83 commit 1f0b52f
Show file tree
Hide file tree
Showing 42 changed files with 2,963 additions and 46 deletions.
9 changes: 9 additions & 0 deletions drizzle-kit/src/cli/commands/libSqlPushUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,17 @@ export const _moveDataStatements = (
const compositePKs = Object.values(
json.tables[tableName].compositePrimaryKeys,
).map((it) => SQLiteSquasher.unsquashPK(it));
const checkConstraints = Object.values(json.tables[tableName].checkConstraints);

const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));

const mappedCheckConstraints: string[] = checkConstraints.map((it) =>
it.replaceAll(`"${tableName}".`, `"${newTableName}".`)
.replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`)
.replaceAll(`${tableName}.`, `${newTableName}.`)
.replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
);

// create new table
statements.push(
new SQLiteCreateTableConvertor().convert({
Expand All @@ -51,6 +59,7 @@ export const _moveDataStatements = (
columns: tableColumns,
referenceData: fks,
compositePKs,
checkConstraints: mappedCheckConstraints,
}),
);

Expand Down
9 changes: 9 additions & 0 deletions drizzle-kit/src/cli/commands/sqlitePushUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ export const _moveDataStatements = (
const compositePKs = Object.values(
json.tables[tableName].compositePrimaryKeys,
).map((it) => SQLiteSquasher.unsquashPK(it));
const checkConstraints = Object.values(json.tables[tableName].checkConstraints);

const mappedCheckConstraints: string[] = checkConstraints.map((it) =>
it.replaceAll(`"${tableName}".`, `"${newTableName}".`)
.replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`)
.replaceAll(`${tableName}.`, `${newTableName}.`)
.replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
);

const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));

Expand All @@ -38,6 +46,7 @@ export const _moveDataStatements = (
columns: tableColumns,
referenceData: fks,
compositePKs,
checkConstraints: mappedCheckConstraints,
}),
);

Expand Down
7 changes: 7 additions & 0 deletions drizzle-kit/src/cli/views.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ export type IntrospectStage =
| 'columns'
| 'enums'
| 'indexes'
| 'checks'
| 'fks'
| 'views';
type IntrospectState = {
Expand Down Expand Up @@ -370,6 +371,11 @@ export class IntrospectProgress extends TaskView {
name: 'foreign keys',
status: 'fetching',
},
checks: {
count: 0,
name: 'check constraints',
status: 'fetching',
},
views: {
count: 0,
name: 'views',
Expand Down Expand Up @@ -428,6 +434,7 @@ export class IntrospectProgress extends TaskView {
info += this.hasEnums ? this.statusText(spin, this.state.enums) : '';
info += this.statusText(spin, this.state.indexes);
info += this.statusText(spin, this.state.fks);
info += this.statusText(spin, this.state.checks);
info += this.statusText(spin, this.state.views);

return info;
Expand Down
29 changes: 29 additions & 0 deletions drizzle-kit/src/introspect-mysql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import './@types/utils';
import type { Casing } from './cli/validations/common';
import { assertUnreachable } from './global';
import {
CheckConstraint,
Column,
ForeignKey,
Index,
Expand Down Expand Up @@ -155,11 +156,15 @@ export const schemaToTypeScript = (
const uniqueImports = Object.values(it.uniqueConstraints).map(
(it) => 'unique',
);
const checkImports = Object.values(it.checkConstraint).map(
(it) => 'check',
);

res.mysql.push(...idxImports);
res.mysql.push(...fkImpots);
res.mysql.push(...pkImports);
res.mysql.push(...uniqueImports);
res.mysql.push(...checkImports);

const columnImports = Object.values(it.columns)
.map((col) => {
Expand Down Expand Up @@ -242,6 +247,7 @@ export const schemaToTypeScript = (
|| filteredFKs.length > 0
|| Object.keys(table.compositePrimaryKeys).length > 0
|| Object.keys(table.uniqueConstraints).length > 0
|| Object.keys(table.checkConstraint).length > 0
) {
statement += ',\n';
statement += '(table) => {\n';
Expand All @@ -260,6 +266,10 @@ export const schemaToTypeScript = (
Object.values(table.uniqueConstraints),
withCasing,
);
statement += createTableChecks(
Object.values(table.checkConstraint),
withCasing,
);
statement += '\t}\n';
statement += '}';
}
Expand Down Expand Up @@ -913,6 +923,25 @@ const createTableUniques = (
return statement;
};

const createTableChecks = (
checks: CheckConstraint[],
casing: (value: string) => string,
): string => {
let statement = '';

checks.forEach((it) => {
const checkKey = casing(it.name);

statement += `\t\t${checkKey}: `;
statement += 'check(';
statement += `"${it.name}", `;
statement += `sql\`${it.value.replace(/`/g, '\\`')}\`)`;
statement += `,\n`;
});

return statement;
};

const createTablePKs = (
pks: PrimaryKey[],
casing: (value: string) => string,
Expand Down
45 changes: 41 additions & 4 deletions drizzle-kit/src/introspect-pg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { Casing } from './cli/validations/common';
import { vectorOps } from './extensions/vector';
import { assertUnreachable } from './global';
import {
CheckConstraint,
Column,
ForeignKey,
Index,
Expand Down Expand Up @@ -334,6 +335,10 @@ export const schemaToTypeScript = (schema: PgSchemaInternal, casing: Casing) =>
const pkImports = Object.values(it.compositePrimaryKeys).map((it) => 'primaryKey');
const uniqueImports = Object.values(it.uniqueConstraints).map((it) => 'unique');

const checkImports = Object.values(it.checkConstraints).map(
(it) => 'check',
);

if (it.schema && it.schema !== 'public' && it.schema !== '') {
res.pg.push('pgSchema');
}
Expand All @@ -342,6 +347,7 @@ export const schemaToTypeScript = (schema: PgSchemaInternal, casing: Casing) =>
res.pg.push(...fkImpots);
res.pg.push(...pkImports);
res.pg.push(...uniqueImports);
res.pg.push(...checkImports);

const columnImports = Object.values(it.columns)
.map((col) => {
Expand Down Expand Up @@ -495,16 +501,29 @@ export const schemaToTypeScript = (schema: PgSchemaInternal, casing: Casing) =>
// });

if (
Object.keys(table.indexes).length > 0 || Object.values(table.foreignKeys).length > 0
|| Object.keys(table.compositePrimaryKeys).length > 0 || Object.keys(table.uniqueConstraints).length > 0
Object.keys(table.indexes).length > 0
|| Object.values(table.foreignKeys).length > 0
|| Object.keys(table.compositePrimaryKeys).length > 0
|| Object.keys(table.uniqueConstraints).length > 0
|| Object.keys(table.checkConstraints).length > 0
) {
statement += ',\n';
statement += '(table) => {\n';
statement += '\treturn {\n';
statement += createTableIndexes(table.name, Object.values(table.indexes), casing);
statement += createTableFKs(Object.values(table.foreignKeys), schemas, casing);
statement += createTablePKs(Object.values(table.compositePrimaryKeys), casing);
statement += createTableUniques(Object.values(table.uniqueConstraints), casing);
statement += createTablePKs(
Object.values(table.compositePrimaryKeys),
casing,
);
statement += createTableUniques(
Object.values(table.uniqueConstraints),
casing,
);
statement += createTableChecks(
Object.values(table.checkConstraints),
casing,
);
statement += '\t}\n';
statement += '}';
}
Expand Down Expand Up @@ -1225,6 +1244,24 @@ const createTableUniques = (unqs: UniqueConstraint[], casing: Casing): string =>
return statement;
};

const createTableChecks = (
checkConstraints: CheckConstraint[],
casing: Casing,
) => {
let statement = '';

checkConstraints.forEach((it) => {
const checkKey = withCasing(it.name, casing);
statement += `\t\t${checkKey}: `;
statement += 'check(';
statement += `"${it.name}", `;
statement += `sql\`${it.value}\`)`;
statement += `,\n`;
});

return statement;
};

const createTableFKs = (fks: ForeignKey[], schemas: Record<string, string>, casing: Casing): string => {
let statement = '';

Expand Down
28 changes: 28 additions & 0 deletions drizzle-kit/src/introspect-sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { toCamelCase } from 'drizzle-orm/casing';
import './@types/utils';
import type { Casing } from './cli/validations/common';
import { assertUnreachable } from './global';
import { CheckConstraint } from './serializer/mysqlSchema';
import type {
Column,
ForeignKey,
Expand Down Expand Up @@ -91,11 +92,15 @@ export const schemaToTypeScript = (
const uniqueImports = Object.values(it.uniqueConstraints).map(
(it) => 'unique',
);
const checkImports = Object.values(it.checkConstraints).map(
(it) => 'check',
);

res.sqlite.push(...idxImports);
res.sqlite.push(...fkImpots);
res.sqlite.push(...pkImports);
res.sqlite.push(...uniqueImports);
res.sqlite.push(...checkImports);

const columnImports = Object.values(it.columns)
.map((col) => {
Expand Down Expand Up @@ -154,6 +159,7 @@ export const schemaToTypeScript = (
|| filteredFKs.length > 0
|| Object.keys(table.compositePrimaryKeys).length > 0
|| Object.keys(table.uniqueConstraints).length > 0
|| Object.keys(table.checkConstraints).length > 0
) {
statement += ',\n';
statement += '(table) => {\n';
Expand All @@ -172,6 +178,10 @@ export const schemaToTypeScript = (
Object.values(table.uniqueConstraints),
casing,
);
statement += createTableChecks(
Object.values(table.checkConstraints),
casing,
);
statement += '\t}\n';
statement += '}';
}
Expand Down Expand Up @@ -457,6 +467,24 @@ const createTableUniques = (

return statement;
};
const createTableChecks = (
checks: CheckConstraint[],
casing: Casing,
): string => {
let statement = '';

checks.forEach((it) => {
const checkKey = withCasing(it.name, casing);

statement += `\t\t${checkKey}: `;
statement += 'check(';
statement += `"${it.name}", `;
statement += `sql\`${it.value}\`)`;
statement += `,\n`;
});

return statement;
};

const createTablePKs = (pks: PrimaryKey[], casing: Casing): string => {
let statement = '';
Expand Down
49 changes: 49 additions & 0 deletions drizzle-kit/src/jsonDiffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,24 @@ const findAlternationsInTable = (table) => {
}),
);

const addedCheckConstraints = Object.fromEntries(
Object.entries(table.checkConstraints || {}).filter((it) => {
return it[0].endsWith('__added');
}),
);

const deletedCheckConstraints = Object.fromEntries(
Object.entries(table.checkConstraints || {}).filter((it) => {
return it[0].endsWith('__deleted');
}),
);

const alteredCheckConstraints = Object.fromEntries(
Object.entries(table.checkConstraints || {}).filter((it) => {
return !it[0].endsWith('__deleted') && !it[0].endsWith('__added');
}),
);

const mappedAltered = altered.map((it) => alternationsInColumn(it)).filter(Boolean);

return {
Expand All @@ -445,11 +463,15 @@ const findAlternationsInTable = (table) => {
addedUniqueConstraints,
deletedUniqueConstraints,
alteredUniqueConstraints,
addedCheckConstraints,
deletedCheckConstraints,
alteredCheckConstraints,
};
};

const alternationsInColumn = (column) => {
const altered = [column];

const result = altered
.filter((it) => {
if ('type' in it && it.type.__old.replace(' (', '(') === it.type.__new.replace(' (', '(')) {
Expand Down Expand Up @@ -713,6 +735,33 @@ const alternationsInColumn = (column) => {
}
return it;
})
.map((it) => {
if ('' in it) {
return {
...it,
autoincrement: {
type: 'changed',
old: it.autoincrement.__old,
new: it.autoincrement.__new,
},
};
}
if ('autoincrement__added' in it) {
const { autoincrement__added, ...others } = it;
return {
...others,
autoincrement: { type: 'added', value: it.autoincrement__added },
};
}
if ('autoincrement__deleted' in it) {
const { autoincrement__deleted, ...others } = it;
return {
...others,
autoincrement: { type: 'deleted', value: it.autoincrement__deleted },
};
}
return it;
})
.filter(Boolean);

return result[0];
Expand Down
Loading

0 comments on commit 1f0b52f

Please sign in to comment.