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

Batch of bugfixes for Kit #2959

Merged
merged 26 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
3b327ac
Escape single quote in enum value
L-Mario564 Sep 9, 2024
b45dbfb
Escape single quotes in string default values
L-Mario564 Sep 9, 2024
0e7d2a4
Handle instrospection of strings with single quotes
L-Mario564 Sep 9, 2024
9673cf2
Add tests
L-Mario564 Sep 9, 2024
714eeca
Add tests
L-Mario564 Sep 9, 2024
81f3d52
Uncomment tests
L-Mario564 Sep 9, 2024
5a759ba
Fix SQL statement order in MySQL
L-Mario564 Sep 9, 2024
eae9d9a
Add MySQL test
L-Mario564 Sep 9, 2024
a22584b
Fix alter composite PK statement missing quotes in PG
L-Mario564 Sep 9, 2024
e20a9ff
Add tests
L-Mario564 Sep 10, 2024
001175d
Handle SQL expressions in timestamp, date and time in PG
L-Mario564 Sep 10, 2024
0e392d6
Use `.run` instead of `.query` in SQLite queries that don't return an…
L-Mario564 Sep 10, 2024
7cb1eb6
Fix parsing of enum array types in PG
L-Mario564 Sep 10, 2024
a6f3dcb
Generate more PG index operators
L-Mario564 Sep 10, 2024
aaf7040
Fix primary key recreate on table rename
L-Mario564 Sep 12, 2024
9653489
Format
L-Mario564 Sep 12, 2024
3804b57
Merge remote-tracking branch 'upstream/beta' into kit-bugfixes
L-Mario564 Oct 7, 2024
ad967af
Format
L-Mario564 Oct 7, 2024
f5a9984
Update test
L-Mario564 Oct 7, 2024
f2fe0e2
Merge remote-tracking branch 'upstream/beta' into kit-bugfixes
L-Mario564 Nov 4, 2024
a3a1a41
Format
L-Mario564 Nov 4, 2024
314865a
Fix tests
L-Mario564 Nov 4, 2024
de61fe9
Fix terminal output mistake
L-Mario564 Nov 5, 2024
7361140
Merge branch 'beta' into kit-bugfixes
AndriiSherman Nov 6, 2024
6dbad9b
Remove duplicate import
L-Mario564 Nov 6, 2024
bd61c5e
Merge branch 'kit-bugfixes' of https://github.com/L-Mario564/drizzle-…
L-Mario564 Nov 6, 2024
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
8 changes: 4 additions & 4 deletions drizzle-kit/src/cli/commands/push.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,15 +383,15 @@ export const sqlitePush = async (
render(`\n[${chalk.blue('i')}] No changes detected`);
} else {
if (!('driver' in credentials)) {
await db.query('begin');
await db.run('begin');
try {
for (const dStmnt of statementsToExecute) {
await db.query(dStmnt);
await db.run(dStmnt);
}
await db.query('commit');
await db.run('commit');
} catch (e) {
console.error(e);
await db.query('rollback');
await db.run('rollback');
process.exit(1);
}
}
Expand Down
2 changes: 1 addition & 1 deletion drizzle-kit/src/cli/validations/outputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const outputs = {
),
noDialect: () =>
withStyle.error(
`Please specify 'dialect' param in config, either of 'pg', 'mysql' or 'sqlite'`,
`Please specify 'dialect' param in config, either of 'postgresql', 'mysql', 'sqlite' or 'turso'`,
),
},
common: {
Expand Down
13 changes: 10 additions & 3 deletions drizzle-kit/src/introspect-mysql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
UniqueConstraint,
} from './serializer/mysqlSchema';
import { indexName } from './serializer/mysqlSerializer';
import { unescapeSingleQuotes } from './utils';

// time precision to fsp
// {mode: "string"} for timestamp by default
Expand Down Expand Up @@ -679,8 +680,9 @@ const column = (
)
} })`;

const mappedDefaultValue = mapColumnDefault(defaultValue, isExpression);
out += defaultValue
? `.default(${mapColumnDefault(defaultValue, isExpression)})`
? `.default(${isExpression ? mappedDefaultValue : unescapeSingleQuotes(mappedDefaultValue, true)})`
: '';
return out;
}
Expand Down Expand Up @@ -787,10 +789,15 @@ const column = (
}

if (lowered.startsWith('enum')) {
const values = lowered.substring('enum'.length + 1, lowered.length - 1);
const values = lowered
.substring('enum'.length + 1, lowered.length - 1)
.split(',')
.map((v) => unescapeSingleQuotes(v, true))
.join(',');
let out = `${casing(name)}: mysqlEnum(${dbColumnName({ name, casing: rawCasing, withMode: true })}[${values}])`;
const mappedDefaultValue = mapColumnDefault(defaultValue, isExpression);
out += defaultValue
? `.default(${mapColumnDefault(defaultValue, isExpression)})`
? `.default(${isExpression ? mappedDefaultValue : unescapeSingleQuotes(mappedDefaultValue, true)})`
: '';
return out;
}
Expand Down
42 changes: 28 additions & 14 deletions drizzle-kit/src/introspect-pg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
import './@types/utils';
import { toCamelCase } from 'drizzle-orm/casing';
import { Casing } from './cli/validations/common';
import { vectorOps } from './extensions/vector';
import { assertUnreachable } from './global';
import {
CheckConstraint,
Expand All @@ -25,6 +24,7 @@ import {
UniqueConstraint,
} from './serializer/pgSchema';
import { indexName } from './serializer/pgSerializer';
import { unescapeSingleQuotes } from './utils';

const pgImportsList = new Set([
'pgTable',
Expand Down Expand Up @@ -436,7 +436,7 @@ export const schemaToTypeScript = (schema: PgSchemaInternal, casing: Casing) =>
const func = enumSchema ? `${enumSchema}.enum` : 'pgEnum';

const values = Object.values(it.values)
.map((it) => `'${it}'`)
.map((it) => `'${unescapeSingleQuotes(it, false)}'`)
.join(', ');
return `export const ${withCasing(paramName, casing)} = ${func}("${it.name}", [${values}])\n`;
})
Expand Down Expand Up @@ -690,7 +690,9 @@ const mapDefault = (
}

if (enumTypes.has(`${typeSchema}.${type.replace('[]', '')}`)) {
return typeof defaultValue !== 'undefined' ? `.default(${mapColumnDefault(defaultValue, isExpression)})` : '';
return typeof defaultValue !== 'undefined'
? `.default(${mapColumnDefault(unescapeSingleQuotes(defaultValue, true), isExpression)})`
: '';
}

if (lowered.startsWith('integer')) {
Expand Down Expand Up @@ -737,18 +739,20 @@ const mapDefault = (
if (lowered.startsWith('timestamp')) {
return defaultValue === 'now()'
? '.defaultNow()'
: defaultValue === 'CURRENT_TIMESTAMP'
? '.default(sql`CURRENT_TIMESTAMP`)'
: defaultValue
: /^'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d+)?([+-]\d{2}(:\d{2})?)?'$/.test(defaultValue) // Matches 'YYYY-MM-DD HH:MI:SS', 'YYYY-MM-DD HH:MI:SS.FFFFFF', 'YYYY-MM-DD HH:MI:SS+TZ', 'YYYY-MM-DD HH:MI:SS.FFFFFF+TZ' and 'YYYY-MM-DD HH:MI:SS+HH:MI'
? `.default(${mapColumnDefault(defaultValue, isExpression)})`
: defaultValue
? `.default(sql\`${defaultValue}\`)`
: '';
}

if (lowered.startsWith('time')) {
return defaultValue === 'now()'
? '.defaultNow()'
: defaultValue
: /^'\d{2}:\d{2}(:\d{2})?(\.\d+)?'$/.test(defaultValue) // Matches 'HH:MI', 'HH:MI:SS' and 'HH:MI:SS.FFFFFF'
? `.default(${mapColumnDefault(defaultValue, isExpression)})`
: defaultValue
? `.default(sql\`${defaultValue}\`)`
: '';
}

Expand All @@ -759,15 +763,17 @@ const mapDefault = (
if (lowered === 'date') {
return defaultValue === 'now()'
? '.defaultNow()'
: defaultValue === 'CURRENT_DATE'
? `.default(sql\`${defaultValue}\`)`
: defaultValue
: /^'\d{4}-\d{2}-\d{2}'$/.test(defaultValue) // Matches 'YYYY-MM-DD'
? `.default(${defaultValue})`
: defaultValue
? `.default(sql\`${defaultValue}\`)`
: '';
}

if (lowered.startsWith('text')) {
return typeof defaultValue !== 'undefined' ? `.default(${mapColumnDefault(defaultValue, isExpression)})` : '';
return typeof defaultValue !== 'undefined'
? `.default(${mapColumnDefault(unescapeSingleQuotes(defaultValue, true), isExpression)})`
: '';
}

if (lowered.startsWith('jsonb')) {
Expand Down Expand Up @@ -801,7 +807,9 @@ const mapDefault = (
}

if (lowered.startsWith('varchar')) {
return typeof defaultValue !== 'undefined' ? `.default(${mapColumnDefault(defaultValue, isExpression)})` : '';
return typeof defaultValue !== 'undefined'
? `.default(${mapColumnDefault(unescapeSingleQuotes(defaultValue, true), isExpression)})`
: '';
}

if (lowered.startsWith('point')) {
Expand All @@ -821,7 +829,9 @@ const mapDefault = (
}

if (lowered.startsWith('char')) {
return typeof defaultValue !== 'undefined' ? `.default(${mapColumnDefault(defaultValue, isExpression)})` : '';
return typeof defaultValue !== 'undefined'
? `.default(${mapColumnDefault(unescapeSingleQuotes(defaultValue, true), isExpression)})`
: '';
}

return '';
Expand Down Expand Up @@ -1219,7 +1229,11 @@ const createTableIndexes = (tableName: string, idxs: Index[], casing: Casing): s
} else {
return `table.${withCasing(it.expression, casing)}${it.asc ? '.asc()' : '.desc()'}${
it.nulls === 'first' ? '.nullsFirst()' : '.nullsLast()'
}${it.opclass && vectorOps.includes(it.opclass) ? `.op("${it.opclass}")` : ''}`;
}${
it.opclass
? `.op("${it.opclass}")`
: ''
}`;
}
})
.join(', ')
Expand Down
4 changes: 1 addition & 3 deletions drizzle-kit/src/introspect-sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,10 +272,8 @@ const mapColumnDefault = (defaultValue: any) => {

if (
typeof defaultValue === 'string'
&& defaultValue.startsWith("'")
&& defaultValue.endsWith("'")
) {
return defaultValue.substring(1, defaultValue.length - 1);
return defaultValue.substring(1, defaultValue.length - 1).replaceAll('"', '\\"').replaceAll("''", "'");
}

return defaultValue;
Expand Down
31 changes: 7 additions & 24 deletions drizzle-kit/src/jsonStatements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2704,19 +2704,14 @@ export const prepareAddCompositePrimaryKeyPg = (
tableName: string,
schema: string,
pks: Record<string, string>,
// TODO: remove?
json2: PgSchema,
): JsonCreateCompositePK[] => {
return Object.values(pks).map((it) => {
const unsquashed = PgSquasher.unsquashPK(it);
return {
type: 'create_composite_pk',
tableName,
data: it,
schema,
constraintName: json2.tables[`${schema || 'public'}.${tableName}`].compositePrimaryKeys[
unsquashed.name
].name,
constraintName: PgSquasher.unsquashPK(it).name,
} as JsonCreateCompositePK;
});
};
Expand All @@ -2725,18 +2720,14 @@ export const prepareDeleteCompositePrimaryKeyPg = (
tableName: string,
schema: string,
pks: Record<string, string>,
// TODO: remove?
json1: PgSchema,
): JsonDeleteCompositePK[] => {
return Object.values(pks).map((it) => {
return {
type: 'delete_composite_pk',
tableName,
data: it,
schema,
constraintName: json1.tables[`${schema || 'public'}.${tableName}`].compositePrimaryKeys[
PgSquasher.unsquashPK(it).name
].name,
constraintName: PgSquasher.unsquashPK(it).name,
} as JsonDeleteCompositePK;
});
};
Expand All @@ -2745,9 +2736,6 @@ export const prepareAlterCompositePrimaryKeyPg = (
tableName: string,
schema: string,
pks: Record<string, { __old: string; __new: string }>,
// TODO: remove?
json1: PgSchema,
json2: PgSchema,
): JsonAlterCompositePK[] => {
return Object.values(pks).map((it) => {
return {
Expand All @@ -2756,12 +2744,8 @@ export const prepareAlterCompositePrimaryKeyPg = (
old: it.__old,
new: it.__new,
schema,
oldConstraintName: json1.tables[`${schema || 'public'}.${tableName}`].compositePrimaryKeys[
PgSquasher.unsquashPK(it.__old).name
].name,
newConstraintName: json2.tables[`${schema || 'public'}.${tableName}`].compositePrimaryKeys[
PgSquasher.unsquashPK(it.__new).name
].name,
oldConstraintName: PgSquasher.unsquashPK(it.__old).name,
newConstraintName: PgSquasher.unsquashPK(it.__new).name,
} as JsonAlterCompositePK;
});
};
Expand Down Expand Up @@ -2874,7 +2858,7 @@ export const prepareAddCompositePrimaryKeyMySql = (
type: 'create_composite_pk',
tableName,
data: it,
constraintName: json2.tables[tableName].compositePrimaryKeys[unsquashed.name].name,
constraintName: unsquashed.name,
} as JsonCreateCompositePK);
}
return res;
Expand All @@ -2887,13 +2871,12 @@ export const prepareDeleteCompositePrimaryKeyMySql = (
json1: MySqlSchema,
): JsonDeleteCompositePK[] => {
return Object.values(pks).map((it) => {
const unsquashed = MySqlSquasher.unsquashPK(it);
return {
type: 'delete_composite_pk',
tableName,
data: it,
constraintName: json1.tables[tableName].compositePrimaryKeys[
MySqlSquasher.unsquashPK(it).name
].name,
constraintName: unsquashed.name,
} as JsonDeleteCompositePK;
});
};
Expand Down
24 changes: 16 additions & 8 deletions drizzle-kit/src/serializer/mysqlSerializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,20 @@ import {
UniqueConstraint,
View,
} from '../serializer/mysqlSchema';
import type { DB } from '../utils';
import { type DB, escapeSingleQuotes } from '../utils';
import { getColumnCasing, sqlToStr } from './utils';

export const indexName = (tableName: string, columns: string[]) => {
return `${tableName}_${columns.join('_')}_index`;
};

const handleEnumType = (type: string) => {
let str = type.split('(')[1];
str = str.substring(0, str.length - 1);
const values = str.split(',').map((v) => `'${escapeSingleQuotes(v.substring(1, v.length - 1))}'`);
return `enum(${values.join(',')})`;
};

export const generateMySqlSnapshot = (
tables: AnyMySqlTable[],
views: MySqlView[],
Expand Down Expand Up @@ -68,7 +75,8 @@ export const generateMySqlSnapshot = (
columns.forEach((column) => {
const name = getColumnCasing(column, casing);
const notNull: boolean = column.notNull;
const sqlTypeLowered = column.getSQLType().toLowerCase();
const sqlType = column.getSQLType();
const sqlTypeLowered = sqlType.toLowerCase();
const autoIncrement = typeof (column as any).autoIncrement === 'undefined'
? false
: (column as any).autoIncrement;
Expand All @@ -77,7 +85,7 @@ export const generateMySqlSnapshot = (

const columnToSet: Column = {
name,
type: column.getSQLType(),
type: sqlType.startsWith('enum') ? handleEnumType(sqlType) : sqlType,
primaryKey: false,
// If field is autoincrement it's notNull by default
// notNull: autoIncrement ? true : notNull,
Expand Down Expand Up @@ -141,7 +149,7 @@ export const generateMySqlSnapshot = (
columnToSet.default = sqlToStr(column.default, casing);
} else {
if (typeof column.default === 'string') {
columnToSet.default = `'${column.default}'`;
columnToSet.default = `'${escapeSingleQuotes(column.default)}'`;
} else {
if (sqlTypeLowered === 'json') {
columnToSet.default = `'${JSON.stringify(column.default)}'`;
Expand Down Expand Up @@ -544,9 +552,9 @@ function clearDefaults(defaultValue: any, collate: string) {
.substring(collate.length, defaultValue.length)
.replace(/\\/g, '');
if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
return `('${resultDefault.substring(1, resultDefault.length - 1)}')`;
return `('${escapeSingleQuotes(resultDefault.substring(1, resultDefault.length - 1))}')`;
} else {
return `'${resultDefault}'`;
return `'${escapeSingleQuotes(resultDefault.substring(1, resultDefault.length - 1))}'`;
}
} else {
return `(${resultDefault})`;
Expand Down Expand Up @@ -665,14 +673,14 @@ export const fromDatabase = async (
}

const newColumn: Column = {
default: columnDefault === null
default: columnDefault === null || columnDefault === undefined
? undefined
: /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault)
&& !['decimal', 'char', 'varchar'].some((type) => columnType.startsWith(type))
? Number(columnDefault)
: isDefaultAnExpression
? clearDefaults(columnDefault, collation)
: `'${columnDefault}'`,
: `'${escapeSingleQuotes(columnDefault)}'`,
autoincrement: isAutoincrement,
name: columnName,
type: changedType,
Expand Down
6 changes: 1 addition & 5 deletions drizzle-kit/src/serializer/pgSchema.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { vectorOps } from 'src/extensions/vector';
import { mapValues, originUUID, snapshotVersion } from '../global';

import { any, array, boolean, enum as enumType, literal, number, object, record, string, TypeOf, union } from 'zod';
Expand Down Expand Up @@ -555,10 +554,7 @@ export const PgSquasher = {
return `${idx.name};${
idx.columns
.map(
(c) =>
`${c.expression}--${c.isExpression}--${c.asc}--${c.nulls}--${
c.opclass && vectorOps.includes(c.opclass) ? c.opclass : ''
}`,
(c) => `${c.expression}--${c.isExpression}--${c.asc}--${c.nulls}--${c.opclass ? c.opclass : ''}`,
AndriiSherman marked this conversation as resolved.
Show resolved Hide resolved
)
.join(',,')
};${idx.isUnique};${idx.concurrently};${idx.method};${idx.where};${JSON.stringify(idx.with)}`;
Expand Down
Loading