@payloadcms/drizzle 4.0.0-internal.fa183d3 → 4.0.0-internal.fec2230
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/createTableName.d.ts.map +1 -1
- package/dist/createTableName.js +2 -7
- package/dist/createTableName.js.map +1 -1
- package/dist/exports/postgres.d.ts +2 -0
- package/dist/exports/postgres.d.ts.map +1 -1
- package/dist/exports/postgres.js +2 -0
- package/dist/exports/postgres.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/migrate.d.ts.map +1 -1
- package/dist/migrate.js +35 -13
- package/dist/migrate.js.map +1 -1
- package/dist/migrateDown.d.ts +2 -1
- package/dist/migrateDown.d.ts.map +1 -1
- package/dist/migrateDown.js +12 -2
- package/dist/migrateDown.js.map +1 -1
- package/dist/migrateFresh.d.ts +4 -2
- package/dist/migrateFresh.d.ts.map +1 -1
- package/dist/migrateFresh.js +21 -7
- package/dist/migrateFresh.js.map +1 -1
- package/dist/migrateRefresh.d.ts +2 -1
- package/dist/migrateRefresh.d.ts.map +1 -1
- package/dist/migrateRefresh.js +14 -3
- package/dist/migrateRefresh.js.map +1 -1
- package/dist/migrateReset.d.ts +2 -1
- package/dist/migrateReset.d.ts.map +1 -1
- package/dist/migrateReset.js +12 -2
- package/dist/migrateReset.js.map +1 -1
- package/dist/migrateStatus.d.ts +2 -1
- package/dist/migrateStatus.d.ts.map +1 -1
- package/dist/migrateStatus.js +11 -6
- package/dist/migrateStatus.js.map +1 -1
- package/dist/postgres/init.d.ts.map +1 -1
- package/dist/postgres/init.js +6 -0
- package/dist/postgres/init.js.map +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/index.js +1 -1
- package/dist/postgres/predefinedMigrations/v2-v3/index.js.map +1 -1
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.d.ts +15 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.d.ts.map +1 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.js +25 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.js.map +1 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.spec.js +91 -0
- package/dist/postgres/query/assertOperatorHandlerExtensionsInstalled.spec.js.map +1 -0
- package/dist/postgres/query/postgresUnaccent.d.ts +13 -0
- package/dist/postgres/query/postgresUnaccent.d.ts.map +1 -0
- package/dist/postgres/query/postgresUnaccent.js +40 -0
- package/dist/postgres/query/postgresUnaccent.js.map +1 -0
- package/dist/postgres/query/postgresUnaccent.spec.js +71 -0
- package/dist/postgres/query/postgresUnaccent.spec.js.map +1 -0
- package/dist/postgres/types.d.ts +13 -2
- package/dist/postgres/types.d.ts.map +1 -1
- package/dist/postgres/types.js.map +1 -1
- package/dist/queries/buildOperatorConstraint.d.ts +22 -0
- package/dist/queries/buildOperatorConstraint.d.ts.map +1 -0
- package/dist/queries/buildOperatorConstraint.js +63 -0
- package/dist/queries/buildOperatorConstraint.js.map +1 -0
- package/dist/queries/buildOperatorConstraint.spec.js +348 -0
- package/dist/queries/buildOperatorConstraint.spec.js.map +1 -0
- package/dist/queries/getTableColumnFromPath.d.ts +12 -3
- package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
- package/dist/queries/getTableColumnFromPath.js +50 -27
- package/dist/queries/getTableColumnFromPath.js.map +1 -1
- package/dist/queries/operatorMap.d.ts +7 -3
- package/dist/queries/operatorMap.d.ts.map +1 -1
- package/dist/queries/operatorMap.js.map +1 -1
- package/dist/queries/parseParams.d.ts.map +1 -1
- package/dist/queries/parseParams.js +203 -8
- package/dist/queries/parseParams.js.map +1 -1
- package/dist/queries/resolveRelationshipPath.d.ts +36 -0
- package/dist/queries/resolveRelationshipPath.d.ts.map +1 -0
- package/dist/queries/resolveRelationshipPath.js +66 -0
- package/dist/queries/resolveRelationshipPath.js.map +1 -0
- package/dist/queries/validateOperatorHandlers.d.ts +8 -0
- package/dist/queries/validateOperatorHandlers.d.ts.map +1 -0
- package/dist/queries/validateOperatorHandlers.js +30 -0
- package/dist/queries/validateOperatorHandlers.js.map +1 -0
- package/dist/queries/validateOperatorHandlers.spec.js +142 -0
- package/dist/queries/validateOperatorHandlers.spec.js.map +1 -0
- package/dist/schema/buildRawSchema.spec.js +290 -0
- package/dist/schema/buildRawSchema.spec.js.map +1 -0
- package/dist/schema/traverseFields.js +5 -5
- package/dist/schema/traverseFields.js.map +1 -1
- package/dist/transform/write/traverseFields.d.ts.map +1 -1
- package/dist/transform/write/traverseFields.js +3 -0
- package/dist/transform/write/traverseFields.js.map +1 -1
- package/dist/types.d.ts +50 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/updateJobs.d.ts.map +1 -1
- package/dist/updateJobs.js +37 -0
- package/dist/updateJobs.js.map +1 -1
- package/dist/utilities/buildCreateMigration.d.ts.map +1 -1
- package/dist/utilities/buildCreateMigration.js +12 -8
- package/dist/utilities/buildCreateMigration.js.map +1 -1
- package/dist/utilities/buildForeignKeyName.d.ts.map +1 -1
- package/dist/utilities/buildForeignKeyName.js +3 -2
- package/dist/utilities/buildForeignKeyName.js.map +1 -1
- package/dist/utilities/buildIndexName.d.ts.map +1 -1
- package/dist/utilities/buildIndexName.js +3 -2
- package/dist/utilities/buildIndexName.js.map +1 -1
- package/dist/utilities/checkTruncatedIdentifiers.d.ts +13 -0
- package/dist/utilities/checkTruncatedIdentifiers.d.ts.map +1 -0
- package/dist/utilities/checkTruncatedIdentifiers.js +56 -0
- package/dist/utilities/checkTruncatedIdentifiers.js.map +1 -0
- package/dist/utilities/checkTruncatedIdentifiers.spec.js +301 -0
- package/dist/utilities/checkTruncatedIdentifiers.spec.js.map +1 -0
- package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
- package/dist/utilities/createSchemaGenerator.js +3 -0
- package/dist/utilities/createSchemaGenerator.js.map +1 -1
- package/dist/utilities/validateExistingBlockIsIdentical.d.ts +1 -5
- package/dist/utilities/validateExistingBlockIsIdentical.d.ts.map +1 -1
- package/dist/utilities/validateExistingBlockIsIdentical.js.map +1 -1
- package/dist/utilities/validateIdentifierLength.d.ts +12 -0
- package/dist/utilities/validateIdentifierLength.d.ts.map +1 -0
- package/dist/utilities/validateIdentifierLength.js +18 -0
- package/dist/utilities/validateIdentifierLength.js.map +1 -0
- package/dist/utilities/validateIdentifierLength.spec.js +19 -0
- package/dist/utilities/validateIdentifierLength.spec.js.map +1 -0
- package/package.json +4 -4
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { checkTruncatedIdentifiers } from './checkTruncatedIdentifiers.js';
|
|
3
|
+
import { maxIdentifierLength } from './validateIdentifierLength.js';
|
|
4
|
+
const buildAdapter = (rawTables, warn = ()=>{})=>({
|
|
5
|
+
payload: {
|
|
6
|
+
logger: {
|
|
7
|
+
warn
|
|
8
|
+
}
|
|
9
|
+
},
|
|
10
|
+
rawTables
|
|
11
|
+
});
|
|
12
|
+
const longName = (char)=>char.repeat(maxIdentifierLength + 1);
|
|
13
|
+
describe('checkTruncatedIdentifiers', ()=>{
|
|
14
|
+
it('should neither warn nor throw when all identifiers fit within the limit', ()=>{
|
|
15
|
+
const warn = vi.fn();
|
|
16
|
+
const adapter = buildAdapter({
|
|
17
|
+
posts: {
|
|
18
|
+
name: 'posts',
|
|
19
|
+
columns: {
|
|
20
|
+
id: {
|
|
21
|
+
name: 'id',
|
|
22
|
+
type: 'serial'
|
|
23
|
+
},
|
|
24
|
+
title: {
|
|
25
|
+
name: 'title',
|
|
26
|
+
type: 'text'
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}, warn);
|
|
31
|
+
expect(()=>checkTruncatedIdentifiers({
|
|
32
|
+
adapter,
|
|
33
|
+
logWarnings: true
|
|
34
|
+
})).not.toThrow();
|
|
35
|
+
expect(warn).not.toHaveBeenCalled();
|
|
36
|
+
});
|
|
37
|
+
it('should warn (not throw) for a single over-long column name', ()=>{
|
|
38
|
+
const columnName = longName('a');
|
|
39
|
+
const warn = vi.fn();
|
|
40
|
+
const adapter = buildAdapter({
|
|
41
|
+
posts: {
|
|
42
|
+
name: 'posts',
|
|
43
|
+
columns: {
|
|
44
|
+
overflow: {
|
|
45
|
+
name: columnName,
|
|
46
|
+
type: 'text'
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}, warn);
|
|
51
|
+
expect(()=>checkTruncatedIdentifiers({
|
|
52
|
+
adapter,
|
|
53
|
+
logWarnings: true
|
|
54
|
+
})).not.toThrow();
|
|
55
|
+
expect(warn).toHaveBeenCalledTimes(1);
|
|
56
|
+
expect(warn.mock.calls[0][0]).toContain(columnName);
|
|
57
|
+
});
|
|
58
|
+
it('should not warn when logWarnings is false', ()=>{
|
|
59
|
+
const warn = vi.fn();
|
|
60
|
+
const adapter = buildAdapter({
|
|
61
|
+
posts: {
|
|
62
|
+
name: 'posts',
|
|
63
|
+
columns: {
|
|
64
|
+
overflow: {
|
|
65
|
+
name: longName('a'),
|
|
66
|
+
type: 'text'
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}, warn);
|
|
71
|
+
expect(()=>checkTruncatedIdentifiers({
|
|
72
|
+
adapter,
|
|
73
|
+
logWarnings: false
|
|
74
|
+
})).not.toThrow();
|
|
75
|
+
expect(warn).not.toHaveBeenCalled();
|
|
76
|
+
});
|
|
77
|
+
it('should throw when two columns in the same table truncate to the same name', ()=>{
|
|
78
|
+
// Differ only past the 63rd character, so both truncate to the same identifier.
|
|
79
|
+
const shared = 'a'.repeat(maxIdentifierLength);
|
|
80
|
+
const adapter = buildAdapter({
|
|
81
|
+
posts: {
|
|
82
|
+
name: 'posts',
|
|
83
|
+
columns: {
|
|
84
|
+
first: {
|
|
85
|
+
name: `${shared}_one`,
|
|
86
|
+
type: 'text'
|
|
87
|
+
},
|
|
88
|
+
second: {
|
|
89
|
+
name: `${shared}_two`,
|
|
90
|
+
type: 'text'
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
expect(()=>checkTruncatedIdentifiers({
|
|
96
|
+
adapter,
|
|
97
|
+
logWarnings: true
|
|
98
|
+
})).toThrow('truncate to the same name');
|
|
99
|
+
});
|
|
100
|
+
it('should throw on a collision even when logWarnings is false', ()=>{
|
|
101
|
+
const shared = 'a'.repeat(maxIdentifierLength);
|
|
102
|
+
const adapter = buildAdapter({
|
|
103
|
+
posts: {
|
|
104
|
+
name: 'posts',
|
|
105
|
+
columns: {
|
|
106
|
+
first: {
|
|
107
|
+
name: `${shared}_one`,
|
|
108
|
+
type: 'text'
|
|
109
|
+
},
|
|
110
|
+
second: {
|
|
111
|
+
name: `${shared}_two`,
|
|
112
|
+
type: 'text'
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
expect(()=>checkTruncatedIdentifiers({
|
|
118
|
+
adapter,
|
|
119
|
+
logWarnings: false
|
|
120
|
+
})).toThrow();
|
|
121
|
+
});
|
|
122
|
+
it('should not treat same-named columns in different tables as a collision', ()=>{
|
|
123
|
+
const shared = 'a'.repeat(maxIdentifierLength);
|
|
124
|
+
const warn = vi.fn();
|
|
125
|
+
const adapter = buildAdapter({
|
|
126
|
+
posts: {
|
|
127
|
+
name: 'posts',
|
|
128
|
+
columns: {
|
|
129
|
+
overflow: {
|
|
130
|
+
name: `${shared}_one`,
|
|
131
|
+
type: 'text'
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
pages: {
|
|
136
|
+
name: 'pages',
|
|
137
|
+
columns: {
|
|
138
|
+
overflow: {
|
|
139
|
+
name: `${shared}_two`,
|
|
140
|
+
type: 'text'
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}, warn);
|
|
145
|
+
expect(()=>checkTruncatedIdentifiers({
|
|
146
|
+
adapter,
|
|
147
|
+
logWarnings: true
|
|
148
|
+
})).not.toThrow();
|
|
149
|
+
expect(warn).toHaveBeenCalledTimes(1);
|
|
150
|
+
});
|
|
151
|
+
it('should throw when two table names truncate to the same name', ()=>{
|
|
152
|
+
const shared = 'a'.repeat(maxIdentifierLength);
|
|
153
|
+
const adapter = buildAdapter({
|
|
154
|
+
[`${shared}_one`]: {
|
|
155
|
+
name: `${shared}_one`,
|
|
156
|
+
columns: {
|
|
157
|
+
id: {
|
|
158
|
+
name: 'id',
|
|
159
|
+
type: 'serial'
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
[`${shared}_two`]: {
|
|
164
|
+
name: `${shared}_two`,
|
|
165
|
+
columns: {
|
|
166
|
+
id: {
|
|
167
|
+
name: 'id',
|
|
168
|
+
type: 'serial'
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
expect(()=>checkTruncatedIdentifiers({
|
|
174
|
+
adapter,
|
|
175
|
+
logWarnings: true
|
|
176
|
+
})).toThrow('truncate to the same name');
|
|
177
|
+
});
|
|
178
|
+
it('should warn about a single over-long inline index name', ()=>{
|
|
179
|
+
const indexName = `${'a'.repeat(maxIdentifierLength)}_idx`;
|
|
180
|
+
const warn = vi.fn();
|
|
181
|
+
const adapter = buildAdapter({
|
|
182
|
+
posts: {
|
|
183
|
+
name: 'posts',
|
|
184
|
+
columns: {
|
|
185
|
+
id: {
|
|
186
|
+
name: 'id',
|
|
187
|
+
type: 'serial'
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
indexes: {
|
|
191
|
+
a: {
|
|
192
|
+
name: indexName,
|
|
193
|
+
on: 'id'
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}, warn);
|
|
198
|
+
checkTruncatedIdentifiers({
|
|
199
|
+
adapter,
|
|
200
|
+
logWarnings: true
|
|
201
|
+
});
|
|
202
|
+
expect(warn).toHaveBeenCalledTimes(1);
|
|
203
|
+
expect(warn.mock.calls[0][0]).toContain(indexName);
|
|
204
|
+
});
|
|
205
|
+
it('should throw when two inline index names truncate to the same name', ()=>{
|
|
206
|
+
const shared = 'a'.repeat(maxIdentifierLength);
|
|
207
|
+
const adapter = buildAdapter({
|
|
208
|
+
posts: {
|
|
209
|
+
name: 'posts',
|
|
210
|
+
columns: {
|
|
211
|
+
id: {
|
|
212
|
+
name: 'id',
|
|
213
|
+
type: 'serial'
|
|
214
|
+
}
|
|
215
|
+
},
|
|
216
|
+
indexes: {
|
|
217
|
+
a: {
|
|
218
|
+
name: `${shared}_one`,
|
|
219
|
+
on: 'id'
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
},
|
|
223
|
+
pages: {
|
|
224
|
+
name: 'pages',
|
|
225
|
+
columns: {
|
|
226
|
+
id: {
|
|
227
|
+
name: 'id',
|
|
228
|
+
type: 'serial'
|
|
229
|
+
}
|
|
230
|
+
},
|
|
231
|
+
indexes: {
|
|
232
|
+
b: {
|
|
233
|
+
name: `${shared}_two`,
|
|
234
|
+
on: 'id'
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
expect(()=>checkTruncatedIdentifiers({
|
|
240
|
+
adapter,
|
|
241
|
+
logWarnings: true
|
|
242
|
+
})).toThrow('truncate to the same name');
|
|
243
|
+
});
|
|
244
|
+
it('should throw when two inline foreign key names truncate to the same name', ()=>{
|
|
245
|
+
const shared = 'a'.repeat(maxIdentifierLength);
|
|
246
|
+
const adapter = buildAdapter({
|
|
247
|
+
posts: {
|
|
248
|
+
name: 'posts',
|
|
249
|
+
columns: {
|
|
250
|
+
author_id: {
|
|
251
|
+
name: 'author_id',
|
|
252
|
+
type: 'integer'
|
|
253
|
+
}
|
|
254
|
+
},
|
|
255
|
+
foreignKeys: {
|
|
256
|
+
a: {
|
|
257
|
+
name: `${shared}_one`,
|
|
258
|
+
columns: [
|
|
259
|
+
'author_id'
|
|
260
|
+
],
|
|
261
|
+
foreignColumns: [
|
|
262
|
+
{
|
|
263
|
+
name: 'id',
|
|
264
|
+
table: 'authors'
|
|
265
|
+
}
|
|
266
|
+
]
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
},
|
|
270
|
+
pages: {
|
|
271
|
+
name: 'pages',
|
|
272
|
+
columns: {
|
|
273
|
+
author_id: {
|
|
274
|
+
name: 'author_id',
|
|
275
|
+
type: 'integer'
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
foreignKeys: {
|
|
279
|
+
b: {
|
|
280
|
+
name: `${shared}_two`,
|
|
281
|
+
columns: [
|
|
282
|
+
'author_id'
|
|
283
|
+
],
|
|
284
|
+
foreignColumns: [
|
|
285
|
+
{
|
|
286
|
+
name: 'id',
|
|
287
|
+
table: 'authors'
|
|
288
|
+
}
|
|
289
|
+
]
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
expect(()=>checkTruncatedIdentifiers({
|
|
295
|
+
adapter,
|
|
296
|
+
logWarnings: true
|
|
297
|
+
})).toThrow('truncate to the same name');
|
|
298
|
+
});
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
//# sourceMappingURL=checkTruncatedIdentifiers.spec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/checkTruncatedIdentifiers.spec.ts"],"sourcesContent":["import { describe, expect, it, vi } from 'vitest'\n\nimport type { DrizzleAdapter } from '../types.js'\n\nimport { checkTruncatedIdentifiers } from './checkTruncatedIdentifiers.js'\nimport { maxIdentifierLength } from './validateIdentifierLength.js'\n\nconst buildAdapter = (\n rawTables: DrizzleAdapter['rawTables'],\n warn: (...args: any[]) => void = () => {},\n): Pick<DrizzleAdapter, 'payload' | 'rawTables'> =>\n ({\n payload: { logger: { warn } },\n rawTables,\n }) as unknown as Pick<DrizzleAdapter, 'payload' | 'rawTables'>\n\nconst longName = (char: string) => char.repeat(maxIdentifierLength + 1)\n\ndescribe('checkTruncatedIdentifiers', () => {\n it('should neither warn nor throw when all identifiers fit within the limit', () => {\n const warn = vi.fn()\n\n const adapter = buildAdapter(\n {\n posts: {\n name: 'posts',\n columns: {\n id: { name: 'id', type: 'serial' },\n title: { name: 'title', type: 'text' },\n },\n },\n },\n warn,\n )\n\n expect(() => checkTruncatedIdentifiers({ adapter, logWarnings: true })).not.toThrow()\n expect(warn).not.toHaveBeenCalled()\n })\n\n it('should warn (not throw) for a single over-long column name', () => {\n const columnName = longName('a')\n const warn = vi.fn()\n\n const adapter = buildAdapter(\n {\n posts: {\n name: 'posts',\n columns: {\n overflow: { name: columnName, type: 'text' },\n },\n },\n },\n warn,\n )\n\n expect(() => checkTruncatedIdentifiers({ adapter, logWarnings: true })).not.toThrow()\n expect(warn).toHaveBeenCalledTimes(1)\n expect(warn.mock.calls[0][0]).toContain(columnName)\n })\n\n it('should not warn when logWarnings is false', () => {\n const warn = vi.fn()\n\n const adapter = buildAdapter(\n {\n posts: {\n name: 'posts',\n columns: {\n overflow: { name: longName('a'), type: 'text' },\n },\n },\n },\n warn,\n )\n\n expect(() => checkTruncatedIdentifiers({ adapter, logWarnings: false })).not.toThrow()\n expect(warn).not.toHaveBeenCalled()\n })\n\n it('should throw when two columns in the same table truncate to the same name', () => {\n // Differ only past the 63rd character, so both truncate to the same identifier.\n const shared = 'a'.repeat(maxIdentifierLength)\n\n const adapter = buildAdapter({\n posts: {\n name: 'posts',\n columns: {\n first: { name: `${shared}_one`, type: 'text' },\n second: { name: `${shared}_two`, type: 'text' },\n },\n },\n })\n\n expect(() => checkTruncatedIdentifiers({ adapter, logWarnings: true })).toThrow(\n 'truncate to the same name',\n )\n })\n\n it('should throw on a collision even when logWarnings is false', () => {\n const shared = 'a'.repeat(maxIdentifierLength)\n\n const adapter = buildAdapter({\n posts: {\n name: 'posts',\n columns: {\n first: { name: `${shared}_one`, type: 'text' },\n second: { name: `${shared}_two`, type: 'text' },\n },\n },\n })\n\n expect(() => checkTruncatedIdentifiers({ adapter, logWarnings: false })).toThrow()\n })\n\n it('should not treat same-named columns in different tables as a collision', () => {\n const shared = 'a'.repeat(maxIdentifierLength)\n const warn = vi.fn()\n\n const adapter = buildAdapter(\n {\n posts: {\n name: 'posts',\n columns: {\n overflow: { name: `${shared}_one`, type: 'text' },\n },\n },\n pages: {\n name: 'pages',\n columns: {\n overflow: { name: `${shared}_two`, type: 'text' },\n },\n },\n },\n warn,\n )\n\n expect(() => checkTruncatedIdentifiers({ adapter, logWarnings: true })).not.toThrow()\n expect(warn).toHaveBeenCalledTimes(1)\n })\n\n it('should throw when two table names truncate to the same name', () => {\n const shared = 'a'.repeat(maxIdentifierLength)\n\n const adapter = buildAdapter({\n [`${shared}_one`]: {\n name: `${shared}_one`,\n columns: { id: { name: 'id', type: 'serial' } },\n },\n [`${shared}_two`]: {\n name: `${shared}_two`,\n columns: { id: { name: 'id', type: 'serial' } },\n },\n })\n\n expect(() => checkTruncatedIdentifiers({ adapter, logWarnings: true })).toThrow(\n 'truncate to the same name',\n )\n })\n\n it('should warn about a single over-long inline index name', () => {\n const indexName = `${'a'.repeat(maxIdentifierLength)}_idx`\n const warn = vi.fn()\n\n const adapter = buildAdapter(\n {\n posts: {\n name: 'posts',\n columns: { id: { name: 'id', type: 'serial' } },\n indexes: { a: { name: indexName, on: 'id' } },\n },\n },\n warn,\n )\n\n checkTruncatedIdentifiers({ adapter, logWarnings: true })\n\n expect(warn).toHaveBeenCalledTimes(1)\n expect(warn.mock.calls[0][0]).toContain(indexName)\n })\n\n it('should throw when two inline index names truncate to the same name', () => {\n const shared = 'a'.repeat(maxIdentifierLength)\n\n const adapter = buildAdapter({\n posts: {\n name: 'posts',\n columns: { id: { name: 'id', type: 'serial' } },\n indexes: { a: { name: `${shared}_one`, on: 'id' } },\n },\n pages: {\n name: 'pages',\n columns: { id: { name: 'id', type: 'serial' } },\n indexes: { b: { name: `${shared}_two`, on: 'id' } },\n },\n })\n\n expect(() => checkTruncatedIdentifiers({ adapter, logWarnings: true })).toThrow(\n 'truncate to the same name',\n )\n })\n\n it('should throw when two inline foreign key names truncate to the same name', () => {\n const shared = 'a'.repeat(maxIdentifierLength)\n\n const adapter = buildAdapter({\n posts: {\n name: 'posts',\n columns: { author_id: { name: 'author_id', type: 'integer' } },\n foreignKeys: {\n a: {\n name: `${shared}_one`,\n columns: ['author_id'],\n foreignColumns: [{ name: 'id', table: 'authors' }],\n },\n },\n },\n pages: {\n name: 'pages',\n columns: { author_id: { name: 'author_id', type: 'integer' } },\n foreignKeys: {\n b: {\n name: `${shared}_two`,\n columns: ['author_id'],\n foreignColumns: [{ name: 'id', table: 'authors' }],\n },\n },\n },\n })\n\n expect(() => checkTruncatedIdentifiers({ adapter, logWarnings: true })).toThrow(\n 'truncate to the same name',\n )\n })\n})\n"],"names":["describe","expect","it","vi","checkTruncatedIdentifiers","maxIdentifierLength","buildAdapter","rawTables","warn","payload","logger","longName","char","repeat","fn","adapter","posts","name","columns","id","type","title","logWarnings","not","toThrow","toHaveBeenCalled","columnName","overflow","toHaveBeenCalledTimes","mock","calls","toContain","shared","first","second","pages","indexName","indexes","a","on","b","author_id","foreignKeys","foreignColumns","table"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,EAAEC,EAAE,QAAQ,SAAQ;AAIjD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,mBAAmB,QAAQ,gCAA+B;AAEnE,MAAMC,eAAe,CACnBC,WACAC,OAAiC,KAAO,CAAC,GAExC,CAAA;QACCC,SAAS;YAAEC,QAAQ;gBAAEF;YAAK;QAAE;QAC5BD;IACF,CAAA;AAEF,MAAMI,WAAW,CAACC,OAAiBA,KAAKC,MAAM,CAACR,sBAAsB;AAErEL,SAAS,6BAA6B;IACpCE,GAAG,2EAA2E;QAC5E,MAAMM,OAAOL,GAAGW,EAAE;QAElB,MAAMC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;oBAAK;gBAAE;YACpD;YACAJ,OAAO;gBACLlB,MAAM;gBACNC,SAAS;oBAAEC,IAAI;wBAAEF,MAAM;wBAAMG,MAAM;oBAAS;gBAAE;gBAC9CiB,SAAS;oBAAEG,GAAG;wBAAEvB,MAAM,GAAGe,OAAO,IAAI,CAAC;wBAAEO,IAAI;oBAAK;gBAAE;YACpD;QACF;QAEAtC,OAAO,IAAMG,0BAA0B;gBAAEW;gBAASO,aAAa;YAAK,IAAIE,OAAO,CAC7E;IAEJ;IAEAtB,GAAG,4EAA4E;QAC7E,MAAM8B,SAAS,IAAInB,MAAM,CAACR;QAE1B,MAAMU,UAAUT,aAAa;YAC3BU,OAAO;gBACLC,MAAM;gBACNC,SAAS;oBAAEuB,WAAW;wBAAExB,MAAM;wBAAaG,MAAM;oBAAU;gBAAE;gBAC7DsB,aAAa;oBACXJ,GAAG;wBACDrB,MAAM,GAAGe,OAAO,IAAI,CAAC;wBACrBd,SAAS;4BAAC;yBAAY;wBACtByB,gBAAgB;4BAAC;gCAAE1B,MAAM;gCAAM2B,OAAO;4BAAU;yBAAE;oBACpD;gBACF;YACF;YACAT,OAAO;gBACLlB,MAAM;gBACNC,SAAS;oBAAEuB,WAAW;wBAAExB,MAAM;wBAAaG,MAAM;oBAAU;gBAAE;gBAC7DsB,aAAa;oBACXF,GAAG;wBACDvB,MAAM,GAAGe,OAAO,IAAI,CAAC;wBACrBd,SAAS;4BAAC;yBAAY;wBACtByB,gBAAgB;4BAAC;gCAAE1B,MAAM;gCAAM2B,OAAO;4BAAU;yBAAE;oBACpD;gBACF;YACF;QACF;QAEA3C,OAAO,IAAMG,0BAA0B;gBAAEW;gBAASO,aAAa;YAAK,IAAIE,OAAO,CAC7E;IAEJ;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createSchemaGenerator.d.ts","sourceRoot":"","sources":["../../src/utilities/createSchemaGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,qBAAqB,EAAkB,MAAM,aAAa,CAAA;AAkCxE,eAAO,MAAM,qBAAqB,4GAO/B;IACD,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,iBAAiB,EAAE,MAAM,CAAA;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,
|
|
1
|
+
{"version":3,"file":"createSchemaGenerator.d.ts","sourceRoot":"","sources":["../../src/utilities/createSchemaGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,qBAAqB,EAAkB,MAAM,aAAa,CAAA;AAkCxE,eAAO,MAAM,qBAAqB,4GAO/B;IACD,qBAAqB,EAAE,qBAAqB,CAAA;IAC5C,iBAAiB,EAAE,MAAM,CAAA;IACzB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,MAAM,CAAA;CACpB,KAAG,cAmTH,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\n/**\n * @example\n * console.log(sanitizeObjectKey(\"oneTwo\")); // oneTwo\n * console.log(sanitizeObjectKey(\"one-two\")); // 'one-two'\n * console.log(sanitizeObjectKey(\"_one$Two3\")); // _one$Two3\n * console.log(sanitizeObjectKey(\"3invalid\")); // '3invalid'\n */\nconst sanitizeObjectKey = (key: string) => {\n // Regular expression for a valid identifier\n const identifierRegex = /^[a-z_$][\\w$]*$/i\n if (identifierRegex.test(key)) {\n return key\n }\n\n return `'${key}'`\n}\n\n/**\n * @example\n * (columns default-valuesID) -> columns['default-valuesID']\n * (columns defaultValues) -> columns.defaultValues\n */\nconst accessProperty = (objName: string, key: string) => {\n const sanitized = sanitizeObjectKey(key)\n\n if (sanitized.startsWith(\"'\")) {\n return `${objName}[${sanitized}]`\n }\n\n return `${objName}.${key}`\n}\n\nexport const createSchemaGenerator = ({\n columnToCodeConverter,\n corePackageSuffix,\n defaultOutputFile,\n enumImport,\n schemaImport,\n tableImport,\n}: {\n columnToCodeConverter: ColumnToCodeConverter\n corePackageSuffix: string\n defaultOutputFile?: string\n enumImport?: string\n schemaImport?: string\n tableImport: string\n}): GenerateSchema => {\n return async function generateSchema(\n this: DrizzleAdapter,\n { log = true, outputFile = defaultOutputFile, prettify = true } = {},\n ) {\n const importDeclarations: Record<string, Set<string>> = {}\n\n const tableDeclarations: string[] = []\n const enumDeclarations: string[] = []\n const relationsDeclarations: string[] = []\n\n const addImport = (from: string, name: string) => {\n if (!importDeclarations[from]) {\n importDeclarations[from] = new Set()\n }\n\n importDeclarations[from].add(name)\n }\n\n const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`\n\n let schemaDeclaration: null | string = null\n\n if (this.schemaName) {\n addImport(corePackage, schemaImport)\n schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`\n }\n\n const enumFn = this.schemaName ? `db_schema.enum` : enumImport\n\n const enumsList: string[] = []\n const addEnum = (name: string, options: string[]) => {\n if (enumsList.some((each) => each === name)) {\n return\n }\n enumsList.push(name)\n enumDeclarations.push(\n `export const ${name} = ${enumFn}('${name}', [${options.map((option) => `'${option}'`).join(', ')}])`,\n )\n }\n\n if (this.payload.config.localization && enumImport) {\n addEnum('enum__locales', this.payload.config.localization.localeCodes)\n }\n\n const tableFn = this.schemaName ? `db_schema.table` : tableImport\n\n if (!this.schemaName) {\n addImport(corePackage, tableImport)\n }\n\n addImport(corePackage, 'index')\n addImport(corePackage, 'uniqueIndex')\n addImport(corePackage, 'foreignKey')\n\n addImport(`${this.packageName}/drizzle`, 'sql')\n addImport(`${this.packageName}/drizzle`, 'relations')\n\n const fkGraph: Record<string, Set<string>> = {}\n\n for (const tableName in this.rawTables) {\n fkGraph[tableName] = new Set()\n const table = this.rawTables[tableName]\n\n for (const colKey in table.columns) {\n const col = table.columns[colKey]\n\n if (col.reference && col.reference.table !== tableName) {\n fkGraph[tableName].add(col.reference.table)\n }\n }\n }\n\n const canReach = (from: string, target: string, visited: Set<string>): boolean => {\n if (from === target) {\n return true\n }\n\n if (visited.has(from)) {\n return false\n }\n\n visited.add(from)\n\n for (const neighbor of fkGraph[from] ?? []) {\n if (canReach(neighbor, target, visited)) {\n return true\n }\n }\n\n return false\n }\n\n const circularEdges = new Set<string>()\n\n for (const tableA in fkGraph) {\n for (const tableB of fkGraph[tableA]) {\n if (canReach(tableB, tableA, new Set())) {\n circularEdges.add(`${tableA}:${tableB}`)\n }\n }\n }\n\n for (const tableName in this.rawTables) {\n const table = this.rawTables[tableName]\n\n const extrasDeclarations: string[] = []\n\n if (table.indexes) {\n for (const key in table.indexes) {\n const index = table.indexes[key]\n let indexDeclaration = `${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`\n indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`\n extrasDeclarations.push(indexDeclaration)\n }\n }\n\n if (table.foreignKeys) {\n for (const key in table.foreignKeys) {\n const foreignKey = table.foreignKeys[key]\n\n let foreignKeyDeclaration = `foreignKey({\n columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],\n foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],\n name: '${foreignKey.name}'\n })`\n\n if (foreignKey.onDelete) {\n foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`\n }\n if (foreignKey.onUpdate) {\n foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`\n }\n\n foreignKeyDeclaration += ','\n\n extrasDeclarations.push(foreignKeyDeclaration)\n }\n }\n\n const tableCode = `\nexport const ${tableName} = ${tableFn}('${tableName}', {\n${Object.entries(table.columns)\n .map(\n ([key, column]) =>\n ` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({\n adapter: this,\n addEnum,\n addImport,\n circularEdges,\n column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n tableKey: tableName,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns) => [\n ${extrasDeclarations.join(' ')}\n]`\n : ''\n }\n)\n`\n\n tableDeclarations.push(tableCode)\n }\n\n for (const tableName in this.rawRelations) {\n const relations = this.rawRelations[tableName]\n const properties: string[] = []\n\n for (const key in relations) {\n const relation = relations[key]\n let declaration: string\n\n if (relation.type === 'one') {\n declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {\n ${relation.fields.some((field) => field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}\n fields: [${relation.fields.map((field) => `${accessProperty(field.table, field.name)}`).join(', ')}],\n references: [${relation.references.map((col) => `${accessProperty(relation.to, col)}`).join(', ')}],\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n } else {\n declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n }\n\n properties.push(declaration)\n }\n\n // beautify / lintify relations callback output, when no many for example, don't add it\n const args = []\n\n if (Object.values(relations).some((rel) => rel.type === 'one')) {\n args.push('one')\n }\n\n if (Object.values(relations).some((rel) => rel.type === 'many')) {\n args.push('many')\n }\n\n const arg = args.length ? `{ ${args.join(', ')} }` : ''\n\n const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({\n ${properties.join('\\n ')}\n }))`\n\n relationsDeclarations.push(declaration)\n }\n\n if (enumDeclarations.length && !this.schemaName) {\n addImport(corePackage, enumImport)\n }\n\n const importDeclarationsSanitized: string[] = []\n\n for (const moduleName in importDeclarations) {\n const moduleImports = importDeclarations[moduleName]\n\n importDeclarationsSanitized.push(\n `import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,\n )\n }\n\n const schemaType = `\ntype DatabaseSchema = {\n ${[\n this.schemaName ? 'db_schema' : null,\n ...enumsList,\n ...Object.keys(this.rawTables),\n ...Object.keys(this.rawRelations).map((table) => `relations_${table}`),\n ]\n .filter(Boolean)\n .map((name) => `${name}: typeof ${name}`)\n .join('\\n ')}\n}\n `\n\n const finalDeclaration = `\ndeclare module '${this.packageName}' {\n export interface GeneratedDatabaseSchema {\n schema: DatabaseSchema\n }\n}\n `\n\n const warning = `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:db-schema\\` to regenerate this file.\n */\n`\n\n const importTypes = `import type {} from '${this.packageName}'`\n\n let code = [\n warning,\n importTypes,\n ...importDeclarationsSanitized,\n schemaDeclaration,\n ...enumDeclarations,\n ...tableDeclarations,\n ...relationsDeclarations,\n schemaType,\n finalDeclaration,\n ]\n .filter(Boolean)\n .join('\\n')\n\n if (!outputFile) {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src')\n\n if (existsSync(srcDir)) {\n outputFile = path.resolve(srcDir, 'payload-generated-schema.ts')\n } else {\n outputFile = path.resolve(cwd, 'payload-generated-schema.ts')\n }\n }\n\n if (prettify) {\n try {\n const prettier = await eval('import(\"prettier\")')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n code = await prettier.format(code, { ...config, parser: 'typescript' })\n } catch {\n /* empty */\n }\n }\n\n await writeFile(outputFile, code, 'utf-8')\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n }\n}\n"],"names":["existsSync","writeFile","path","sanitizeObjectKey","key","identifierRegex","test","accessProperty","objName","sanitized","startsWith","createSchemaGenerator","columnToCodeConverter","corePackageSuffix","defaultOutputFile","enumImport","schemaImport","tableImport","generateSchema","log","outputFile","prettify","importDeclarations","tableDeclarations","enumDeclarations","relationsDeclarations","addImport","from","name","Set","add","corePackage","packageName","schemaDeclaration","schemaName","enumFn","enumsList","addEnum","options","some","each","push","map","option","join","payload","config","localization","localeCodes","tableFn","fkGraph","tableName","rawTables","table","colKey","columns","col","reference","canReach","target","visited","has","neighbor","circularEdges","tableA","tableB","extrasDeclarations","indexes","index","indexDeclaration","unique","on","foreignKeys","foreignKey","foreignKeyDeclaration","foreignColumns","onDelete","onUpdate","tableCode","Object","entries","column","adapter","locales","undefined","tableKey","length","rawRelations","relations","properties","relation","declaration","type","to","fields","field","references","relationName","args","values","rel","arg","importDeclarationsSanitized","moduleName","moduleImports","Array","schemaType","keys","filter","Boolean","finalDeclaration","warning","importTypes","code","cwd","process","srcDir","resolve","prettier","eval","configPath","resolveConfigFile","resolveConfig","format","parser","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB;;;;;;CAMC,GACD,MAAMC,oBAAoB,CAACC;IACzB,4CAA4C;IAC5C,MAAMC,kBAAkB;IACxB,IAAIA,gBAAgBC,IAAI,CAACF,MAAM;QAC7B,OAAOA;IACT;IAEA,OAAO,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC;AACnB;AAEA;;;;CAIC,GACD,MAAMG,iBAAiB,CAACC,SAAiBJ;IACvC,MAAMK,YAAYN,kBAAkBC;IAEpC,IAAIK,UAAUC,UAAU,CAAC,MAAM;QAC7B,OAAO,GAAGF,QAAQ,CAAC,EAAEC,UAAU,CAAC,CAAC;IACnC;IAEA,OAAO,GAAGD,QAAQ,CAAC,EAAEJ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E/D,IAAIiF,OAAO;YACTF;YACAC;eACGV;YACHrE;eACGT;eACAD;eACAE;YACHiF;YACAI;SACD,CACEF,MAAM,CAACC,SACPjE,IAAI,CAAC;QAER,IAAI,CAACxB,YAAY;YACf,MAAM8F,MAAMC,QAAQD,GAAG;YACvB,MAAME,SAASlH,KAAKmH,OAAO,CAACH,KAAK;YAEjC,IAAIlH,WAAWoH,SAAS;gBACtBhG,aAAalB,KAAKmH,OAAO,CAACD,QAAQ;YACpC,OAAO;gBACLhG,aAAalB,KAAKmH,OAAO,CAACH,KAAK;YACjC;QACF;QAEA,IAAI7F,UAAU;YACZ,IAAI;gBACF,MAAMiG,WAAW,MAAMC,KAAK;gBAC5B,MAAMC,aAAa,MAAMF,SAASG,iBAAiB;gBACnD,MAAM3E,SAAS0E,aAAa,MAAMF,SAASI,aAAa,CAACF,cAAc,CAAC;gBACxEP,OAAO,MAAMK,SAASK,MAAM,CAACV,MAAM;oBAAE,GAAGnE,MAAM;oBAAE8E,QAAQ;gBAAa;YACvE,EAAE,OAAM;YACN,SAAS,GACX;QACF;QAEA,MAAM3H,UAAUmB,YAAY6F,MAAM;QAElC,IAAI9F,KAAK;YACP,IAAI,CAAC0B,OAAO,CAACgF,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAE1G,YAAY;QAClD;IACF;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/createSchemaGenerator.ts"],"sourcesContent":["import type { GenerateSchema } from 'payload'\n\nimport { existsSync } from 'fs'\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\n\nimport type { ColumnToCodeConverter, DrizzleAdapter } from '../types.js'\n\n/**\n * @example\n * console.log(sanitizeObjectKey(\"oneTwo\")); // oneTwo\n * console.log(sanitizeObjectKey(\"one-two\")); // 'one-two'\n * console.log(sanitizeObjectKey(\"_one$Two3\")); // _one$Two3\n * console.log(sanitizeObjectKey(\"3invalid\")); // '3invalid'\n */\nconst sanitizeObjectKey = (key: string) => {\n // Regular expression for a valid identifier\n const identifierRegex = /^[a-z_$][\\w$]*$/i\n if (identifierRegex.test(key)) {\n return key\n }\n\n return `'${key}'`\n}\n\n/**\n * @example\n * (columns default-valuesID) -> columns['default-valuesID']\n * (columns defaultValues) -> columns.defaultValues\n */\nconst accessProperty = (objName: string, key: string) => {\n const sanitized = sanitizeObjectKey(key)\n\n if (sanitized.startsWith(\"'\")) {\n return `${objName}[${sanitized}]`\n }\n\n return `${objName}.${key}`\n}\n\nexport const createSchemaGenerator = ({\n columnToCodeConverter,\n corePackageSuffix,\n defaultOutputFile,\n enumImport,\n schemaImport,\n tableImport,\n}: {\n columnToCodeConverter: ColumnToCodeConverter\n corePackageSuffix: string\n defaultOutputFile?: string\n enumImport?: string\n schemaImport?: string\n tableImport: string\n}): GenerateSchema => {\n return async function generateSchema(\n this: DrizzleAdapter,\n { log = true, outputFile = defaultOutputFile, prettify = true } = {},\n ) {\n const importDeclarations: Record<string, Set<string>> = {}\n\n const tableDeclarations: string[] = []\n const enumDeclarations: string[] = []\n const relationsDeclarations: string[] = []\n\n const addImport = (from: string, name: string) => {\n if (!importDeclarations[from]) {\n importDeclarations[from] = new Set()\n }\n\n importDeclarations[from].add(name)\n }\n\n const corePackage = `${this.packageName}/drizzle/${corePackageSuffix}`\n\n let schemaDeclaration: null | string = null\n\n if (this.schemaName) {\n addImport(corePackage, schemaImport)\n schemaDeclaration = `export const db_schema = ${schemaImport}('${this.schemaName}')`\n }\n\n const enumFn = this.schemaName ? `db_schema.enum` : enumImport\n\n const enumsList: string[] = []\n const addEnum = (name: string, options: string[]) => {\n if (enumsList.some((each) => each === name)) {\n return\n }\n enumsList.push(name)\n enumDeclarations.push(\n `export const ${name} = ${enumFn}('${name}', [${options.map((option) => `'${option}'`).join(', ')}])`,\n )\n }\n\n if (this.payload.config.localization && enumImport) {\n addEnum('enum__locales', this.payload.config.localization.localeCodes)\n }\n\n const tableFn = this.schemaName ? `db_schema.table` : tableImport\n\n if (!this.schemaName) {\n addImport(corePackage, tableImport)\n }\n\n addImport(corePackage, 'index')\n addImport(corePackage, 'uniqueIndex')\n addImport(corePackage, 'foreignKey')\n\n addImport(`${this.packageName}/drizzle`, 'sql')\n addImport(`${this.packageName}/drizzle`, 'relations')\n\n const fkGraph: Record<string, Set<string>> = {}\n\n for (const tableName in this.rawTables) {\n fkGraph[tableName] = new Set()\n const table = this.rawTables[tableName]\n\n for (const colKey in table.columns) {\n const col = table.columns[colKey]\n\n if (col.reference && col.reference.table !== tableName) {\n fkGraph[tableName].add(col.reference.table)\n }\n }\n }\n\n const canReach = (from: string, target: string, visited: Set<string>): boolean => {\n if (from === target) {\n return true\n }\n\n if (visited.has(from)) {\n return false\n }\n\n visited.add(from)\n\n for (const neighbor of fkGraph[from] ?? []) {\n if (canReach(neighbor, target, visited)) {\n return true\n }\n }\n\n return false\n }\n\n const circularEdges = new Set<string>()\n\n for (const tableA in fkGraph) {\n for (const tableB of fkGraph[tableA]) {\n if (canReach(tableB, tableA, new Set())) {\n circularEdges.add(`${tableA}:${tableB}`)\n }\n }\n }\n\n for (const tableName in this.rawTables) {\n const table = this.rawTables[tableName]\n\n const extrasDeclarations: string[] = []\n\n if (table.indexes) {\n for (const key in table.indexes) {\n const index = table.indexes[key]\n let indexDeclaration = `${index.unique ? 'uniqueIndex' : 'index'}('${index.name}')`\n indexDeclaration += `.on(${typeof index.on === 'string' ? `${accessProperty('columns', index.on)}` : `${index.on.map((on) => `${accessProperty('columns', on)}`).join(', ')}`}),`\n extrasDeclarations.push(indexDeclaration)\n }\n }\n\n if (table.foreignKeys) {\n for (const key in table.foreignKeys) {\n const foreignKey = table.foreignKeys[key]\n\n let foreignKeyDeclaration = `foreignKey({\n columns: [${foreignKey.columns.map((col) => `columns['${col}']`).join(', ')}],\n foreignColumns: [${foreignKey.foreignColumns.map((col) => `${accessProperty(col.table, col.name)}`).join(', ')}],\n name: '${foreignKey.name}'\n })`\n\n if (foreignKey.onDelete) {\n foreignKeyDeclaration += `.onDelete('${foreignKey.onDelete}')`\n }\n if (foreignKey.onUpdate) {\n foreignKeyDeclaration += `.onUpdate('${foreignKey.onDelete}')`\n }\n\n foreignKeyDeclaration += ','\n\n extrasDeclarations.push(foreignKeyDeclaration)\n }\n }\n\n const tableCode = `\nexport const ${tableName} = ${tableFn}('${tableName}', {\n${Object.entries(table.columns)\n .map(\n ([key, column]) =>\n ` ${sanitizeObjectKey(key)}: ${columnToCodeConverter({\n adapter: this,\n addEnum,\n addImport,\n circularEdges,\n column,\n locales: this.payload.config.localization\n ? this.payload.config.localization.localeCodes\n : undefined,\n tableKey: tableName,\n })},`,\n )\n .join('\\n')}\n}${\n extrasDeclarations.length\n ? `, (columns) => [\n ${extrasDeclarations.join(' ')}\n]`\n : ''\n }\n)\n`\n\n tableDeclarations.push(tableCode)\n }\n\n for (const tableName in this.rawRelations) {\n const relations = this.rawRelations[tableName]\n const properties: string[] = []\n\n for (const key in relations) {\n const relation = relations[key]\n let declaration: string\n\n if (relation.type === 'one') {\n declaration = `${sanitizeObjectKey(key)}: one(${relation.to}, {\n ${relation.fields.some((field) => field.table !== tableName) ? '// @ts-expect-error Drizzle TypeScript bug for ONE relationships with a field in different table' : ''}\n fields: [${relation.fields.map((field) => `${accessProperty(field.table, field.name)}`).join(', ')}],\n references: [${relation.references.map((col) => `${accessProperty(relation.to, col)}`).join(', ')}],\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n } else {\n declaration = `${sanitizeObjectKey(key)}: many(${relation.to}, {\n ${relation.relationName ? `relationName: '${relation.relationName}',` : ''}\n }),`\n }\n\n properties.push(declaration)\n }\n\n // beautify / lintify relations callback output, when no many for example, don't add it\n const args = []\n\n if (Object.values(relations).some((rel) => rel.type === 'one')) {\n args.push('one')\n }\n\n if (Object.values(relations).some((rel) => rel.type === 'many')) {\n args.push('many')\n }\n\n const arg = args.length ? `{ ${args.join(', ')} }` : ''\n\n const declaration = `export const relations_${tableName} = relations(${tableName}, (${arg}) => ({\n ${properties.join('\\n ')}\n }))`\n\n relationsDeclarations.push(declaration)\n }\n\n if (enumDeclarations.length && !this.schemaName) {\n addImport(corePackage, enumImport)\n }\n\n const importDeclarationsSanitized: string[] = []\n\n for (const moduleName in importDeclarations) {\n const moduleImports = importDeclarations[moduleName]\n\n importDeclarationsSanitized.push(\n `import { ${Array.from(moduleImports).join(', ')} } from '${moduleName}'`,\n )\n }\n\n const schemaType = `\ntype DatabaseSchema = {\n ${[\n this.schemaName ? 'db_schema' : null,\n ...enumsList,\n ...Object.keys(this.rawTables),\n ...Object.keys(this.rawRelations).map((table) => `relations_${table}`),\n ]\n .filter(Boolean)\n .map((name) => `${name}: typeof ${name}`)\n .join('\\n ')}\n}\n `\n\n const finalDeclaration = `\ndeclare module '${this.packageName}' {\n export interface GeneratedDatabaseSchema {\n schema: DatabaseSchema\n }\n}\n `\n\n const warning = `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:db-schema\\` to regenerate this file.\n */\n`\n\n const importTypes = `import type {} from '${this.packageName}'`\n\n let code = [\n warning,\n importTypes,\n ...importDeclarationsSanitized,\n schemaDeclaration,\n ...enumDeclarations,\n ...tableDeclarations,\n ...relationsDeclarations,\n schemaType,\n finalDeclaration,\n ]\n .filter(Boolean)\n .join('\\n')\n\n if (!outputFile) {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src')\n\n if (existsSync(srcDir)) {\n outputFile = path.resolve(srcDir, 'payload-generated-schema.ts')\n } else {\n outputFile = path.resolve(cwd, 'payload-generated-schema.ts')\n }\n }\n\n if (prettify) {\n try {\n const prettier = await eval('import(\"prettier\")')\n const configPath = await prettier.resolveConfigFile()\n const config = configPath ? await prettier.resolveConfig(configPath) : {}\n code = await prettier.format(code, { ...config, parser: 'typescript' })\n } catch {\n /* empty */\n }\n }\n\n await writeFile(outputFile, code, 'utf-8')\n\n if (log) {\n this.payload.logger.info(`Written ${outputFile}`)\n }\n\n return { outputFile }\n }\n}\n"],"names":["existsSync","writeFile","path","sanitizeObjectKey","key","identifierRegex","test","accessProperty","objName","sanitized","startsWith","createSchemaGenerator","columnToCodeConverter","corePackageSuffix","defaultOutputFile","enumImport","schemaImport","tableImport","generateSchema","log","outputFile","prettify","importDeclarations","tableDeclarations","enumDeclarations","relationsDeclarations","addImport","from","name","Set","add","corePackage","packageName","schemaDeclaration","schemaName","enumFn","enumsList","addEnum","options","some","each","push","map","option","join","payload","config","localization","localeCodes","tableFn","fkGraph","tableName","rawTables","table","colKey","columns","col","reference","canReach","target","visited","has","neighbor","circularEdges","tableA","tableB","extrasDeclarations","indexes","index","indexDeclaration","unique","on","foreignKeys","foreignKey","foreignKeyDeclaration","foreignColumns","onDelete","onUpdate","tableCode","Object","entries","column","adapter","locales","undefined","tableKey","length","rawRelations","relations","properties","relation","declaration","type","to","fields","field","references","relationName","args","values","rel","arg","importDeclarationsSanitized","moduleName","moduleImports","Array","schemaType","keys","filter","Boolean","finalDeclaration","warning","importTypes","code","cwd","process","srcDir","resolve","prettier","eval","configPath","resolveConfigFile","resolveConfig","format","parser","logger","info"],"mappings":"AAEA,SAASA,UAAU,QAAQ,KAAI;AAC/B,SAASC,SAAS,QAAQ,cAAa;AACvC,OAAOC,UAAU,OAAM;AAIvB;;;;;;CAMC,GACD,MAAMC,oBAAoB,CAACC;IACzB,4CAA4C;IAC5C,MAAMC,kBAAkB;IACxB,IAAIA,gBAAgBC,IAAI,CAACF,MAAM;QAC7B,OAAOA;IACT;IAEA,OAAO,CAAC,CAAC,EAAEA,IAAI,CAAC,CAAC;AACnB;AAEA;;;;CAIC,GACD,MAAMG,iBAAiB,CAACC,SAAiBJ;IACvC,MAAMK,YAAYN,kBAAkBC;IAEpC,IAAIK,UAAUC,UAAU,CAAC,MAAM;QAC7B,OAAO,GAAGF,QAAQ,CAAC,EAAEC,UAAU,CAAC,CAAC;IACnC;IAEA,OAAO,GAAGD,QAAQ,CAAC,EAAEJ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AE/D,IAAIiF,OAAO;YACTF;YACAC;eACGV;YACHrE;eACGT;eACAD;eACAE;YACHiF;YACAI;SACD,CACEF,MAAM,CAACC,SACPjE,IAAI,CAAC;QAER,IAAI,CAACxB,YAAY;YACf,MAAM8F,MAAMC,QAAQD,GAAG;YACvB,MAAME,SAASlH,KAAKmH,OAAO,CAACH,KAAK;YAEjC,IAAIlH,WAAWoH,SAAS;gBACtBhG,aAAalB,KAAKmH,OAAO,CAACD,QAAQ;YACpC,OAAO;gBACLhG,aAAalB,KAAKmH,OAAO,CAACH,KAAK;YACjC;QACF;QAEA,IAAI7F,UAAU;YACZ,IAAI;gBACF,MAAMiG,WAAW,MAAMC,KAAK;gBAC5B,MAAMC,aAAa,MAAMF,SAASG,iBAAiB;gBACnD,MAAM3E,SAAS0E,aAAa,MAAMF,SAASI,aAAa,CAACF,cAAc,CAAC;gBACxEP,OAAO,MAAMK,SAASK,MAAM,CAACV,MAAM;oBAAE,GAAGnE,MAAM;oBAAE8E,QAAQ;gBAAa;YACvE,EAAE,OAAM;YACN,SAAS,GACX;QACF;QAEA,MAAM3H,UAAUmB,YAAY6F,MAAM;QAElC,IAAI9F,KAAK;YACP,IAAI,CAAC0B,OAAO,CAACgF,MAAM,CAACC,IAAI,CAAC,CAAC,QAAQ,EAAE1G,YAAY;QAClD;QAEA,OAAO;YAAEA;QAAW;IACtB;AACF,EAAC"}
|
|
@@ -3,11 +3,7 @@ import type { RawTable } from '../types.js';
|
|
|
3
3
|
type Args = {
|
|
4
4
|
block: Block;
|
|
5
5
|
localized: boolean;
|
|
6
|
-
|
|
7
|
-
* @todo make required in v4.0. Usually you'd wanna pass this in
|
|
8
|
-
*/
|
|
9
|
-
parentIsLocalized?: boolean;
|
|
10
|
-
rootTableName: string;
|
|
6
|
+
parentIsLocalized: boolean;
|
|
11
7
|
table: RawTable;
|
|
12
8
|
tableLocales?: RawTable;
|
|
13
9
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validateExistingBlockIsIdentical.d.ts","sourceRoot":"","sources":["../../src/utilities/validateExistingBlockIsIdentical.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAS,cAAc,EAAE,MAAM,SAAS,CAAA;AAS3D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAE3C,KAAK,IAAI,GAAG;IACV,KAAK,EAAE,KAAK,CAAA;IACZ,SAAS,EAAE,OAAO,CAAA;IAClB
|
|
1
|
+
{"version":3,"file":"validateExistingBlockIsIdentical.d.ts","sourceRoot":"","sources":["../../src/utilities/validateExistingBlockIsIdentical.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAS,cAAc,EAAE,MAAM,SAAS,CAAA;AAS3D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAE3C,KAAK,IAAI,GAAG;IACV,KAAK,EAAE,KAAK,CAAA;IACZ,SAAS,EAAE,OAAO,CAAA;IAClB,iBAAiB,EAAE,OAAO,CAAA;IAC1B,KAAK,EAAE,QAAQ,CAAA;IACf,YAAY,CAAC,EAAE,QAAQ,CAAA;CACxB,CAAA;AA+DD;;GAEG;AACH,eAAO,MAAM,gCAAgC,kEAM1C,IAAI,KAAG,OAwBT,CAAA;AAED,eAAO,MAAM,2BAA2B,eAAwC,CAAA;AAChF,eAAO,MAAM,qBAAqB,UAAW,cAAc,SAAS,MAAM,SAEzE,CAAA;AAED,eAAO,MAAM,qBAAqB,UAAW,cAAc,qBAAqB,MAAM,WAMrF,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/validateExistingBlockIsIdentical.ts"],"sourcesContent":["import type { Block, Field, FlattenedBlock } from 'payload'\n\nimport {\n fieldAffectsData,\n fieldHasSubFields,\n fieldShouldBeLocalized,\n tabHasName,\n} from 'payload/shared'\n\nimport type { RawTable } from '../types.js'\n\ntype Args = {\n block: Block\n localized: boolean\n
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/validateExistingBlockIsIdentical.ts"],"sourcesContent":["import type { Block, Field, FlattenedBlock } from 'payload'\n\nimport {\n fieldAffectsData,\n fieldHasSubFields,\n fieldShouldBeLocalized,\n tabHasName,\n} from 'payload/shared'\n\nimport type { RawTable } from '../types.js'\n\ntype Args = {\n block: Block\n localized: boolean\n parentIsLocalized: boolean\n table: RawTable\n tableLocales?: RawTable\n}\n\nconst getFlattenedFieldNames = (args: {\n fields: Field[]\n parentIsLocalized: boolean\n prefix?: string\n}): { localized?: boolean; name: string }[] => {\n const { fields, parentIsLocalized, prefix = '' } = args\n return fields.reduce((fieldsToUse, field) => {\n let fieldPrefix = prefix\n\n if (\n ['array', 'blocks', 'relationship', 'upload'].includes(field.type) ||\n ('hasMany' in field && field.hasMany === true)\n ) {\n return fieldsToUse\n }\n\n if (fieldHasSubFields(field)) {\n fieldPrefix = 'name' in field ? `${prefix}${field.name}_` : prefix\n return [\n ...fieldsToUse,\n ...getFlattenedFieldNames({\n fields: field.fields,\n parentIsLocalized: parentIsLocalized || ('localized' in field && field.localized),\n prefix: fieldPrefix,\n }),\n ]\n }\n\n if (field.type === 'tabs') {\n return [\n ...fieldsToUse,\n ...field.tabs.reduce((tabFields, tab) => {\n fieldPrefix = 'name' in tab ? `${prefix}_${tab.name}` : prefix\n return [\n ...tabFields,\n ...(tabHasName(tab)\n ? [{ ...tab, type: 'tab' }]\n : getFlattenedFieldNames({\n fields: tab.fields,\n parentIsLocalized: parentIsLocalized || tab.localized,\n prefix: fieldPrefix,\n })),\n ]\n }, []),\n ]\n }\n\n if (fieldAffectsData(field)) {\n return [\n ...fieldsToUse,\n {\n name: `${fieldPrefix}${field.name}`,\n localized: fieldShouldBeLocalized({ field, parentIsLocalized }),\n },\n ]\n }\n\n return fieldsToUse\n }, [])\n}\n\n/**\n * returns true if all the fields in a block are identical to the existing table\n */\nexport const validateExistingBlockIsIdentical = ({\n block,\n localized,\n parentIsLocalized,\n table,\n tableLocales,\n}: Args): boolean => {\n const fieldNames = getFlattenedFieldNames({\n fields: block.fields,\n parentIsLocalized: parentIsLocalized || localized,\n })\n\n const missingField =\n // ensure every field from the config is in the matching table\n fieldNames.find(({ name, localized }) => {\n const fieldTable = localized && tableLocales ? tableLocales : table\n return Object.keys(fieldTable.columns).indexOf(name) === -1\n }) ||\n // ensure every table column is matched for every field from the config\n Object.keys(table).find((fieldName) => {\n if (!['_locale', '_order', '_parentID', '_path', '_uuid'].includes(fieldName)) {\n return fieldNames.findIndex((field) => field.name) === -1\n }\n })\n\n if (missingField) {\n return false\n }\n\n return Boolean(localized) === Boolean(table.columns._locale)\n}\n\nexport const InternalBlockTableNameIndex = Symbol('InternalBlockTableNameIndex')\nexport const setInternalBlockIndex = (block: FlattenedBlock, index: number) => {\n block[InternalBlockTableNameIndex] = index\n}\n\nexport const resolveBlockTableName = (block: FlattenedBlock, originalTableName: string) => {\n if (!block[InternalBlockTableNameIndex]) {\n return originalTableName\n }\n\n return `${originalTableName}_${block[InternalBlockTableNameIndex]}`\n}\n"],"names":["fieldAffectsData","fieldHasSubFields","fieldShouldBeLocalized","tabHasName","getFlattenedFieldNames","args","fields","parentIsLocalized","prefix","reduce","fieldsToUse","field","fieldPrefix","includes","type","hasMany","name","localized","tabs","tabFields","tab","validateExistingBlockIsIdentical","block","table","tableLocales","fieldNames","missingField","find","fieldTable","Object","keys","columns","indexOf","fieldName","findIndex","Boolean","_locale","InternalBlockTableNameIndex","Symbol","setInternalBlockIndex","index","resolveBlockTableName","originalTableName"],"mappings":"AAEA,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,sBAAsB,EACtBC,UAAU,QACL,iBAAgB;AAYvB,MAAMC,yBAAyB,CAACC;IAK9B,MAAM,EAAEC,MAAM,EAAEC,iBAAiB,EAAEC,SAAS,EAAE,EAAE,GAAGH;IACnD,OAAOC,OAAOG,MAAM,CAAC,CAACC,aAAaC;QACjC,IAAIC,cAAcJ;QAElB,IACE;YAAC;YAAS;YAAU;Y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,8DAA8D;IAC9DD,WAAWE,IAAI,CAAC,CAAC,EAAEX,IAAI,EAAEC,SAAS,EAAE;QAClC,MAAMW,aAAaX,aAAaO,eAAeA,eAAeD;QAC9D,OAAOM,OAAOC,IAAI,CAACF,WAAWG,OAAO,EAAEC,OAAO,CAAChB,UAAU,CAAC;IAC5D,MACA,uEAAuE;IACvEa,OAAOC,IAAI,CAACP,OAAOI,IAAI,CAAC,CAACM;QACvB,IAAI,CAAC;YAAC;YAAW;YAAU;YAAa;YAAS;SAAQ,CAACpB,QAAQ,CAACoB,YAAY;YAC7E,OAAOR,WAAWS,SAAS,CAAC,CAACvB,QAAUA,MAAMK,IAAI,MAAM,CAAC;QAC1D;IACF;IAEF,IAAIU,cAAc;QAChB,OAAO;IACT;IAEA,OAAOS,QAAQlB,eAAekB,QAAQZ,MAAMQ,OAAO,CAACK,OAAO;AAC7D,EAAC;AAED,OAAO,MAAMC,8BAA8BC,OAAO,+BAA8B;AAChF,OAAO,MAAMC,wBAAwB,CAACjB,OAAuBkB;IAC3DlB,KAAK,CAACe,4BAA4B,GAAGG;AACvC,EAAC;AAED,OAAO,MAAMC,wBAAwB,CAACnB,OAAuBoB;IAC3D,IAAI,CAACpB,KAAK,CAACe,4BAA4B,EAAE;QACvC,OAAOK;IACT;IAEA,OAAO,GAAGA,kBAAkB,CAAC,EAAEpB,KAAK,CAACe,4BAA4B,EAAE;AACrE,EAAC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Postgres max identifier length (NAMEDATALEN - 1). */
|
|
2
|
+
export declare const maxIdentifierLength = 63;
|
|
3
|
+
/**
|
|
4
|
+
* Cap for builder-generated identifiers (`buildIndexName`/`buildForeignKeyName`). Sits
|
|
5
|
+
* below `maxIdentifierLength` to leave headroom for the appended `_idx`/`_fk`/`_N` suffixes.
|
|
6
|
+
*/
|
|
7
|
+
export declare const maxGeneratedIdentifierLength: number;
|
|
8
|
+
/**
|
|
9
|
+
* Throws if a table or enum identifier exceeds the Postgres 63-char limit.
|
|
10
|
+
*/
|
|
11
|
+
export declare const validateIdentifierLength: (name: string) => string;
|
|
12
|
+
//# sourceMappingURL=validateIdentifierLength.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validateIdentifierLength.d.ts","sourceRoot":"","sources":["../../src/utilities/validateIdentifierLength.ts"],"names":[],"mappings":"AAEA,wDAAwD;AACxD,eAAO,MAAM,mBAAmB,KAAK,CAAA;AAErC;;;GAGG;AACH,eAAO,MAAM,4BAA4B,QAA0B,CAAA;AAEnE;;GAEG;AACH,eAAO,MAAM,wBAAwB,SAAU,MAAM,KAAG,MAUvD,CAAA"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { APIError } from 'payload';
|
|
2
|
+
/** Postgres max identifier length (NAMEDATALEN - 1). */ export const maxIdentifierLength = 63;
|
|
3
|
+
/**
|
|
4
|
+
* Cap for builder-generated identifiers (`buildIndexName`/`buildForeignKeyName`). Sits
|
|
5
|
+
* below `maxIdentifierLength` to leave headroom for the appended `_idx`/`_fk`/`_N` suffixes.
|
|
6
|
+
*/ export const maxGeneratedIdentifierLength = maxIdentifierLength - 3;
|
|
7
|
+
/**
|
|
8
|
+
* Throws if a table or enum identifier exceeds the Postgres 63-char limit.
|
|
9
|
+
*/ export const validateIdentifierLength = (name)=>{
|
|
10
|
+
if (name.length > maxIdentifierLength) {
|
|
11
|
+
throw new APIError(`Exceeded max identifier length for table or enum name of ${maxIdentifierLength} characters. Invalid name: ${name}.
|
|
12
|
+
Tip: You can use the dbName property to reduce the table name length.
|
|
13
|
+
`);
|
|
14
|
+
}
|
|
15
|
+
return name;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=validateIdentifierLength.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/validateIdentifierLength.ts"],"sourcesContent":["import { APIError } from 'payload'\n\n/** Postgres max identifier length (NAMEDATALEN - 1). */\nexport const maxIdentifierLength = 63\n\n/**\n * Cap for builder-generated identifiers (`buildIndexName`/`buildForeignKeyName`). Sits\n * below `maxIdentifierLength` to leave headroom for the appended `_idx`/`_fk`/`_N` suffixes.\n */\nexport const maxGeneratedIdentifierLength = maxIdentifierLength - 3\n\n/**\n * Throws if a table or enum identifier exceeds the Postgres 63-char limit.\n */\nexport const validateIdentifierLength = (name: string): string => {\n if (name.length > maxIdentifierLength) {\n throw new APIError(\n `Exceeded max identifier length for table or enum name of ${maxIdentifierLength} characters. Invalid name: ${name}.\nTip: You can use the dbName property to reduce the table name length.\n `,\n )\n }\n\n return name\n}\n"],"names":["APIError","maxIdentifierLength","maxGeneratedIdentifierLength","validateIdentifierLength","name","length"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,UAAS;AAElC,sDAAsD,GACtD,OAAO,MAAMC,sBAAsB,GAAE;AAErC;;;CAGC,GACD,OAAO,MAAMC,+BAA+BD,sBAAsB,EAAC;AAEnE;;CAEC,GACD,OAAO,MAAME,2BAA2B,CAACC;IACvC,IAAIA,KAAKC,MAAM,GAAGJ,qBAAqB;QACrC,MAAM,IAAID,SACR,CAAC,yDAAyD,EAAEC,oBAAoB,2BAA2B,EAAEG,KAAK;;MAElH,CAAC;IAEL;IAEA,OAAOA;AACT,EAAC"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { maxIdentifierLength, validateIdentifierLength } from './validateIdentifierLength.js';
|
|
3
|
+
describe('validateIdentifierLength', ()=>{
|
|
4
|
+
it('should return the name unchanged when at or under the 63-char limit', ()=>{
|
|
5
|
+
const name = 'a'.repeat(maxIdentifierLength);
|
|
6
|
+
expect(validateIdentifierLength(name)).toBe(name);
|
|
7
|
+
});
|
|
8
|
+
it('should throw when the name exceeds the 63-char limit', ()=>{
|
|
9
|
+
const name = 'a'.repeat(maxIdentifierLength + 1);
|
|
10
|
+
expect(()=>validateIdentifierLength(name)).toThrow('Exceeded max identifier length');
|
|
11
|
+
});
|
|
12
|
+
it('should include the invalid name and the dbName tip in the error', ()=>{
|
|
13
|
+
const name = `some_long_table_name${'x'.repeat(maxIdentifierLength)}_locales`;
|
|
14
|
+
expect(()=>validateIdentifierLength(name)).toThrow(name);
|
|
15
|
+
expect(()=>validateIdentifierLength(name)).toThrow('You can use the dbName property to reduce the table name length');
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
//# sourceMappingURL=validateIdentifierLength.spec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/validateIdentifierLength.spec.ts"],"sourcesContent":["import { describe, expect, it } from 'vitest'\n\nimport { maxIdentifierLength, validateIdentifierLength } from './validateIdentifierLength.js'\n\ndescribe('validateIdentifierLength', () => {\n it('should return the name unchanged when at or under the 63-char limit', () => {\n const name = 'a'.repeat(maxIdentifierLength)\n\n expect(validateIdentifierLength(name)).toBe(name)\n })\n\n it('should throw when the name exceeds the 63-char limit', () => {\n const name = 'a'.repeat(maxIdentifierLength + 1)\n\n expect(() => validateIdentifierLength(name)).toThrow('Exceeded max identifier length')\n })\n\n it('should include the invalid name and the dbName tip in the error', () => {\n const name = `some_long_table_name${'x'.repeat(maxIdentifierLength)}_locales`\n\n expect(() => validateIdentifierLength(name)).toThrow(name)\n expect(() => validateIdentifierLength(name)).toThrow(\n 'You can use the dbName property to reduce the table name length',\n )\n })\n})\n"],"names":["describe","expect","it","maxIdentifierLength","validateIdentifierLength","name","repeat","toBe","toThrow"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAE7C,SAASC,mBAAmB,EAAEC,wBAAwB,QAAQ,gCAA+B;AAE7FJ,SAAS,4BAA4B;IACnCE,GAAG,uEAAuE;QACxE,MAAMG,OAAO,IAAIC,MAAM,CAACH;QAExBF,OAAOG,yBAAyBC,OAAOE,IAAI,CAACF;IAC9C;IAEAH,GAAG,wDAAwD;QACzD,MAAMG,OAAO,IAAIC,MAAM,CAACH,sBAAsB;QAE9CF,OAAO,IAAMG,yBAAyBC,OAAOG,OAAO,CAAC;IACvD;IAEAN,GAAG,mEAAmE;QACpE,MAAMG,OAAO,CAAC,oBAAoB,EAAE,IAAIC,MAAM,CAACH,qBAAqB,QAAQ,CAAC;QAE7EF,OAAO,IAAMG,yBAAyBC,OAAOG,OAAO,CAACH;QACrDJ,OAAO,IAAMG,yBAAyBC,OAAOG,OAAO,CAClD;IAEJ;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/drizzle",
|
|
3
|
-
"version": "4.0.0-internal.
|
|
3
|
+
"version": "4.0.0-internal.fec2230",
|
|
4
4
|
"description": "A library of shared functions used by different payload database adapters",
|
|
5
5
|
"homepage": "https://payloadcms.com",
|
|
6
6
|
"repository": {
|
|
@@ -54,11 +54,11 @@
|
|
|
54
54
|
"@libsql/client": "0.14.0",
|
|
55
55
|
"@types/pg": "8.20.0",
|
|
56
56
|
"@types/to-snake-case": "1.0.0",
|
|
57
|
-
"
|
|
58
|
-
"
|
|
57
|
+
"@payloadcms/eslint-config": "3.28.0",
|
|
58
|
+
"payload": "4.0.0-internal.fec2230"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
|
-
"payload": "4.0.0-internal.
|
|
61
|
+
"payload": "4.0.0-internal.fec2230"
|
|
62
62
|
},
|
|
63
63
|
"scripts": {
|
|
64
64
|
"build": "pnpm build:swc && pnpm build:types",
|