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

[PG] Improve default value generation for array columns #2756

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
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