@payloadcms/db-sqlite 3.0.0-canary.95fcd13 → 3.0.0-canary.96477cf
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/README.md +1 -1
- package/dist/connect.d.ts.map +1 -1
- package/dist/connect.js +15 -3
- package/dist/connect.js.map +1 -1
- package/dist/countDistinct.d.ts.map +1 -1
- package/dist/countDistinct.js +3 -3
- package/dist/countDistinct.js.map +1 -1
- package/dist/createMigration.d.ts.map +1 -1
- package/dist/createMigration.js +4 -1
- package/dist/createMigration.js.map +1 -1
- package/dist/getMigrationTemplate.d.ts +1 -0
- package/dist/getMigrationTemplate.d.ts.map +1 -1
- package/dist/getMigrationTemplate.js +3 -2
- package/dist/getMigrationTemplate.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -3
- package/dist/index.js.map +1 -1
- package/dist/init.d.ts.map +1 -1
- package/dist/init.js +34 -4
- package/dist/init.js.map +1 -1
- package/dist/schema/build.d.ts +15 -2
- package/dist/schema/build.d.ts.map +1 -1
- package/dist/schema/build.js +17 -8
- package/dist/schema/build.js.map +1 -1
- package/dist/schema/createIndex.d.ts.map +1 -1
- package/dist/schema/createIndex.js +3 -1
- package/dist/schema/createIndex.js.map +1 -1
- package/dist/schema/traverseFields.d.ts +7 -2
- package/dist/schema/traverseFields.d.ts.map +1 -1
- package/dist/schema/traverseFields.js +179 -61
- package/dist/schema/traverseFields.js.map +1 -1
- package/dist/schema/withDefault.d.ts.map +1 -1
- package/dist/schema/withDefault.js +3 -1
- package/dist/schema/withDefault.js.map +1 -1
- package/dist/types.d.ts +42 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +9 -7
package/README.md
CHANGED
package/dist/connect.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAQtC,eAAO,MAAM,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAQtC,eAAO,MAAM,OAAO,EAAE,OAoDrB,CAAA"}
|
package/dist/connect.js
CHANGED
|
@@ -28,15 +28,27 @@ export const connect = async function connect(options = {
|
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
30
|
} catch (err) {
|
|
31
|
-
this.payload.logger.error(
|
|
32
|
-
|
|
31
|
+
this.payload.logger.error({
|
|
32
|
+
err,
|
|
33
|
+
msg: `Error: cannot connect to SQLite: ${err.message}`
|
|
34
|
+
});
|
|
35
|
+
if (typeof this.rejectInitializing === 'function') {
|
|
36
|
+
this.rejectInitializing();
|
|
37
|
+
}
|
|
33
38
|
process.exit(1);
|
|
34
39
|
}
|
|
35
40
|
// Only push schema if not in production
|
|
36
41
|
if (process.env.NODE_ENV !== 'production' && process.env.PAYLOAD_MIGRATING !== 'true' && this.push !== false) {
|
|
37
42
|
await pushDevSchema(this);
|
|
38
43
|
}
|
|
39
|
-
if (typeof this.resolveInitializing === 'function')
|
|
44
|
+
if (typeof this.resolveInitializing === 'function') {
|
|
45
|
+
this.resolveInitializing();
|
|
46
|
+
}
|
|
47
|
+
if (process.env.NODE_ENV === 'production' && this.prodMigrations) {
|
|
48
|
+
await this.migrate({
|
|
49
|
+
migrations: this.prodMigrations
|
|
50
|
+
});
|
|
51
|
+
}
|
|
40
52
|
};
|
|
41
53
|
|
|
42
54
|
//# sourceMappingURL=connect.js.map
|
package/dist/connect.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/connect.ts"],"sourcesContent":["import type { DrizzleAdapter } from '@payloadcms/drizzle/types'\nimport type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { Connect } from 'payload'\n\nimport { createClient } from '@libsql/client'\nimport { pushDevSchema } from '@payloadcms/drizzle'\nimport { drizzle } from 'drizzle-orm/libsql'\n\nimport type { SQLiteAdapter } from './types.js'\n\nexport const connect: Connect = async function connect(\n this: SQLiteAdapter,\n options = {\n hotReload: false,\n },\n) {\n const { hotReload } = options\n\n this.schema = {\n ...this.tables,\n ...this.relations,\n }\n\n try {\n if (!this.client) {\n this.client = createClient(this.clientConfig)\n }\n\n const logger = this.logger || false\n this.drizzle = drizzle(this.client, { logger, schema: this.schema }) as LibSQLDatabase\n\n if (!hotReload) {\n if (process.env.PAYLOAD_DROP_DATABASE === 'true') {\n this.payload.logger.info(`---- DROPPING TABLES ----`)\n await this.dropDatabase({ adapter: this })\n this.payload.logger.info('---- DROPPED TABLES ----')\n }\n }\n } catch (err) {\n this.payload.logger.error(`Error: cannot connect to SQLite
|
|
1
|
+
{"version":3,"sources":["../src/connect.ts"],"sourcesContent":["import type { DrizzleAdapter } from '@payloadcms/drizzle/types'\nimport type { LibSQLDatabase } from 'drizzle-orm/libsql'\nimport type { Connect } from 'payload'\n\nimport { createClient } from '@libsql/client'\nimport { pushDevSchema } from '@payloadcms/drizzle'\nimport { drizzle } from 'drizzle-orm/libsql'\n\nimport type { SQLiteAdapter } from './types.js'\n\nexport const connect: Connect = async function connect(\n this: SQLiteAdapter,\n options = {\n hotReload: false,\n },\n) {\n const { hotReload } = options\n\n this.schema = {\n ...this.tables,\n ...this.relations,\n }\n\n try {\n if (!this.client) {\n this.client = createClient(this.clientConfig)\n }\n\n const logger = this.logger || false\n this.drizzle = drizzle(this.client, { logger, schema: this.schema }) as LibSQLDatabase\n\n if (!hotReload) {\n if (process.env.PAYLOAD_DROP_DATABASE === 'true') {\n this.payload.logger.info(`---- DROPPING TABLES ----`)\n await this.dropDatabase({ adapter: this })\n this.payload.logger.info('---- DROPPED TABLES ----')\n }\n }\n } catch (err) {\n this.payload.logger.error({ err, msg: `Error: cannot connect to SQLite: ${err.message}` })\n if (typeof this.rejectInitializing === 'function') {\n this.rejectInitializing()\n }\n process.exit(1)\n }\n\n // Only push schema if not in production\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.PAYLOAD_MIGRATING !== 'true' &&\n this.push !== false\n ) {\n await pushDevSchema(this as unknown as DrizzleAdapter)\n }\n\n if (typeof this.resolveInitializing === 'function') {\n this.resolveInitializing()\n }\n\n if (process.env.NODE_ENV === 'production' && this.prodMigrations) {\n await this.migrate({ migrations: this.prodMigrations })\n }\n}\n"],"names":["createClient","pushDevSchema","drizzle","connect","options","hotReload","schema","tables","relations","client","clientConfig","logger","process","env","PAYLOAD_DROP_DATABASE","payload","info","dropDatabase","adapter","err","error","msg","message","rejectInitializing","exit","NODE_ENV","PAYLOAD_MIGRATING","push","resolveInitializing","prodMigrations","migrate","migrations"],"mappings":"AAIA,SAASA,YAAY,QAAQ,iBAAgB;AAC7C,SAASC,aAAa,QAAQ,sBAAqB;AACnD,SAASC,OAAO,QAAQ,qBAAoB;AAI5C,OAAO,MAAMC,UAAmB,eAAeA,QAE7CC,UAAU;IACRC,WAAW;AACb,CAAC;IAED,MAAM,EAAEA,SAAS,EAAE,GAAGD;IAEtB,IAAI,CAACE,MAAM,GAAG;QACZ,GAAG,IAAI,CAACC,MAAM;QACd,GAAG,IAAI,CAACC,SAAS;IACnB;IAEA,IAAI;QACF,IAAI,CAAC,IAAI,CAACC,MAAM,EAAE;YAChB,IAAI,CAACA,MAAM,GAAGT,aAAa,IAAI,CAACU,YAAY;QAC9C;QAEA,MAAMC,SAAS,IAAI,CAACA,MAAM,IAAI;QAC9B,IAAI,CAACT,OAAO,GAAGA,QAAQ,IAAI,CAACO,MAAM,EAAE;YAAEE;YAAQL,QAAQ,IAAI,CAACA,MAAM;QAAC;QAElE,IAAI,CAACD,WAAW;YACd,IAAIO,QAAQC,GAAG,CAACC,qBAAqB,KAAK,QAAQ;gBAChD,IAAI,CAACC,OAAO,CAACJ,MAAM,CAACK,IAAI,CAAC,CAAC,yBAAyB,CAAC;gBACpD,MAAM,IAAI,CAACC,YAAY,CAAC;oBAAEC,SAAS,IAAI;gBAAC;gBACxC,IAAI,CAACH,OAAO,CAACJ,MAAM,CAACK,IAAI,CAAC;YAC3B;QACF;IACF,EAAE,OAAOG,KAAK;QACZ,IAAI,CAACJ,OAAO,CAACJ,MAAM,CAACS,KAAK,CAAC;YAAED;YAAKE,KAAK,CAAC,iCAAiC,EAAEF,IAAIG,OAAO,CAAC,CAAC;QAAC;QACxF,IAAI,OAAO,IAAI,CAACC,kBAAkB,KAAK,YAAY;YACjD,IAAI,CAACA,kBAAkB;QACzB;QACAX,QAAQY,IAAI,CAAC;IACf;IAEA,wCAAwC;IACxC,IACEZ,QAAQC,GAAG,CAACY,QAAQ,KAAK,gBACzBb,QAAQC,GAAG,CAACa,iBAAiB,KAAK,UAClC,IAAI,CAACC,IAAI,KAAK,OACd;QACA,MAAM1B,cAAc,IAAI;IAC1B;IAEA,IAAI,OAAO,IAAI,CAAC2B,mBAAmB,KAAK,YAAY;QAClD,IAAI,CAACA,mBAAmB;IAC1B;IAEA,IAAIhB,QAAQC,GAAG,CAACY,QAAQ,KAAK,gBAAgB,IAAI,CAACI,cAAc,EAAE;QAChE,MAAM,IAAI,CAACC,OAAO,CAAC;YAAEC,YAAY,IAAI,CAACF,cAAc;QAAC;IACvD;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"countDistinct.d.ts","sourceRoot":"","sources":["../src/countDistinct.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAiB,MAAM,YAAY,CAAA;AAE9D,eAAO,MAAM,aAAa,EAAE,
|
|
1
|
+
{"version":3,"file":"countDistinct.d.ts","sourceRoot":"","sources":["../src/countDistinct.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAiB,MAAM,YAAY,CAAA;AAE9D,eAAO,MAAM,aAAa,EAAE,aA4B3B,CAAA"}
|
package/dist/countDistinct.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { chainMethods } from '@payloadcms/drizzle';
|
|
2
|
-
import { sql } from 'drizzle-orm';
|
|
2
|
+
import { count, sql } from 'drizzle-orm';
|
|
3
3
|
export const countDistinct = async function countDistinct({ db, joins, tableName, where }) {
|
|
4
4
|
const chainedMethods = [];
|
|
5
5
|
joins.forEach(({ condition, table })=>{
|
|
@@ -14,8 +14,8 @@ export const countDistinct = async function countDistinct({ db, joins, tableName
|
|
|
14
14
|
const countResult = await chainMethods({
|
|
15
15
|
methods: chainedMethods,
|
|
16
16
|
query: db.select({
|
|
17
|
-
count: sql`count
|
|
18
|
-
|
|
17
|
+
count: joins.length > 0 ? sql`count
|
|
18
|
+
(DISTINCT ${this.tables[tableName].id})`.mapWith(Number) : count()
|
|
19
19
|
}).from(this.tables[tableName]).where(where)
|
|
20
20
|
});
|
|
21
21
|
return Number(countResult[0].count);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/countDistinct.ts"],"sourcesContent":["import type { ChainedMethods } from '@payloadcms/drizzle/types'\n\nimport { chainMethods } from '@payloadcms/drizzle'\nimport { sql } from 'drizzle-orm'\n\nimport type { CountDistinct, SQLiteAdapter } from './types.js'\n\nexport const countDistinct: CountDistinct = async function countDistinct(\n this: SQLiteAdapter,\n { db, joins, tableName, where },\n) {\n const chainedMethods: ChainedMethods = []\n\n joins.forEach(({ condition, table }) => {\n chainedMethods.push({\n args: [table, condition],\n method: 'leftJoin',\n })\n })\n\n const countResult = await chainMethods({\n methods: chainedMethods,\n query: db\n .select({\n count
|
|
1
|
+
{"version":3,"sources":["../src/countDistinct.ts"],"sourcesContent":["import type { ChainedMethods } from '@payloadcms/drizzle/types'\n\nimport { chainMethods } from '@payloadcms/drizzle'\nimport { count, sql } from 'drizzle-orm'\n\nimport type { CountDistinct, SQLiteAdapter } from './types.js'\n\nexport const countDistinct: CountDistinct = async function countDistinct(\n this: SQLiteAdapter,\n { db, joins, tableName, where },\n) {\n const chainedMethods: ChainedMethods = []\n\n joins.forEach(({ condition, table }) => {\n chainedMethods.push({\n args: [table, condition],\n method: 'leftJoin',\n })\n })\n\n const countResult = await chainMethods({\n methods: chainedMethods,\n query: db\n .select({\n count:\n joins.length > 0\n ? sql`count\n (DISTINCT ${this.tables[tableName].id})`.mapWith(Number)\n : count(),\n })\n .from(this.tables[tableName])\n .where(where),\n })\n\n return Number(countResult[0].count)\n}\n"],"names":["chainMethods","count","sql","countDistinct","db","joins","tableName","where","chainedMethods","forEach","condition","table","push","args","method","countResult","methods","query","select","length","tables","id","mapWith","Number","from"],"mappings":"AAEA,SAASA,YAAY,QAAQ,sBAAqB;AAClD,SAASC,KAAK,EAAEC,GAAG,QAAQ,cAAa;AAIxC,OAAO,MAAMC,gBAA+B,eAAeA,cAEzD,EAAEC,EAAE,EAAEC,KAAK,EAAEC,SAAS,EAAEC,KAAK,EAAE;IAE/B,MAAMC,iBAAiC,EAAE;IAEzCH,MAAMI,OAAO,CAAC,CAAC,EAAEC,SAAS,EAAEC,KAAK,EAAE;QACjCH,eAAeI,IAAI,CAAC;YAClBC,MAAM;gBAACF;gBAAOD;aAAU;YACxBI,QAAQ;QACV;IACF;IAEA,MAAMC,cAAc,MAAMf,aAAa;QACrCgB,SAASR;QACTS,OAAOb,GACJc,MAAM,CAAC;YACNjB,OACEI,MAAMc,MAAM,GAAG,IACXjB,GAAG,CAAC;cACJ,EAAE,IAAI,CAACkB,MAAM,CAACd,UAAU,CAACe,EAAE,CAAC,CAAC,CAAC,CAACC,OAAO,CAACC,UACvCtB;QACR,GACCuB,IAAI,CAAC,IAAI,CAACJ,MAAM,CAACd,UAAU,EAC3BC,KAAK,CAACA;IACX;IAEA,OAAOgB,OAAOR,WAAW,CAAC,EAAE,CAACd,KAAK;AACpC,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createMigration.d.ts","sourceRoot":"","sources":["../src/createMigration.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAgB9C,eAAO,MAAM,eAAe,EAAE,
|
|
1
|
+
{"version":3,"file":"createMigration.d.ts","sourceRoot":"","sources":["../src/createMigration.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAgB9C,eAAO,MAAM,eAAe,EAAE,eAqG7B,CAAA"}
|
package/dist/createMigration.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import { createRequire } from 'module';
|
|
3
3
|
import path from 'path';
|
|
4
|
-
import { getPredefinedMigration } from 'payload';
|
|
4
|
+
import { getPredefinedMigration, writeMigrationIndex } from 'payload';
|
|
5
5
|
import prompts from 'prompts';
|
|
6
6
|
import { fileURLToPath } from 'url';
|
|
7
7
|
import { defaultDrizzleSnapshot } from './defaultSnapshot.js';
|
|
@@ -73,6 +73,9 @@ export const createMigration = async function createMigration({ file, forceAccep
|
|
|
73
73
|
imports,
|
|
74
74
|
upSQL: upSQL || ` // Migration code`
|
|
75
75
|
}));
|
|
76
|
+
writeMigrationIndex({
|
|
77
|
+
migrationsDir: payload.db.migrationDir
|
|
78
|
+
});
|
|
76
79
|
payload.logger.info({
|
|
77
80
|
msg: `Migration created at ${filePath}.ts`
|
|
78
81
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createMigration.ts"],"sourcesContent":["import type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { CreateMigration } from 'payload'\n\nimport fs from 'fs'\nimport { createRequire } from 'module'\nimport path from 'path'\nimport { getPredefinedMigration } from 'payload'\nimport prompts from 'prompts'\nimport { fileURLToPath } from 'url'\n\nimport type { SQLiteAdapter } from './types.js'\n\nimport { defaultDrizzleSnapshot } from './defaultSnapshot.js'\nimport { getMigrationTemplate } from './getMigrationTemplate.js'\n\nconst require = createRequire(import.meta.url)\n\nexport const createMigration: CreateMigration = async function createMigration(\n this: SQLiteAdapter,\n { file, forceAcceptWarning, migrationName, payload },\n) {\n const filename = fileURLToPath(import.meta.url)\n const dirname = path.dirname(filename)\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n const { generateSQLiteDrizzleJson, generateSQLiteMigration } = require('drizzle-kit/api')\n const drizzleJsonAfter = await generateSQLiteDrizzleJson(this.schema)\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n let imports: string = ''\n let downSQL: string\n let upSQL: string\n ;({ downSQL, imports, upSQL } = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n }))\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const name = migrationName || file?.split('/').slice(2).join('/')\n const fileName = `${timestamp}${name ? `_${name.replace(/\\W/g, '_')}` : ''}`\n\n const filePath = `${dir}/${fileName}`\n\n let drizzleJsonBefore = defaultDrizzleSnapshot as any\n\n if (!upSQL) {\n // Get latest migration snapshot\n const latestSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()?.[0]\n\n if (latestSnapshot) {\n drizzleJsonBefore = JSON.parse(\n fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'),\n ) as DrizzleSnapshotJSON\n }\n\n const sqlStatementsUp = await generateSQLiteMigration(drizzleJsonBefore, drizzleJsonAfter)\n const sqlStatementsDown = await generateSQLiteMigration(drizzleJsonAfter, drizzleJsonBefore)\n // need to create tables as separate statements\n const sqlExecute = 'await payload.db.drizzle.run(sql`'\n\n if (sqlStatementsUp?.length) {\n upSQL = sqlStatementsUp\n .map((statement) => `${sqlExecute}${statement?.replaceAll('`', '\\\\`')}\\`)`)\n .join('\\n')\n }\n if (sqlStatementsDown?.length) {\n downSQL = sqlStatementsDown\n .map((statement) => `${sqlExecute}${statement?.replaceAll('`', '\\\\`')}\\`)`)\n .join('\\n')\n }\n\n if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {\n const { confirm: shouldCreateBlankMigration } = await prompts(\n {\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message: 'No schema changes detected. Would you like to create a blank migration file?',\n },\n {\n onCancel: () => {\n process.exit(0)\n },\n },\n )\n\n if (!shouldCreateBlankMigration) {\n process.exit(0)\n }\n }\n\n // write schema\n fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n }\n\n // write migration\n fs.writeFileSync(\n `${filePath}.ts`,\n getMigrationTemplate({\n downSQL: downSQL || ` // Migration code`,\n imports,\n upSQL: upSQL || ` // Migration code`,\n }),\n )\n payload.logger.info({ msg: `Migration created at ${filePath}.ts` })\n}\n"],"names":["fs","createRequire","path","getPredefinedMigration","prompts","fileURLToPath","defaultDrizzleSnapshot","getMigrationTemplate","require","url","createMigration","file","forceAcceptWarning","migrationName","payload","filename","dirname","dir","db","migrationDir","existsSync","mkdirSync","generateSQLiteDrizzleJson","generateSQLiteMigration","drizzleJsonAfter","schema","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","imports","downSQL","upSQL","timestamp","name","slice","join","fileName","filePath","drizzleJsonBefore","latestSnapshot","readdirSync","filter","endsWith","sort","reverse","JSON","parse","readFileSync","sqlStatementsUp","sqlStatementsDown","sqlExecute","length","map","statement","replaceAll","confirm","shouldCreateBlankMigration","type","initial","message","onCancel","process","exit","writeFileSync","stringify","logger","info","msg"],"mappings":"AAGA,OAAOA,QAAQ,KAAI;AACnB,SAASC,aAAa,QAAQ,SAAQ;AACtC,OAAOC,UAAU,OAAM;AACvB,SAASC,sBAAsB,QAAQ,UAAS;
|
|
1
|
+
{"version":3,"sources":["../src/createMigration.ts"],"sourcesContent":["import type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { CreateMigration } from 'payload'\n\nimport fs from 'fs'\nimport { createRequire } from 'module'\nimport path from 'path'\nimport { getPredefinedMigration, writeMigrationIndex } from 'payload'\nimport prompts from 'prompts'\nimport { fileURLToPath } from 'url'\n\nimport type { SQLiteAdapter } from './types.js'\n\nimport { defaultDrizzleSnapshot } from './defaultSnapshot.js'\nimport { getMigrationTemplate } from './getMigrationTemplate.js'\n\nconst require = createRequire(import.meta.url)\n\nexport const createMigration: CreateMigration = async function createMigration(\n this: SQLiteAdapter,\n { file, forceAcceptWarning, migrationName, payload },\n) {\n const filename = fileURLToPath(import.meta.url)\n const dirname = path.dirname(filename)\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n const { generateSQLiteDrizzleJson, generateSQLiteMigration } = require('drizzle-kit/api')\n const drizzleJsonAfter = await generateSQLiteDrizzleJson(this.schema)\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n let imports: string = ''\n let downSQL: string\n let upSQL: string\n ;({ downSQL, imports, upSQL } = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n }))\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const name = migrationName || file?.split('/').slice(2).join('/')\n const fileName = `${timestamp}${name ? `_${name.replace(/\\W/g, '_')}` : ''}`\n\n const filePath = `${dir}/${fileName}`\n\n let drizzleJsonBefore = defaultDrizzleSnapshot as any\n\n if (!upSQL) {\n // Get latest migration snapshot\n const latestSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()?.[0]\n\n if (latestSnapshot) {\n drizzleJsonBefore = JSON.parse(\n fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'),\n ) as DrizzleSnapshotJSON\n }\n\n const sqlStatementsUp = await generateSQLiteMigration(drizzleJsonBefore, drizzleJsonAfter)\n const sqlStatementsDown = await generateSQLiteMigration(drizzleJsonAfter, drizzleJsonBefore)\n // need to create tables as separate statements\n const sqlExecute = 'await payload.db.drizzle.run(sql`'\n\n if (sqlStatementsUp?.length) {\n upSQL = sqlStatementsUp\n .map((statement) => `${sqlExecute}${statement?.replaceAll('`', '\\\\`')}\\`)`)\n .join('\\n')\n }\n if (sqlStatementsDown?.length) {\n downSQL = sqlStatementsDown\n .map((statement) => `${sqlExecute}${statement?.replaceAll('`', '\\\\`')}\\`)`)\n .join('\\n')\n }\n\n if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {\n const { confirm: shouldCreateBlankMigration } = await prompts(\n {\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message: 'No schema changes detected. Would you like to create a blank migration file?',\n },\n {\n onCancel: () => {\n process.exit(0)\n },\n },\n )\n\n if (!shouldCreateBlankMigration) {\n process.exit(0)\n }\n }\n\n // write schema\n fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n }\n\n // write migration\n fs.writeFileSync(\n `${filePath}.ts`,\n getMigrationTemplate({\n downSQL: downSQL || ` // Migration code`,\n imports,\n upSQL: upSQL || ` // Migration code`,\n }),\n )\n\n writeMigrationIndex({ migrationsDir: payload.db.migrationDir })\n\n payload.logger.info({ msg: `Migration created at ${filePath}.ts` })\n}\n"],"names":["fs","createRequire","path","getPredefinedMigration","writeMigrationIndex","prompts","fileURLToPath","defaultDrizzleSnapshot","getMigrationTemplate","require","url","createMigration","file","forceAcceptWarning","migrationName","payload","filename","dirname","dir","db","migrationDir","existsSync","mkdirSync","generateSQLiteDrizzleJson","generateSQLiteMigration","drizzleJsonAfter","schema","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","imports","downSQL","upSQL","timestamp","name","slice","join","fileName","filePath","drizzleJsonBefore","latestSnapshot","readdirSync","filter","endsWith","sort","reverse","JSON","parse","readFileSync","sqlStatementsUp","sqlStatementsDown","sqlExecute","length","map","statement","replaceAll","confirm","shouldCreateBlankMigration","type","initial","message","onCancel","process","exit","writeFileSync","stringify","migrationsDir","logger","info","msg"],"mappings":"AA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X,GACA;gBACEC,UAAU;oBACRC,QAAQC,IAAI,CAAC;gBACf;YACF;YAGF,IAAI,CAACN,4BAA4B;gBAC/BK,QAAQC,IAAI,CAAC;YACf;QACF;QAEA,eAAe;QACfpE,GAAGqE,aAAa,CAAC,CAAC,EAAE1B,SAAS,KAAK,CAAC,EAAEQ,KAAKmB,SAAS,CAAC7C,kBAAkB,MAAM;IAC9E;IAEA,kBAAkB;IAClBzB,GAAGqE,aAAa,CACd,CAAC,EAAE1B,SAAS,GAAG,CAAC,EAChBnC,qBAAqB;QACnB4B,SAASA,WAAW,CAAC,mBAAmB,CAAC;QACzCD;QACAE,OAAOA,SAAS,CAAC,mBAAmB,CAAC;IACvC;IAGFjC,oBAAoB;QAAEmE,eAAexD,QAAQI,EAAE,CAACC,YAAY;IAAC;IAE7DL,QAAQyD,MAAM,CAACC,IAAI,CAAC;QAAEC,KAAK,CAAC,qBAAqB,EAAE/B,SAAS,GAAG,CAAC;IAAC;AACnE,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getMigrationTemplate.d.ts","sourceRoot":"","sources":["../src/getMigrationTemplate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAA;AAEpD,eAAO,MAAM,oBAAoB,iCAI9B,qBAAqB,KAAG,MAS1B,CAAA"}
|
|
1
|
+
{"version":3,"file":"getMigrationTemplate.d.ts","sourceRoot":"","sources":["../src/getMigrationTemplate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAA;AAEpD,eAAO,MAAM,MAAM,SAAU,MAAM,WAIpB,CAAA;AAEf,eAAO,MAAM,oBAAoB,iCAI9B,qBAAqB,KAAG,MAS1B,CAAA"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
+
export const indent = (text)=>text.split('\n').map((line)=>` ${line}`).join('\n');
|
|
1
2
|
export const getMigrationTemplate = ({ downSQL, imports, upSQL })=>`import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-sqlite'
|
|
2
3
|
${imports ? `${imports}\n` : ''}
|
|
3
4
|
export async function up({ payload, req }: MigrateUpArgs): Promise<void> {
|
|
4
|
-
${upSQL}
|
|
5
|
+
${indent(upSQL)}
|
|
5
6
|
}
|
|
6
7
|
|
|
7
8
|
export async function down({ payload, req }: MigrateDownArgs): Promise<void> {
|
|
8
|
-
${downSQL}
|
|
9
|
+
${indent(downSQL)}
|
|
9
10
|
}
|
|
10
11
|
`;
|
|
11
12
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/getMigrationTemplate.ts"],"sourcesContent":["import type { MigrationTemplateArgs } from 'payload'\n\nexport const getMigrationTemplate = ({\n downSQL,\n imports,\n upSQL,\n}: MigrationTemplateArgs): string => `import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-sqlite'\n${imports ? `${imports}\\n` : ''}\nexport async function up({ payload, req }: MigrateUpArgs): Promise<void> {\n${upSQL}\n}\n\nexport async function down({ payload, req }: MigrateDownArgs): Promise<void> {\n${downSQL}\n}\n`\n"],"names":["getMigrationTemplate","downSQL","imports","upSQL"],"mappings":"AAEA,OAAO,MAAMA,uBAAuB,CAAC,EACnCC,OAAO,EACPC,OAAO,EACPC,KAAK,EACiB,GAAa,CAAC;AACtC,EAAED,UAAU,CAAC,EAAEA,QAAQ,EAAE,CAAC,GAAG,GAAG;;AAEhC,
|
|
1
|
+
{"version":3,"sources":["../src/getMigrationTemplate.ts"],"sourcesContent":["import type { MigrationTemplateArgs } from 'payload'\n\nexport const indent = (text: string) =>\n text\n .split('\\n')\n .map((line) => ` ${line}`)\n .join('\\n')\n\nexport const getMigrationTemplate = ({\n downSQL,\n imports,\n upSQL,\n}: MigrationTemplateArgs): string => `import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-sqlite'\n${imports ? `${imports}\\n` : ''}\nexport async function up({ payload, req }: MigrateUpArgs): Promise<void> {\n${indent(upSQL)}\n}\n\nexport async function down({ payload, req }: MigrateDownArgs): Promise<void> {\n${indent(downSQL)}\n}\n`\n"],"names":["indent","text","split","map","line","join","getMigrationTemplate","downSQL","imports","upSQL"],"mappings":"AAEA,OAAO,MAAMA,SAAS,CAACC,OACrBA,KACGC,KAAK,CAAC,MACNC,GAAG,CAAC,CAACC,OAAS,CAAC,EAAE,EAAEA,KAAK,CAAC,EACzBC,IAAI,CAAC,MAAK;AAEf,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,OAAO,EACPC,OAAO,EACPC,KAAK,EACiB,GAAa,CAAC;AACtC,EAAED,UAAU,CAAC,EAAEA,QAAQ,EAAE,CAAC,GAAG,GAAG;;AAEhC,EAAER,OAAOS,OAAO;;;;AAIhB,EAAET,OAAOO,SAAS;;AAElB,CAAC,CAAA"}
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAW,MAAM,SAAS,CAAA;AAqC1D,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAgBrD,YAAY,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAEhE,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAA;AAEjC,wBAAgB,aAAa,CAAC,IAAI,EAAE,IAAI,GAAG,kBAAkB,CAAC,aAAa,CAAC,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAW,MAAM,SAAS,CAAA;AAqC1D,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAgBrD,YAAY,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAEhE,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAA;AAEjC,wBAAgB,aAAa,CAAC,IAAI,EAAE,IAAI,GAAG,kBAAkB,CAAC,aAAa,CAAC,CAyG3E"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { beginTransaction, commitTransaction, count, create, createGlobal, createGlobalVersion, createVersion, deleteMany, deleteOne, deleteVersions, destroy, find, findGlobal, findGlobalVersions, findMigrationDir, findOne, findVersions, migrate, migrateDown, migrateFresh, migrateRefresh, migrateReset, migrateStatus, operatorMap, queryDrafts, rollbackTransaction, updateGlobal, updateGlobalVersion, updateOne, updateVersion } from '@payloadcms/drizzle';
|
|
2
2
|
import { like } from 'drizzle-orm';
|
|
3
|
-
import { createDatabaseAdapter } from 'payload';
|
|
3
|
+
import { createDatabaseAdapter, defaultBeginTransaction } from 'payload';
|
|
4
4
|
import { connect } from './connect.js';
|
|
5
5
|
import { countDistinct } from './countDistinct.js';
|
|
6
6
|
import { convertPathToJSONTraversal } from './createJSONQuery/convertPathToJSONTraversal.js';
|
|
@@ -34,6 +34,8 @@ export function sqliteAdapter(args) {
|
|
|
34
34
|
};
|
|
35
35
|
return createDatabaseAdapter({
|
|
36
36
|
name: 'sqlite',
|
|
37
|
+
afterSchemaInit: args.afterSchemaInit ?? [],
|
|
38
|
+
beforeSchemaInit: args.beforeSchemaInit ?? [],
|
|
37
39
|
client: undefined,
|
|
38
40
|
clientConfig: args.client,
|
|
39
41
|
defaultDrizzleSnapshot,
|
|
@@ -48,6 +50,7 @@ export function sqliteAdapter(args) {
|
|
|
48
50
|
localesSuffix: args.localesSuffix || '_locales',
|
|
49
51
|
logger: args.logger,
|
|
50
52
|
operators,
|
|
53
|
+
prodMigrations: args.prodMigrations,
|
|
51
54
|
push: args.push,
|
|
52
55
|
relations: {},
|
|
53
56
|
relationshipsSuffix: args.relationshipsSuffix || '_rels',
|
|
@@ -59,7 +62,7 @@ export function sqliteAdapter(args) {
|
|
|
59
62
|
transactionOptions: args.transactionOptions || undefined,
|
|
60
63
|
versionsSuffix: args.versionsSuffix || '_v',
|
|
61
64
|
// DatabaseAdapter
|
|
62
|
-
beginTransaction: args.transactionOptions ? beginTransaction :
|
|
65
|
+
beginTransaction: args.transactionOptions ? beginTransaction : defaultBeginTransaction(),
|
|
63
66
|
commitTransaction,
|
|
64
67
|
connect,
|
|
65
68
|
convertPathToJSONTraversal,
|
|
@@ -93,6 +96,7 @@ export function sqliteAdapter(args) {
|
|
|
93
96
|
migrateReset,
|
|
94
97
|
migrateStatus,
|
|
95
98
|
migrationDir,
|
|
99
|
+
packageName: '@payloadcms/db-sqlite',
|
|
96
100
|
payload,
|
|
97
101
|
queryDrafts,
|
|
98
102
|
rejectInitializing,
|
|
@@ -102,7 +106,8 @@ export function sqliteAdapter(args) {
|
|
|
102
106
|
updateGlobal,
|
|
103
107
|
updateGlobalVersion,
|
|
104
108
|
updateOne,
|
|
105
|
-
updateVersion
|
|
109
|
+
updateVersion,
|
|
110
|
+
upsert: updateOne
|
|
106
111
|
});
|
|
107
112
|
}
|
|
108
113
|
return {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Operators } from '@payloadcms/drizzle'\nimport type { DatabaseAdapterObj, Payload } from 'payload'\n\nimport {\n beginTransaction,\n commitTransaction,\n count,\n create,\n createGlobal,\n createGlobalVersion,\n createVersion,\n deleteMany,\n deleteOne,\n deleteVersions,\n destroy,\n find,\n findGlobal,\n findGlobalVersions,\n findMigrationDir,\n findOne,\n findVersions,\n migrate,\n migrateDown,\n migrateFresh,\n migrateRefresh,\n migrateReset,\n migrateStatus,\n operatorMap,\n queryDrafts,\n rollbackTransaction,\n updateGlobal,\n updateGlobalVersion,\n updateOne,\n updateVersion,\n} from '@payloadcms/drizzle'\nimport { like } from 'drizzle-orm'\nimport { createDatabaseAdapter } from 'payload'\n\nimport type { Args, SQLiteAdapter } from './types.js'\n\nimport { connect } from './connect.js'\nimport { countDistinct } from './countDistinct.js'\nimport { convertPathToJSONTraversal } from './createJSONQuery/convertPathToJSONTraversal.js'\nimport { createJSONQuery } from './createJSONQuery/index.js'\nimport { createMigration } from './createMigration.js'\nimport { defaultDrizzleSnapshot } from './defaultSnapshot.js'\nimport { deleteWhere } from './deleteWhere.js'\nimport { dropDatabase } from './dropDatabase.js'\nimport { execute } from './execute.js'\nimport { getMigrationTemplate } from './getMigrationTemplate.js'\nimport { init } from './init.js'\nimport { insert } from './insert.js'\nimport { requireDrizzleKit } from './requireDrizzleKit.js'\n\nexport type { MigrateDownArgs, MigrateUpArgs } from './types.js'\n\nexport { sql } from 'drizzle-orm'\n\nexport function sqliteAdapter(args: Args): DatabaseAdapterObj<SQLiteAdapter> {\n const postgresIDType = args.idType || 'serial'\n const payloadIDType = postgresIDType === 'serial' ? 'number' : 'text'\n\n function adapter({ payload }: { payload: Payload }) {\n const migrationDir = findMigrationDir(args.migrationDir)\n let resolveInitializing\n let rejectInitializing\n\n const initializing = new Promise<void>((res, rej) => {\n resolveInitializing = res\n rejectInitializing = rej\n })\n\n // sqlite's like operator is case-insensitive, so we overwrite the DrizzleAdapter operators to not use ilike\n const operators = {\n ...operatorMap,\n contains: like,\n like,\n } as unknown as Operators\n\n return createDatabaseAdapter<SQLiteAdapter>({\n name: 'sqlite',\n client: undefined,\n clientConfig: args.client,\n defaultDrizzleSnapshot,\n drizzle: undefined,\n features: {\n json: true,\n },\n fieldConstraints: {},\n getMigrationTemplate,\n idType: postgresIDType,\n initializing,\n localesSuffix: args.localesSuffix || '_locales',\n logger: args.logger,\n operators,\n push: args.push,\n relations: {},\n relationshipsSuffix: args.relationshipsSuffix || '_rels',\n schema: {},\n schemaName: args.schemaName,\n sessions: {},\n tableNameMap: new Map<string, string>(),\n tables: {},\n transactionOptions: args.transactionOptions || undefined,\n versionsSuffix: args.versionsSuffix || '_v',\n\n // DatabaseAdapter\n beginTransaction: args.transactionOptions ? beginTransaction :
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Operators } from '@payloadcms/drizzle'\nimport type { DatabaseAdapterObj, Payload } from 'payload'\n\nimport {\n beginTransaction,\n commitTransaction,\n count,\n create,\n createGlobal,\n createGlobalVersion,\n createVersion,\n deleteMany,\n deleteOne,\n deleteVersions,\n destroy,\n find,\n findGlobal,\n findGlobalVersions,\n findMigrationDir,\n findOne,\n findVersions,\n migrate,\n migrateDown,\n migrateFresh,\n migrateRefresh,\n migrateReset,\n migrateStatus,\n operatorMap,\n queryDrafts,\n rollbackTransaction,\n updateGlobal,\n updateGlobalVersion,\n updateOne,\n updateVersion,\n} from '@payloadcms/drizzle'\nimport { like } from 'drizzle-orm'\nimport { createDatabaseAdapter, defaultBeginTransaction } from 'payload'\n\nimport type { Args, SQLiteAdapter } from './types.js'\n\nimport { connect } from './connect.js'\nimport { countDistinct } from './countDistinct.js'\nimport { convertPathToJSONTraversal } from './createJSONQuery/convertPathToJSONTraversal.js'\nimport { createJSONQuery } from './createJSONQuery/index.js'\nimport { createMigration } from './createMigration.js'\nimport { defaultDrizzleSnapshot } from './defaultSnapshot.js'\nimport { deleteWhere } from './deleteWhere.js'\nimport { dropDatabase } from './dropDatabase.js'\nimport { execute } from './execute.js'\nimport { getMigrationTemplate } from './getMigrationTemplate.js'\nimport { init } from './init.js'\nimport { insert } from './insert.js'\nimport { requireDrizzleKit } from './requireDrizzleKit.js'\n\nexport type { MigrateDownArgs, MigrateUpArgs } from './types.js'\n\nexport { sql } from 'drizzle-orm'\n\nexport function sqliteAdapter(args: Args): DatabaseAdapterObj<SQLiteAdapter> {\n const postgresIDType = args.idType || 'serial'\n const payloadIDType = postgresIDType === 'serial' ? 'number' : 'text'\n\n function adapter({ payload }: { payload: Payload }) {\n const migrationDir = findMigrationDir(args.migrationDir)\n let resolveInitializing\n let rejectInitializing\n\n const initializing = new Promise<void>((res, rej) => {\n resolveInitializing = res\n rejectInitializing = rej\n })\n\n // sqlite's like operator is case-insensitive, so we overwrite the DrizzleAdapter operators to not use ilike\n const operators = {\n ...operatorMap,\n contains: like,\n like,\n } as unknown as Operators\n\n return createDatabaseAdapter<SQLiteAdapter>({\n name: 'sqlite',\n afterSchemaInit: args.afterSchemaInit ?? [],\n beforeSchemaInit: args.beforeSchemaInit ?? [],\n client: undefined,\n clientConfig: args.client,\n defaultDrizzleSnapshot,\n drizzle: undefined,\n features: {\n json: true,\n },\n fieldConstraints: {},\n getMigrationTemplate,\n idType: postgresIDType,\n initializing,\n localesSuffix: args.localesSuffix || '_locales',\n logger: args.logger,\n operators,\n prodMigrations: args.prodMigrations,\n push: args.push,\n relations: {},\n relationshipsSuffix: args.relationshipsSuffix || '_rels',\n schema: {},\n schemaName: args.schemaName,\n sessions: {},\n tableNameMap: new Map<string, string>(),\n tables: {},\n transactionOptions: args.transactionOptions || undefined,\n versionsSuffix: args.versionsSuffix || '_v',\n\n // DatabaseAdapter\n beginTransaction: args.transactionOptions ? beginTransaction : defaultBeginTransaction(),\n commitTransaction,\n connect,\n convertPathToJSONTraversal,\n count,\n countDistinct,\n create,\n createGlobal,\n createGlobalVersion,\n createJSONQuery,\n createMigration,\n createVersion,\n defaultIDType: payloadIDType,\n deleteMany,\n deleteOne,\n deleteVersions,\n deleteWhere,\n destroy,\n dropDatabase,\n execute,\n find,\n findGlobal,\n findGlobalVersions,\n findOne,\n findVersions,\n init,\n insert,\n migrate,\n migrateDown,\n migrateFresh,\n migrateRefresh,\n migrateReset,\n migrateStatus,\n migrationDir,\n packageName: '@payloadcms/db-sqlite',\n payload,\n queryDrafts,\n rejectInitializing,\n requireDrizzleKit,\n resolveInitializing,\n rollbackTransaction,\n updateGlobal,\n updateGlobalVersion,\n updateOne,\n updateVersion,\n upsert: updateOne,\n })\n }\n\n return {\n defaultIDType: payloadIDType,\n init: adapter,\n }\n}\n"],"names":["beginTransaction","commitTransaction","count","create","createGlobal","createGlobalVersion","createVersion","deleteMany","deleteOne","deleteVersions","destroy","find","findGlobal","findGlobalVersions","findMigrationDir","findOne","findVersions","migrate","migrateDown","migrateFresh","migrateRefresh","migrateReset","migrateStatus","operatorMap","queryDrafts","rollbackTransaction","updateGlobal","updateGlobalVersion","updateOne","updateVersion","like","createDatabaseAdapter","defaultBeginTransaction","connect","countDistinct","convertPathToJSONTraversal","createJSONQuery","createMigration","defaultDrizzleSnapshot","deleteWhere","dropDatabase","execute","getMigrationTemplate","init","insert","requireDrizzleKit","sql","sqliteAdapter","args","postgresIDType","idType","payloadIDType","adapter","payload","migrationDir","resolveInitializing","rejectInitializing","initializing","Promise","res","rej","operators","contains","name","afterSchemaInit","beforeSchemaInit","client","undefined","clientConfig","drizzle","features","json","fieldConstraints","localesSuffix","logger","prodMigrations","push","relations","relationshipsSuffix","schema","schemaName","sessions","tableNameMap","Map","tables","transactionOptions","versionsSuffix","defaultIDType","packageName","upsert"],"mappings":"AAGA,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,KAAK,EACLC,MAAM,EACNC,YAAY,EACZC,mBAAmB,EACnBC,aAAa,EACbC,UAAU,EACVC,SAAS,EACTC,cAAc,EACdC,OAAO,EACPC,IAAI,EACJC,UAAU,EACVC,kBAAkB,EAClBC,gBAAgB,EAChBC,OAAO,EACPC,YAAY,EACZC,OAAO,EACPC,WAAW,EACXC,YAAY,EACZC,cAAc,EACdC,YAAY,EACZC,aAAa,EACbC,WAAW,EACXC,WAAW,EACXC,mBAAmB,EACnBC,YAAY,EACZC,mBAAmB,EACnBC,SAAS,EACTC,aAAa,QACR,sBAAqB;AAC5B,SAASC,IAAI,QAAQ,cAAa;AAClC,SAASC,qBAAqB,EAAEC,uBAAuB,QAAQ,UAAS;AAIxE,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,sBAAsB,QAAQ,uBAA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C,QAAQ,CAAC;YACTC,oBAAoBrC,KAAKqC,kBAAkB,IAAIlB;YAC/CmB,gBAAgBtC,KAAKsC,cAAc,IAAI;YAEvC,kBAAkB;YAClBtF,kBAAkBgD,KAAKqC,kBAAkB,GAAGrF,mBAAmBgC;YAC/D/B;YACAgC;YACAE;YACAjC;YACAgC;YACA/B;YACAC;YACAC;YACA+B;YACAC;YACA/B;YACAiF,eAAepC;YACf5C;YACAC;YACAC;YACA8B;YACA7B;YACA8B;YACAC;YACA9B;YACAC;YACAC;YACAE;YACAC;YACA2B;YACAC;YACA3B;YACAC;YACAC;YACAC;YACAC;YACAC;YACAgC;YACAkC,aAAa;YACbnC;YACA7B;YACAgC;YACAX;YACAU;YACA9B;YACAC;YACAC;YACAC;YACAC;YACA4D,QAAQ7D;QACV;IACF;IAEA,OAAO;QACL2D,eAAepC;QACfR,MAAMS;IACR;AACF"}
|
package/dist/init.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAA6B,MAAM,SAAS,CAAA;AAY9D,eAAO,MAAM,IAAI,EAAE,IA6HlB,CAAA"}
|
package/dist/init.js
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
|
-
|
|
1
|
+
import { createTableName, executeSchemaHooks } from '@payloadcms/drizzle';
|
|
2
|
+
import { uniqueIndex } from 'drizzle-orm/sqlite-core';
|
|
2
3
|
import { buildVersionCollectionFields, buildVersionGlobalFields } from 'payload';
|
|
3
4
|
import toSnakeCase from 'to-snake-case';
|
|
4
5
|
import { buildTable } from './schema/build.js';
|
|
5
|
-
export const init = function init() {
|
|
6
|
+
export const init = async function init() {
|
|
6
7
|
let locales;
|
|
8
|
+
await executeSchemaHooks({
|
|
9
|
+
type: 'beforeSchemaInit',
|
|
10
|
+
adapter: this
|
|
11
|
+
});
|
|
7
12
|
if (this.payload.config.localization) {
|
|
8
13
|
locales = this.payload.config.localization.locales.map(({ code })=>code);
|
|
9
14
|
}
|
|
@@ -23,6 +28,26 @@ export const init = function init() {
|
|
|
23
28
|
});
|
|
24
29
|
this.payload.config.collections.forEach((collection)=>{
|
|
25
30
|
const tableName = this.tableNameMap.get(toSnakeCase(collection.slug));
|
|
31
|
+
const config = this.payload.config;
|
|
32
|
+
const baseExtraConfig = {};
|
|
33
|
+
if (collection.upload.filenameCompoundIndex) {
|
|
34
|
+
const indexName = `${tableName}_filename_compound_idx`;
|
|
35
|
+
baseExtraConfig.filename_compound_index = (cols)=>{
|
|
36
|
+
const colsConstraint = collection.upload.filenameCompoundIndex.map((f)=>{
|
|
37
|
+
return cols[f];
|
|
38
|
+
});
|
|
39
|
+
return uniqueIndex(indexName).on(colsConstraint[0], ...colsConstraint.slice(1));
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
if (collection.upload.filenameCompoundIndex) {
|
|
43
|
+
const indexName = `${tableName}_filename_compound_idx`;
|
|
44
|
+
baseExtraConfig.filename_compound_index = (cols)=>{
|
|
45
|
+
const colsConstraint = collection.upload.filenameCompoundIndex.map((f)=>{
|
|
46
|
+
return cols[f];
|
|
47
|
+
});
|
|
48
|
+
return uniqueIndex(indexName).on(colsConstraint[0], ...colsConstraint.slice(1));
|
|
49
|
+
};
|
|
50
|
+
}
|
|
26
51
|
buildTable({
|
|
27
52
|
adapter: this,
|
|
28
53
|
disableNotNull: !!collection?.versions?.drafts,
|
|
@@ -35,7 +60,7 @@ export const init = function init() {
|
|
|
35
60
|
});
|
|
36
61
|
if (collection.versions) {
|
|
37
62
|
const versionsTableName = this.tableNameMap.get(`_${toSnakeCase(collection.slug)}${this.versionsSuffix}`);
|
|
38
|
-
const versionFields = buildVersionCollectionFields(collection);
|
|
63
|
+
const versionFields = buildVersionCollectionFields(config, collection);
|
|
39
64
|
buildTable({
|
|
40
65
|
adapter: this,
|
|
41
66
|
disableNotNull: !!collection.versions?.drafts,
|
|
@@ -70,7 +95,8 @@ export const init = function init() {
|
|
|
70
95
|
versions: true,
|
|
71
96
|
versionsCustomName: true
|
|
72
97
|
});
|
|
73
|
-
const
|
|
98
|
+
const config = this.payload.config;
|
|
99
|
+
const versionFields = buildVersionGlobalFields(config, global);
|
|
74
100
|
buildTable({
|
|
75
101
|
adapter: this,
|
|
76
102
|
disableNotNull: !!global.versions?.drafts,
|
|
@@ -83,6 +109,10 @@ export const init = function init() {
|
|
|
83
109
|
});
|
|
84
110
|
}
|
|
85
111
|
});
|
|
112
|
+
await executeSchemaHooks({
|
|
113
|
+
type: 'afterSchemaInit',
|
|
114
|
+
adapter: this
|
|
115
|
+
});
|
|
86
116
|
};
|
|
87
117
|
|
|
88
118
|
//# sourceMappingURL=init.js.map
|
package/dist/init.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/init.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"sources":["../src/init.ts"],"sourcesContent":["import type { DrizzleAdapter } from '@payloadcms/drizzle/types'\nimport type { Init, SanitizedCollectionConfig } from 'payload'\n\nimport { createTableName, executeSchemaHooks } from '@payloadcms/drizzle'\nimport { uniqueIndex } from 'drizzle-orm/sqlite-core'\nimport { buildVersionCollectionFields, buildVersionGlobalFields } from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { BaseExtraConfig } from './schema/build.js'\nimport type { SQLiteAdapter } from './types.js'\n\nimport { buildTable } from './schema/build.js'\n\nexport const init: Init = async function init(this: SQLiteAdapter) {\n let locales: [string, ...string[]] | undefined\n await executeSchemaHooks({ type: 'beforeSchemaInit', adapter: this })\n\n if (this.payload.config.localization) {\n locales = this.payload.config.localization.locales.map(({ code }) => code) as [\n string,\n ...string[],\n ]\n }\n\n this.payload.config.collections.forEach((collection: SanitizedCollectionConfig) => {\n createTableName({\n adapter: this as unknown as DrizzleAdapter,\n config: collection,\n })\n\n if (collection.versions) {\n createTableName({\n adapter: this as unknown as DrizzleAdapter,\n config: collection,\n versions: true,\n versionsCustomName: true,\n })\n }\n })\n this.payload.config.collections.forEach((collection: SanitizedCollectionConfig) => {\n const tableName = this.tableNameMap.get(toSnakeCase(collection.slug))\n const config = this.payload.config\n\n const baseExtraConfig: BaseExtraConfig = {}\n\n if (collection.upload.filenameCompoundIndex) {\n const indexName = `${tableName}_filename_compound_idx`\n\n baseExtraConfig.filename_compound_index = (cols) => {\n const colsConstraint = collection.upload.filenameCompoundIndex.map((f) => {\n return cols[f]\n })\n return uniqueIndex(indexName).on(colsConstraint[0], ...colsConstraint.slice(1))\n }\n }\n\n if (collection.upload.filenameCompoundIndex) {\n const indexName = `${tableName}_filename_compound_idx`\n\n baseExtraConfig.filename_compound_index = (cols) => {\n const colsConstraint = collection.upload.filenameCompoundIndex.map((f) => {\n return cols[f]\n })\n return uniqueIndex(indexName).on(colsConstraint[0], ...colsConstraint.slice(1))\n }\n }\n\n buildTable({\n adapter: this,\n disableNotNull: !!collection?.versions?.drafts,\n disableUnique: false,\n fields: collection.fields,\n locales,\n tableName,\n timestamps: collection.timestamps,\n versions: false,\n })\n\n if (collection.versions) {\n const versionsTableName = this.tableNameMap.get(\n `_${toSnakeCase(collection.slug)}${this.versionsSuffix}`,\n )\n const versionFields = buildVersionCollectionFields(config, collection)\n\n buildTable({\n adapter: this,\n disableNotNull: !!collection.versions?.drafts,\n disableUnique: true,\n fields: versionFields,\n locales,\n tableName: versionsTableName,\n timestamps: true,\n versions: true,\n })\n }\n })\n\n this.payload.config.globals.forEach((global) => {\n const tableName = createTableName({\n adapter: this as unknown as DrizzleAdapter,\n config: global,\n })\n\n buildTable({\n adapter: this,\n disableNotNull: !!global?.versions?.drafts,\n disableUnique: false,\n fields: global.fields,\n locales,\n tableName,\n timestamps: false,\n versions: false,\n })\n\n if (global.versions) {\n const versionsTableName = createTableName({\n adapter: this as unknown as DrizzleAdapter,\n config: global,\n versions: true,\n versionsCustomName: true,\n })\n const config = this.payload.config\n const versionFields = buildVersionGlobalFields(config, global)\n\n buildTable({\n adapter: this,\n disableNotNull: !!global.versions?.drafts,\n disableUnique: true,\n fields: versionFields,\n locales,\n tableName: versionsTableName,\n timestamps: true,\n versions: true,\n })\n }\n })\n\n await executeSchemaHooks({ type: 'afterSchemaInit', adapter: this })\n}\n"],"names":["createTableName","executeSchemaHooks","uniqueIndex","buildVersionCollectionFields","buildVersionGlobalFields","toSnakeCase","buildTable","init","locales","type","adapter","payload","config","localization","map","code","collections","forEach","collection","versions","versionsCustomName","tableName","tableNameMap","get","slug","baseExtraConfig","upload","filenameCompoundIndex","indexName","filename_compound_index","cols","colsConstraint","f","on","slice","disableNotNull","drafts","disableUnique","fields","timestamps","versionsTableName","versionsSuffix","versionFields","globals","global"],"mappings":"AAGA,SAASA,eAAe,EAAEC,kBAAkB,QAAQ,sBAAqB;AACzE,SAASC,WAAW,QAAQ,0BAAyB;AACrD,SAASC,4BAA4B,EAAEC,wBAAwB,QAAQ,UAAS;AAChF,OAAOC,iBAAiB,gBAAe;AAKvC,SAASC,UAAU,QAAQ,oBAAmB;AAE9C,OAAO,MAAMC,OAAa,eAAeA;IACvC,IAAIC;IACJ,MAAMP,mBAAmB;QAAEQ,MAAM;QAAoBC,SAAS,IAAI;IAAC;IAEnE,IAAI,IAAI,CAACC,OAAO,CAACC,MAAM,CAACC,YAAY,EAAE;QACpCL,UAAU,IAAI,CAACG,OAAO,CAACC,MAAM,CAACC,YAAY,CAACL,OAAO,CAACM,GAAG,CAAC,CAAC,EAAEC,IAAI,EAAE,GAAKA;IAIvE;IAEA,IAAI,CAACJ,OAAO,CAACC,MAAM,CAACI,WAAW,CAACC,OAAO,CAAC,CAACC;QACvClB,gBAAgB;YACdU,SAAS,IAAI;YACbE,QAAQM;QACV;QAEA,IAAIA,WAAWC,QAAQ,EAAE;YACvBnB,gBAAgB;gBACdU,SAAS,IAAI;gBACbE,QAAQM;gBACRC,UAAU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) => ForeignKeyBuilder | IndexBuilder | UniqueConstraintBuilder>;
|
|
7
7
|
export type RelationMap = Map<string, {
|
|
8
8
|
localized: boolean;
|
|
9
|
+
relationName?: string;
|
|
9
10
|
target: string;
|
|
10
11
|
type: 'many' | 'one';
|
|
11
12
|
}>;
|
|
12
13
|
type Args = {
|
|
13
14
|
adapter: SQLiteAdapter;
|
|
14
15
|
baseColumns?: Record<string, SQLiteColumnBuilder>;
|
|
16
|
+
/**
|
|
17
|
+
* After table is created, run these functions to add extra config to the table
|
|
18
|
+
* ie. indexes, multiple columns, etc
|
|
19
|
+
*/
|
|
15
20
|
baseExtraConfig?: BaseExtraConfig;
|
|
16
21
|
buildNumbers?: boolean;
|
|
17
22
|
buildRelationships?: boolean;
|
|
@@ -19,19 +24,27 @@ type Args = {
|
|
|
19
24
|
disableUnique: boolean;
|
|
20
25
|
fields: Field[];
|
|
21
26
|
locales?: [string, ...string[]];
|
|
22
|
-
rootRelationsToBuild?: RelationMap;
|
|
23
27
|
rootRelationships?: Set<string>;
|
|
28
|
+
rootRelationsToBuild?: RelationMap;
|
|
24
29
|
rootTableIDColType?: IDType;
|
|
25
30
|
rootTableName?: string;
|
|
26
31
|
tableName: string;
|
|
27
32
|
timestamps?: boolean;
|
|
28
33
|
versions: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Tracks whether or not this table is built
|
|
36
|
+
* from the result of a localized array or block field at some point
|
|
37
|
+
*/
|
|
38
|
+
withinLocalizedArrayOrBlock?: boolean;
|
|
29
39
|
};
|
|
30
40
|
type Result = {
|
|
41
|
+
hasLocalizedManyNumberField: boolean;
|
|
42
|
+
hasLocalizedManyTextField: boolean;
|
|
43
|
+
hasLocalizedRelationshipField: boolean;
|
|
31
44
|
hasManyNumberField: 'index' | boolean;
|
|
32
45
|
hasManyTextField: 'index' | boolean;
|
|
33
46
|
relationsToBuild: RelationMap;
|
|
34
47
|
};
|
|
35
|
-
export declare const buildTable: ({ adapter, baseColumns, baseExtraConfig, disableNotNull, disableUnique, fields, locales,
|
|
48
|
+
export declare const buildTable: ({ adapter, baseColumns, baseExtraConfig, disableNotNull, disableUnique, fields, locales, rootRelationships, rootRelationsToBuild, rootTableIDColType, rootTableName: incomingRootTableName, tableName, timestamps, versions, withinLocalizedArrayOrBlock, }: Args) => Result;
|
|
36
49
|
export {};
|
|
37
50
|
//# sourceMappingURL=build.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/schema/build.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,mBAAmB,EAEnB,uBAAuB,EACxB,MAAM,yBAAyB,CAAA;AAChC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAepC,OAAO,KAAK,EAAgC,MAAM,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAMtF,MAAM,MAAM,eAAe,GAAG,MAAM,CAClC,MAAM,EACN,CAAC,IAAI,EAAE;IACL,CAAC,CAAC,EAAE,MAAM,GAAG,eAAe,CAAA;CAC7B,KAAK,iBAAiB,GAAG,YAAY,GAAG,uBAAuB,CACjE,CAAA;AAED,MAAM,MAAM,WAAW,GAAG,GAAG,
|
|
1
|
+
{"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/schema/build.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,mBAAmB,EAEnB,uBAAuB,EACxB,MAAM,yBAAyB,CAAA;AAChC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAepC,OAAO,KAAK,EAAgC,MAAM,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAMtF,MAAM,MAAM,eAAe,GAAG,MAAM,CAClC,MAAM,EACN,CAAC,IAAI,EAAE;IACL,CAAC,CAAC,EAAE,MAAM,GAAG,eAAe,CAAA;CAC7B,KAAK,iBAAiB,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;CAC9B,CAAA;AAED,eAAO,MAAM,UAAU,gQAgBpB,IAAI,KAAG,MA0ZT,CAAA"}
|
package/dist/schema/build.js
CHANGED
|
@@ -5,7 +5,7 @@ import toSnakeCase from 'to-snake-case';
|
|
|
5
5
|
import { getIDColumn } from './getIDColumn.js';
|
|
6
6
|
import { setColumnID } from './setColumnID.js';
|
|
7
7
|
import { traverseFields } from './traverseFields.js';
|
|
8
|
-
export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, disableNotNull, disableUnique = false, fields, locales,
|
|
8
|
+
export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, disableNotNull, disableUnique = false, fields, locales, rootRelationships, rootRelationsToBuild, rootTableIDColType, rootTableName: incomingRootTableName, tableName, timestamps, versions, withinLocalizedArrayOrBlock })=>{
|
|
9
9
|
const isRoot = !incomingRootTableName;
|
|
10
10
|
const rootTableName = incomingRootTableName || tableName;
|
|
11
11
|
const columns = baseColumns;
|
|
@@ -36,20 +36,22 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, di
|
|
|
36
36
|
localesIndexes,
|
|
37
37
|
newTableName: tableName,
|
|
38
38
|
parentTableName: tableName,
|
|
39
|
-
relationsToBuild,
|
|
40
39
|
relationships,
|
|
40
|
+
relationsToBuild,
|
|
41
41
|
rootRelationsToBuild: rootRelationsToBuild || relationsToBuild,
|
|
42
42
|
rootTableIDColType: rootTableIDColType || idColType,
|
|
43
43
|
rootTableName,
|
|
44
|
-
versions
|
|
44
|
+
versions,
|
|
45
|
+
withinLocalizedArrayOrBlock
|
|
45
46
|
});
|
|
46
47
|
// split the relationsToBuild by localized and non-localized
|
|
47
48
|
const localizedRelations = new Map();
|
|
48
49
|
const nonLocalizedRelations = new Map();
|
|
49
|
-
relationsToBuild.forEach(({ type, localized, target }, key)=>{
|
|
50
|
+
relationsToBuild.forEach(({ type, localized, relationName, target }, key)=>{
|
|
50
51
|
const map = localized ? localizedRelations : nonLocalizedRelations;
|
|
51
52
|
map.set(key, {
|
|
52
53
|
type,
|
|
54
|
+
relationName,
|
|
53
55
|
target
|
|
54
56
|
});
|
|
55
57
|
});
|
|
@@ -282,8 +284,12 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, di
|
|
|
282
284
|
});
|
|
283
285
|
let colType = 'integer';
|
|
284
286
|
const relatedCollectionCustomIDType = adapter.payload.collections[relationshipConfig.slug]?.customIDType;
|
|
285
|
-
if (relatedCollectionCustomIDType === 'number')
|
|
286
|
-
|
|
287
|
+
if (relatedCollectionCustomIDType === 'number') {
|
|
288
|
+
colType = 'numeric';
|
|
289
|
+
}
|
|
290
|
+
if (relatedCollectionCustomIDType === 'text') {
|
|
291
|
+
colType = 'text';
|
|
292
|
+
}
|
|
287
293
|
relationshipColumns[`${relationTo}ID`] = getIDColumn({
|
|
288
294
|
name: `${formattedRelationTo}_id`,
|
|
289
295
|
type: colType,
|
|
@@ -357,7 +363,7 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, di
|
|
|
357
363
|
}
|
|
358
364
|
adapter.relations[`relations_${tableName}`] = relations(table, ({ many, one })=>{
|
|
359
365
|
const result = {};
|
|
360
|
-
nonLocalizedRelations.forEach(({ type, target }, key)=>{
|
|
366
|
+
nonLocalizedRelations.forEach(({ type, relationName, target }, key)=>{
|
|
361
367
|
if (type === 'one') {
|
|
362
368
|
result[key] = one(adapter.tables[target], {
|
|
363
369
|
fields: [
|
|
@@ -371,7 +377,7 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, di
|
|
|
371
377
|
}
|
|
372
378
|
if (type === 'many') {
|
|
373
379
|
result[key] = many(adapter.tables[target], {
|
|
374
|
-
relationName: key
|
|
380
|
+
relationName: relationName || key
|
|
375
381
|
});
|
|
376
382
|
}
|
|
377
383
|
});
|
|
@@ -398,6 +404,9 @@ export const buildTable = ({ adapter, baseColumns = {}, baseExtraConfig = {}, di
|
|
|
398
404
|
return result;
|
|
399
405
|
});
|
|
400
406
|
return {
|
|
407
|
+
hasLocalizedManyNumberField,
|
|
408
|
+
hasLocalizedManyTextField,
|
|
409
|
+
hasLocalizedRelationshipField,
|
|
401
410
|
hasManyNumberField,
|
|
402
411
|
hasManyTextField,
|
|
403
412
|
relationsToBuild
|