Skip to content

Commit

Permalink
Encased foreign key names in single quotes for consistency, escaped q…
Browse files Browse the repository at this point in the history
…uoted strings
  • Loading branch information
Sukairo-02 committed May 20, 2024
1 parent 4df43e8 commit 4c1afe7
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 35 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "drizzle-prisma-generator",
"author": "Drizzle Team",
"version": "0.1.1",
"version": "0.1.2",
"description": "Generate Drizzle schema from Prisma schema",
"scripts": {
"run": "pnpm run build && cd ../prisma-testbench && npx prisma generate dev && code ./src/db/schema.ts",
Expand Down
6 changes: 6 additions & 0 deletions src/util/escape/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export type StringContainer = "'" | '`' | '"';

const backslashes = new RegExp(/\\/g);

export const s = (src: string, container: StringContainer = "'") =>
src.replace(backslashes, '\\\\').replace(new RegExp(container, 'g'), `\\${container}`);
24 changes: 13 additions & 11 deletions src/util/generators/mysql.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { s } from '@/util/escape';
import { extractManyToManyModels } from '@/util/extract-many-to-many-models';
import { UnReadonlyDeep } from '@/util/un-readonly-deep';
import { type DMMF, GeneratorError, type GeneratorOptions } from '@prisma/generator-helper';
Expand Down Expand Up @@ -84,14 +85,14 @@ const addColumnModifiers = (field: DMMF.Field, column: string) => {
}

if (value.name === 'dbgenerated') {
column = column + `.default(sql\`${value.args[0]}\`)`;
column = column + `.default(sql\`${s(value.args[0], '`')}\`)`;

drizzleImports.add('sql');
break;
}

const stringified = `${value.name}(${value.args.map((e) => String(e)).join(', ')})`;
const sequel = `sql\`${stringified}\``;
const sequel = `sql\`${s(stringified, '`')}\``;

drizzleImports.add('sql');
column = column + `.default(${sequel})`;
Expand All @@ -106,7 +107,7 @@ const prismaToDrizzleColumn = (
field: DMMF.Field,
enums: UnReadonlyDeep<DMMF.DatamodelEnum[]>,
): string | undefined => {
const colDbName = field.dbName ?? field.name;
const colDbName = s(field.dbName ?? field.name);
let column = `\t${field.name}: `;

const drizzleType = prismaToDrizzleType(
Expand Down Expand Up @@ -135,7 +136,7 @@ export const generateMySqlSchema = (options: GeneratorOptions) => {
const rqb: string[] = [];

for (const schemaTable of modelsWithImplicit) {
const tableDbName = schemaTable.dbName ?? schemaTable.name;
const tableDbName = s(schemaTable.dbName ?? schemaTable.name);

const columnFields = Object.fromEntries(
schemaTable.fields
Expand All @@ -159,7 +160,7 @@ export const generateMySqlSchema = (options: GeneratorOptions) => {
return undefined;
}

const fkeyName = `${schemaTable.dbName ?? schemaTable.name}_${field.dbName ?? field.name}_fkey`;
const fkeyName = s(`${schemaTable.dbName ?? schemaTable.name}_${field.dbName ?? field.name}_fkey`);
let deleteAction: string;
switch (field.relationOnDelete) {
case undefined:
Expand All @@ -181,7 +182,7 @@ export const generateMySqlSchema = (options: GeneratorOptions) => {

mySqlImports.add('foreignKey');

return `\t${fkeyName}: foreignKey({\n\t\tname: '${fkeyName}',\n\t\tcolumns: [${
return `\t'${fkeyName}': foreignKey({\n\t\tname: '${fkeyName}',\n\t\tcolumns: [${
field.relationFromFields.map((rel) => `${schemaTable.name}.${rel}`).join(', ')
}],\n\t\tforeignColumns: [${field.relationToFields!.map((rel) => `${field.type}.${rel}`).join(', ')}]\n\t})${
deleteAction && deleteAction !== 'no action' ? `\n\t\t.onDelete('${deleteAction}')` : ''
Expand All @@ -194,7 +195,7 @@ export const generateMySqlSchema = (options: GeneratorOptions) => {
mySqlImports.add('uniqueIndex');

const uniques = schemaTable.uniqueIndexes.map((idx) => {
const idxName = idx.name ?? `${schemaTable.name}_${idx.fields.join('_')}_key`;
const idxName = s(idx.name ?? `${schemaTable.name}_${idx.fields.join('_')}_key`);
// _key comes from Prisma, if their AI is to be trusted

return `\t'${
Expand All @@ -209,7 +210,7 @@ export const generateMySqlSchema = (options: GeneratorOptions) => {
mySqlImports.add('primaryKey');

const pk = schemaTable.primaryKey!;
const pkName = pk.name ?? `${schemaTable.name}_cpk`;
const pkName = s(pk.name ?? `${schemaTable.name}_cpk`);

const pkField = `\t'${pkName}': primaryKey({\n\t\tname: '${pkName}',\n\t\tcolumns: [${
pk.fields.map((f) => `${schemaTable.name}.${f}`).join(', ')
Expand All @@ -229,13 +230,14 @@ export const generateMySqlSchema = (options: GeneratorOptions) => {
const relationArgs = new Set<string>();
const rqbFields = relFields.map((field) => {
relationArgs.add(field.relationFromFields?.length ? 'one' : 'many');
const relName = s(field.relationName ?? '');

return `\t'${field.relationName}': ${
return `\t'${relName}': ${
field.relationFromFields?.length
? `one(${field.type}, {\n\t\trelationName: '${field.relationName}',\n\t\tfields: [${
? `one(${field.type}, {\n\t\trelationName: '${relName}',\n\t\tfields: [${
field.relationFromFields.map((e) => `${schemaTable.name}.${e}`).join(', ')
}],\n\t\treferences: [${field.relationToFields!.map((e) => `${field.type}.${e}`).join(', ')}]\n\t})`
: `many(${field.type}, {\n\t\trelationName: '${field.relationName}'\n\t})`
: `many(${field.type}, {\n\t\trelationName: '${relName}'\n\t})`
}`;
}).join(',\n');

Expand Down
26 changes: 14 additions & 12 deletions src/util/generators/pg.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { s } from '@/util/escape';
import { extractManyToManyModels } from '@/util/extract-many-to-many-models';
import { UnReadonlyDeep } from '@/util/un-readonly-deep';
import { type DMMF, GeneratorError, type GeneratorOptions } from '@prisma/generator-helper';
Expand Down Expand Up @@ -85,14 +86,14 @@ const addColumnModifiers = (field: DMMF.Field, column: string) => {
}

if (value.name === 'dbgenerated') {
column = column + `.default(sql\`${value.args[0]}\`)`;
column = column + `.default(sql\`${s(value.args[0], '`')}\`)`;

drizzleImports.add('sql');
break;
}

const stringified = `${value.name}(${value.args.map((e) => String(e)).join(', ')})`;
const sequel = `sql\`${stringified}\``;
const sequel = `sql\`${s(stringified, '`')}\``;

drizzleImports.add('sql');
column = column + `.default(${sequel})`;
Expand All @@ -106,7 +107,7 @@ const addColumnModifiers = (field: DMMF.Field, column: string) => {
const prismaToDrizzleColumn = (
field: DMMF.Field,
): string | undefined => {
const colDbName = field.dbName ?? field.name;
const colDbName = s(field.dbName ?? field.name);
let column = `\t${field.name}: `;

if (field.kind === 'enum') {
Expand Down Expand Up @@ -139,7 +140,7 @@ export const generatePgSchema = (options: GeneratorOptions) => {

for (const schemaEnum of enums) {
if (!schemaEnum.values.length) continue;
const enumDbName = schemaEnum.dbName ?? schemaEnum.name;
const enumDbName = s(schemaEnum.dbName ?? schemaEnum.name);

pgImports.add('pgEnum');

Expand All @@ -154,7 +155,7 @@ export const generatePgSchema = (options: GeneratorOptions) => {
const rqb: string[] = [];

for (const schemaTable of modelsWithImplicit) {
const tableDbName = schemaTable.dbName ?? schemaTable.name;
const tableDbName = s(schemaTable.dbName ?? schemaTable.name);

const columnFields = Object.fromEntries(
schemaTable.fields
Expand All @@ -178,7 +179,7 @@ export const generatePgSchema = (options: GeneratorOptions) => {
return undefined;
}

const fkeyName = `${schemaTable.dbName ?? schemaTable.name}_${field.dbName ?? field.name}_fkey`;
const fkeyName = s(`${schemaTable.dbName ?? schemaTable.name}_${field.dbName ?? field.name}_fkey`);
let deleteAction: string;
switch (field.relationOnDelete) {
case undefined:
Expand All @@ -200,7 +201,7 @@ export const generatePgSchema = (options: GeneratorOptions) => {

pgImports.add('foreignKey');

return `\t${fkeyName}: foreignKey({\n\t\tname: '${fkeyName}',\n\t\tcolumns: [${
return `\t'${fkeyName}': foreignKey({\n\t\tname: '${fkeyName}',\n\t\tcolumns: [${
field.relationFromFields.map((rel) => `${schemaTable.name}.${rel}`).join(', ')
}],\n\t\tforeignColumns: [${field.relationToFields!.map((rel) => `${field.type}.${rel}`).join(', ')}]\n\t})${
deleteAction && deleteAction !== 'no action' ? `\n\t\t.onDelete('${deleteAction}')` : ''
Expand All @@ -213,7 +214,7 @@ export const generatePgSchema = (options: GeneratorOptions) => {
pgImports.add('uniqueIndex');

const uniques = schemaTable.uniqueIndexes.map((idx) => {
const idxName = idx.name ?? `${schemaTable.name}_${idx.fields.join('_')}_key`;
const idxName = s(idx.name ?? `${schemaTable.name}_${idx.fields.join('_')}_key`);
// _key comes from Prisma, if their AI is to be trusted

return `\t'${
Expand All @@ -228,7 +229,7 @@ export const generatePgSchema = (options: GeneratorOptions) => {
pgImports.add('primaryKey');

const pk = schemaTable.primaryKey!;
const pkName = pk.name ?? `${schemaTable.name}_cpk`;
const pkName = s(pk.name ?? `${schemaTable.name}_cpk`);

const pkField = `\t'${pkName}': primaryKey({\n\t\tname: '${pkName}',\n\t\tcolumns: [${
pk.fields.map((f) => `${schemaTable.name}.${f}`).join(', ')
Expand All @@ -249,13 +250,14 @@ export const generatePgSchema = (options: GeneratorOptions) => {
const relationArgs = new Set<string>();
const rqbFields = relFields.map((field) => {
relationArgs.add(field.relationFromFields?.length ? 'one' : 'many');
const relName = s(field.relationName ?? '');

return `\t'${field.relationName}': ${
return `\t'${relName}': ${
field.relationFromFields?.length
? `one(${field.type}, {\n\t\trelationName: '${field.relationName}',\n\t\tfields: [${
? `one(${field.type}, {\n\t\trelationName: '${relName}',\n\t\tfields: [${
field.relationFromFields.map((e) => `${schemaTable.name}.${e}`).join(', ')
}],\n\t\treferences: [${field.relationToFields!.map((e) => `${field.type}.${e}`).join(', ')}]\n\t})`
: `many(${field.type}, {\n\t\trelationName: '${field.relationName}'\n\t})`
: `many(${field.type}, {\n\t\trelationName: '${relName}'\n\t})`
}`;
}).join(',\n');

Expand Down
24 changes: 13 additions & 11 deletions src/util/generators/sqlite.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { s } from '@/util/escape';
import { extractManyToManyModels } from '@/util/extract-many-to-many-models';
import { UnReadonlyDeep } from '@/util/un-readonly-deep';
import { type DMMF, GeneratorError, type GeneratorOptions } from '@prisma/generator-helper';
Expand Down Expand Up @@ -78,14 +79,14 @@ const addColumnModifiers = (field: DMMF.Field, column: string) => {
}

if (value.name === 'dbgenerated') {
column = column + `.default(sql\`${value.args[0]}\`)`;
column = column + `.default(sql\`${s(value.args[0], '`')}\`)`;

drizzleImports.add('sql');
break;
}

const stringified = `${value.name}(${value.args.map((e) => String(e)).join(', ')})`;
const sequel = `sql\`${stringified}\``;
const sequel = `sql\`${s(stringified, '`')}\``;

drizzleImports.add('sql');
column = column + `.default(${sequel})`;
Expand All @@ -99,7 +100,7 @@ const addColumnModifiers = (field: DMMF.Field, column: string) => {
const prismaToDrizzleColumn = (
field: DMMF.Field,
): string | undefined => {
const colDbName = field.dbName ?? field.name;
const colDbName = s(field.dbName ?? field.name);
let column = `\t${field.name}: `;

const drizzleType = prismaToDrizzleType(field.type, colDbName);
Expand All @@ -124,7 +125,7 @@ export const generateSQLiteSchema = (options: GeneratorOptions) => {
const rqb: string[] = [];

for (const schemaTable of modelsWithImplicit) {
const tableDbName = schemaTable.dbName ?? schemaTable.name;
const tableDbName = s(schemaTable.dbName ?? schemaTable.name);

const columnFields = Object.fromEntries(
schemaTable.fields
Expand All @@ -148,7 +149,7 @@ export const generateSQLiteSchema = (options: GeneratorOptions) => {
return undefined;
}

const fkeyName = `${schemaTable.dbName ?? schemaTable.name}_${field.dbName ?? field.name}_fkey`;
const fkeyName = s(`${schemaTable.dbName ?? schemaTable.name}_${field.dbName ?? field.name}_fkey`);
let deleteAction: string;
switch (field.relationOnDelete) {
case undefined:
Expand All @@ -170,7 +171,7 @@ export const generateSQLiteSchema = (options: GeneratorOptions) => {

sqliteImports.add('foreignKey');

return `\t${fkeyName}: foreignKey({\n\t\tname: '${fkeyName}',\n\t\tcolumns: [${
return `\t'${fkeyName}': foreignKey({\n\t\tname: '${fkeyName}',\n\t\tcolumns: [${
field.relationFromFields.map((rel) => `${schemaTable.name}.${rel}`).join(', ')
}],\n\t\tforeignColumns: [${field.relationToFields!.map((rel) => `${field.type}.${rel}`).join(', ')}]\n\t})${
deleteAction && deleteAction !== 'no action' ? `\n\t\t.onDelete('${deleteAction}')` : ''
Expand All @@ -183,7 +184,7 @@ export const generateSQLiteSchema = (options: GeneratorOptions) => {
sqliteImports.add('uniqueIndex');

const uniques = schemaTable.uniqueIndexes.map((idx) => {
const idxName = idx.name ?? `${schemaTable.name}_${idx.fields.join('_')}_key`;
const idxName = s(idx.name ?? `${schemaTable.name}_${idx.fields.join('_')}_key`);
// _key comes from Prisma, if their AI is to be trusted

return `\t'${
Expand All @@ -198,7 +199,7 @@ export const generateSQLiteSchema = (options: GeneratorOptions) => {
sqliteImports.add('primaryKey');

const pk = schemaTable.primaryKey!;
const pkName = pk.name ?? `${schemaTable.name}_cpk`;
const pkName = s(pk.name ?? `${schemaTable.name}_cpk`);

const pkField = `\t'${pkName}': primaryKey({\n\t\tname: '${pkName}',\n\t\tcolumns: [${
pk.fields.map((f) => `${schemaTable.name}.${f}`).join(', ')
Expand All @@ -219,13 +220,14 @@ export const generateSQLiteSchema = (options: GeneratorOptions) => {
const relationArgs = new Set<string>();
const rqbFields = relFields.map((field) => {
relationArgs.add(field.relationFromFields?.length ? 'one' : 'many');
const relName = s(field.relationName ?? '');

return `\t'${field.relationName}': ${
return `\t'${relName}': ${
field.relationFromFields?.length
? `one(${field.type}, {\n\t\trelationName: '${field.relationName}',\n\t\tfields: [${
? `one(${field.type}, {\n\t\trelationName: '${relName}',\n\t\tfields: [${
field.relationFromFields.map((e) => `${schemaTable.name}.${e}`).join(', ')
}],\n\t\treferences: [${field.relationToFields!.map((e) => `${field.type}.${e}`).join(', ')}]\n\t})`
: `many(${field.type}, {\n\t\trelationName: '${field.relationName}'\n\t})`
: `many(${field.type}, {\n\t\trelationName: '${relName}'\n\t})`
}`;
}).join(',\n');

Expand Down

0 comments on commit 4c1afe7

Please sign in to comment.