Skip to content

Commit

Permalink
Merge pull request #2756 from L-Mario564/fix-empty-array-generation
Browse files Browse the repository at this point in the history
[PG] Improve default value generation for array columns
  • Loading branch information
AndriiSherman authored Aug 7, 2024
2 parents 6234cbf + 8b0360a commit 505c62f
Show file tree
Hide file tree
Showing 4 changed files with 491 additions and 1 deletion.
46 changes: 45 additions & 1 deletion drizzle-kit/src/serializer/pgSerializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import type {
Table,
UniqueConstraint,
} from '../serializer/pgSchema';
import type { DB } from '../utils';
import { type DB, isPgArrayType } from '../utils';
import { sqlToStr } from '.';

const dialect = new PgDialect();
Expand Down Expand Up @@ -75,6 +75,43 @@ function stringFromDatabaseIdentityProperty(field: any): string | undefined {
: String(field);
}

function buildArrayString(array: any[], sqlType: string): string {
sqlType = sqlType.split('[')[0];
const values = array
.map((value) => {
if (typeof value === 'number' || typeof value === 'bigint') {
return value.toString();
} else if (typeof value === 'boolean') {
return value ? 'true' : 'false';
} else if (Array.isArray(value)) {
return buildArrayString(value, sqlType);
} else if (value instanceof Date) {
if (sqlType === 'date') {
return `"${value.toISOString().split('T')[0]}"`;
} else if (sqlType === 'timestamp') {
return `"${
value.toISOString()
.replace('T', ' ')
.slice(0, 23)
}"`;
} else {
return `"${value.toISOString()}"`;
}
} else if (typeof value === 'object') {
return `"${
JSON
.stringify(value)
.replaceAll('"', '\\"')
}"`;
}

return `"${value}"`;
})
.join(',');

return `{${values}}`;
}

export const generatePgSnapshot = (
tables: AnyPgTable[],
enums: PgEnum<any>[],
Expand Down Expand Up @@ -226,6 +263,13 @@ export const generatePgSnapshot = (
} else {
columnToSet.default = `'${column.default.toISOString()}'`;
}
} else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column.default)) {
columnToSet.default = `'${
buildArrayString(
column.default,
sqlTypeLowered,
)
}'::${sqlTypeLowered}`;
} else {
// Should do for all types
// columnToSet.default = `'${column.default}'::${sqlTypeLowered}`;
Expand Down
4 changes: 4 additions & 0 deletions drizzle-kit/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,3 +327,7 @@ export const normaliseSQLiteUrl = (

assertUnreachable(type);
};

export function isPgArrayType(sqlType: string) {
return sqlType.match(/.*\[\d*\].*|.*\[\].*/g) !== null;
}
Loading

0 comments on commit 505c62f

Please sign in to comment.