nitro-drizzle 0.3.0-beta.2 → 0.3.0-beta.4
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 +24 -3
- package/dist/config/defineConfig.d.mts +4 -4
- package/dist/config/defineConfig.mjs +4 -4
- package/dist/config/defineConfig.mjs.map +1 -1
- package/dist/context/internal/async.mjs +8 -0
- package/dist/context/internal/async.mjs.map +1 -1
- package/dist/context/internal/codegen.mjs +28 -0
- package/dist/context/internal/codegen.mjs.map +1 -0
- package/dist/context/internal/config.mjs +9 -4
- package/dist/context/internal/config.mjs.map +1 -1
- package/dist/context/internal/format.mjs +6 -0
- package/dist/context/internal/format.mjs.map +1 -1
- package/dist/context/internal/fs.mjs +7 -0
- package/dist/context/internal/fs.mjs.map +1 -1
- package/dist/context/internal/logger.mjs +6 -0
- package/dist/context/internal/logger.mjs.map +1 -1
- package/dist/context/internal/templates.mjs +84 -31
- package/dist/context/internal/templates.mjs.map +1 -1
- package/dist/context/internal/virtual.mjs +51 -26
- package/dist/context/internal/virtual.mjs.map +1 -1
- package/dist/context.d.mts +22 -15
- package/dist/context.mjs +58 -15
- package/dist/context.mjs.map +1 -1
- package/dist/dialects/sqlite.d.mts +2 -2
- package/dist/dialects/sqlite.mjs +3 -3
- package/dist/dialects/sqlite.mjs.map +1 -1
- package/dist/drivers/{internal/d1-dialect.mjs → d1/dialect.mjs} +4 -3
- package/dist/drivers/d1/dialect.mjs.map +1 -0
- package/dist/drivers/d1-http.d.mts +1 -1
- package/dist/drivers/d1-http.mjs +3 -3
- package/dist/drivers/d1-http.mjs.map +1 -1
- package/dist/drivers/d1.d.mts +2 -1
- package/dist/drivers/d1.mjs +3 -3
- package/dist/drivers/d1.mjs.map +1 -1
- package/dist/drivers/db0.d.mts +2 -0
- package/dist/drivers/db0.mjs +3 -2
- package/dist/drivers/db0.mjs.map +1 -1
- package/dist/drivers/index.d.mts +14 -7
- package/dist/drivers/index.mjs +3 -3
- package/dist/drivers/index.mjs.map +1 -1
- package/dist/drivers/mysql.mjs +2 -2
- package/dist/drivers/mysql.mjs.map +1 -1
- package/dist/drivers/pglite.d.mts +1 -0
- package/dist/drivers/pglite.mjs +3 -2
- package/dist/drivers/pglite.mjs.map +1 -1
- package/dist/drivers/postgresql.d.mts +2 -1
- package/dist/drivers/postgresql.mjs +2 -2
- package/dist/drivers/postgresql.mjs.map +1 -1
- package/dist/drivers/sqlite.mjs +2 -2
- package/dist/drivers/sqlite.mjs.map +1 -1
- package/dist/middleware/context.d.mts +8 -0
- package/dist/middleware/context.mjs +4 -0
- package/dist/middleware/context.mjs.map +1 -1
- package/dist/migrations/migrate.mjs +3 -2
- package/dist/migrations/migrate.mjs.map +1 -1
- package/dist/migrations/task.d.mts +4 -0
- package/dist/migrations/task.mjs +4 -0
- package/dist/migrations/task.mjs.map +1 -1
- package/dist/migrations/useMigrations.d.mts +2 -2
- package/dist/migrations/useMigrations.mjs +3 -1
- package/dist/migrations/useMigrations.mjs.map +1 -1
- package/dist/module/internal/fs.mjs +5 -0
- package/dist/module/internal/fs.mjs.map +1 -1
- package/dist/module/internal/path.mjs +6 -0
- package/dist/module/internal/path.mjs.map +1 -1
- package/dist/module/internal/reload.mjs +6 -0
- package/dist/module/internal/reload.mjs.map +1 -1
- package/dist/module/internal/resolver.mjs +6 -0
- package/dist/module/internal/resolver.mjs.map +1 -1
- package/dist/module/internal/rollup.mjs +5 -0
- package/dist/module/internal/rollup.mjs.map +1 -1
- package/dist/module/internal/types.mjs +16 -0
- package/dist/module/internal/types.mjs.map +1 -1
- package/dist/module/utils/assets.d.mts +5 -0
- package/dist/module/utils/assets.mjs +7 -0
- package/dist/module/utils/assets.mjs.map +1 -1
- package/dist/module/utils/externals.d.mts +5 -0
- package/dist/module/utils/externals.mjs +10 -0
- package/dist/module/utils/externals.mjs.map +1 -1
- package/dist/module/utils/nitro.d.mts +5 -0
- package/dist/module/utils/nitro.mjs +5 -0
- package/dist/module/utils/nitro.mjs.map +1 -1
- package/dist/module.d.mts +24 -2
- package/dist/module.mjs +21 -2
- package/dist/module.mjs.map +1 -1
- package/dist/plugins/legacy/init.mjs +27 -10
- package/dist/plugins/legacy/init.mjs.map +1 -1
- package/dist/runtime/internal/config.mjs +18 -6
- package/dist/runtime/internal/config.mjs.map +1 -1
- package/dist/runtime/internal/createDatasource.mjs +24 -5
- package/dist/runtime/internal/createDatasource.mjs.map +1 -1
- package/dist/runtime/useConfig.d.mts +15 -0
- package/dist/runtime/useConfig.mjs +22 -0
- package/dist/runtime/useConfig.mjs.map +1 -0
- package/dist/runtime/useDatasource.d.mts +5 -2
- package/dist/runtime/useDatasource.mjs +2 -1
- package/dist/runtime/useDatasource.mjs.map +1 -1
- package/dist/runtime/useDialect.d.mts +26 -0
- package/dist/runtime/useDialect.mjs +22 -0
- package/dist/runtime/useDialect.mjs.map +1 -0
- package/dist/runtime.d.mts +45 -28
- package/dist/runtime.mjs +3 -1
- package/dist/shared/variants.d.mts +35 -0
- package/dist/shared/variants.mjs +17 -0
- package/dist/shared/variants.mjs.map +1 -0
- package/dist/shared.d.mts +11 -3
- package/dist/shared.mjs +2 -1
- package/package.json +7 -5
- package/dist/drivers/internal/d1-dialect.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"virtual.mjs","names":[],"sources":["../../../src/context/internal/virtual.ts"],"sourcesContent":["import {\n genArrayFromRaw,\n genExport,\n genImport,\n genObjectFromRaw,\n genObjectFromRawEntries,\n genSafeVariableName,\n genString,\n} from \"knitwork\";\nimport type { DatasourceInfo, MigrationOptions } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\nimport { script } from \"./format\";\n\nfunction genDatasourceModuleVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`dbModule${dbModuleIndex}`);\n}\n\nfunction genMergedSchemaVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`mergedSchema${dbModuleIndex}`);\n}\n\nconst genSchemaModuleVariableName = (dbModuleIndex: number, schemaIndex: number) =>\n genSafeVariableName(`schemaModule${dbModuleIndex}_${schemaIndex}`);\n\nfunction mergeSchemaModules(schemaIds: string[], dbModuleIndex: number) {\n return /* js */ `\n Object.assign(\n ${[\n /* js */ `{}`,\n ...schemaIds.map((_, schemaModuleIdIndex) =>\n genSchemaModuleVariableName(dbModuleIndex, schemaModuleIdIndex),\n ),\n ].join(\",\")}\n )\n `;\n}\n\nexport function runtimeVirtualModule(\n datasources: readonly DatasourceInfo[],\n { legacyNitro, runtimeConfigProp }: { legacyNitro: boolean; runtimeConfigProp: string },\n) {\n const datasourceRegistryParts = datasources\n .filter((datasource) => datasource.enabled)\n .map(({ name, imports: { schema, connector } }, datasourceIndex) => {\n const datasourceModuleVariableName = genDatasourceModuleVariableName(datasourceIndex);\n\n const imports = [\n genImport(connector, datasourceModuleVariableName),\n ...schema.map((schemaModuleId, schemaIndex) => {\n return genImport(schemaModuleId, {\n name: \"*\",\n as: genSchemaModuleVariableName(datasourceIndex, schemaIndex),\n });\n }),\n ];\n\n const mergedSchemaVariableName = genMergedSchemaVariableName(datasourceIndex);\n const mergedSchemaObject = mergeSchemaModules(schema, datasourceIndex);\n\n const schemaDefinitions = [\n /* js */ `const ${mergedSchemaVariableName} = ${mergedSchemaObject};`,\n ];\n\n const entries: [string, string][] = [\n [\n name,\n genObjectFromRaw({\n create: /* js */ `(config) => ${datasourceModuleVariableName}(config, ${mergedSchemaVariableName})`,\n schema: mergedSchemaVariableName,\n }),\n ],\n ];\n\n return {\n imports,\n schemaDefinitions,\n entries,\n };\n })\n .reduce(\n (acc, { imports, schemaDefinitions, entries }) => {\n return {\n imports: [...acc.imports, ...imports],\n schemaDefinitions: [...acc.schemaDefinitions, ...schemaDefinitions],\n entries: [...acc.entries, ...entries],\n };\n },\n {\n imports: [] as string[],\n schemaDefinitions: [] as string[],\n entries: [] as [string, string][],\n },\n );\n\n const datasourceRegistryVarName = genSafeVariableName(\"datasourceRegistry\");\n\n const nitroRuntimeParts = {\n imports: [\n legacyNitro\n ? genImport(\"nitropack/runtime\", [\"useNitroApp\"])\n : genImport(\"nitro/app\", [\"useNitroHooks\"]),\n genImport(legacyNitro ? \"nitropack/runtime\" : \"nitro/runtime-config\", [\n {\n name: \"useRuntimeConfig\",\n as: \"useNitroRuntimeConfig\",\n },\n ]),\n ],\n declarations: [\n script /* js */ `\n export function useRuntimeConfig() {\n const runtimeConfig = useNitroRuntimeConfig();\n return runtimeConfig[${genString(runtimeConfigProp)}]\n }\n\n ${\n legacyNitro\n ? script /* js */ `\n function useNitroHooks() {\n return useNitroApp().hooks;\n }\n `\n : \"\"\n }\n\n export function onServerClose(cb) {\n return useNitroHooks().hook(\"close\", cb);\n }\n\n export function callConfigHook(name, config) {\n return useNitroHooks().callHook(\"drizzle:config\", name, config);\n }\n `,\n ],\n exports: [genExport(legacyNitro ? \"nitropack/runtime\" : \"nitro/storage\", [\"useStorage\"])],\n };\n\n return script /* js */ `\n ${datasourceRegistryParts.imports.join(\"\\n\")}\n ${nitroRuntimeParts.imports.join(\"\\n\")}\n \n ${datasourceRegistryParts.schemaDefinitions.join(\"\\n\")}\n \n const ${datasourceRegistryVarName} = ${genObjectFromRawEntries(datasourceRegistryParts.entries)};\n\n export function useDatasourceRegistry() {\n return ${datasourceRegistryVarName};\n }\n\n ${nitroRuntimeParts.declarations.join(\"\\n\")}\n\n ${nitroRuntimeParts.exports.join(\"\\n\")}\n `;\n}\n\n// Replaced with aliases\nexport function dialectVirtualModules(\n datasources: readonly DatasourceInfo[],\n): VirtualModules<`#nitro-drizzle/${string}`> {\n return Object.fromEntries(\n datasources\n .filter((d) => d.enabled)\n .map(({ name, dialect }) => {\n return [\n `#nitro-drizzle/dialects/${name}`,\n genExport(`nitro-drizzle/dialects/${dialect}`, \"*\"),\n ] as const;\n }),\n );\n}\n\nexport function migrationsVirtualModule(\n datasources: readonly DatasourceInfo[],\n options: MigrationOptions | undefined,\n): VirtualModules<`#nitro-drizzle/${string}`> {\n if (!options) {\n return {};\n }\n\n const parts: string[] = [];\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n parts.push(/*js*/ `\n export const migrationConfig = ${genObjectFromRawEntries(\n enabledDatasources.map(({ name, migrations }) => {\n return [name, JSON.stringify(migrations.config)];\n }),\n )};\n `);\n\n let migrateOnInit = enabledDatasources.map((d) => d.name);\n if (options && Array.isArray(options.migrateOnInit)) {\n migrateOnInit = migrateOnInit.filter((name) =>\n (options.migrateOnInit as readonly string[]).includes(name),\n );\n }\n\n parts.push(script /*js*/ `\n export const MIGRATIONS_STORAGE_BASE = ${genString(options.storageBase)};\n export const MIGRATE_ON_INIT = ${genArrayFromRaw(migrateOnInit.map((name) => genString(name)))};\n `);\n\n return {\n \"#nitro-drizzle/migrations\": parts.join(\"\\n\"),\n };\n}\n"],"mappings":";;;AAaA,SAAS,gCAAgC,eAAuB;CAC9D,OAAO,oBAAoB,WAAW,eAAe;AACvD;AAEA,SAAS,4BAA4B,eAAuB;CAC1D,OAAO,oBAAoB,eAAe,eAAe;AAC3D;AAEA,MAAM,+BAA+B,eAAuB,gBAC1D,oBAAoB,eAAe,cAAc,GAAG,aAAa;AAEnE,SAAS,mBAAmB,WAAqB,eAAuB;CACtE,OAAgB;;QAEV,CACS,MACT,GAAG,UAAU,KAAK,GAAG,wBACnB,4BAA4B,eAAe,mBAAmB,CAChE,CACF,CAAC,CAAC,KAAK,GAAG,EAAE;;;AAGlB;AAEA,SAAgB,qBACd,aACA,EAAE,aAAa,qBACf;CACA,MAAM,0BAA0B,YAC7B,QAAQ,eAAe,WAAW,OAAO,CAAC,CAC1C,KAAK,EAAE,MAAM,SAAS,EAAE,QAAQ,eAAe,oBAAoB;EAClE,MAAM,+BAA+B,gCAAgC,eAAe;EAEpF,MAAM,UAAU,CACd,UAAU,WAAW,4BAA4B,GACjD,GAAG,OAAO,KAAK,gBAAgB,gBAAgB;GAC7C,OAAO,UAAU,gBAAgB;IAC/B,MAAM;IACN,IAAI,4BAA4B,iBAAiB,WAAW;GA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,IAAI,EAAE;;MAE1C,kBAAkB,QAAQ,KAAK,IAAI,EAAE;;AAE3C;AAGA,SAAgB,sBACd,aAC4C;CAC5C,OAAO,OAAO,YACZ,YACG,QAAQ,MAAM,EAAE,OAAO,CAAC,CACxB,KAAK,EAAE,MAAM,cAAc;EAC1B,OAAO,CACL,2BAA2B,QAC3B,UAAU,0BAA0B,WAAW,GAAG,CACpD;CACF,CAAC,CACL;AACF;AAEA,SAAgB,wBACd,aACA,SAC4C;CAC5C,IAAI,CAAC,SACH,OAAO,CAAC;CAGV,MAAM,QAAkB,CAAC;CAEzB,MAAM,qBAAqB,YAAY,QAAQ,MAAM,EAAE,OAAO;CAE9D,MAAM,KAAY;qCACiB,wBAC/B,mBAAmB,KAAK,EAAE,MAAM,iBAAiB;EAC/C,OAAO,CAAC,MAAM,KAAK,UAAU,WAAW,MAAM,CAAC;CACjD,CAAC,CACH,EAAE;GACH;CAED,IAAI,gBAAgB,mBAAmB,KAAK,MAAM,EAAE,IAAI;CACxD,IAAI,WAAW,MAAM,QAAQ,QAAQ,aAAa,GAChD,gBAAgB,cAAc,QAAQ,SACnC,QAAQ,cAAoC,SAAS,IAAI,CAC5D;CAGF,MAAM,KAAK,MAAc;6CACkB,UAAU,QAAQ,WAAW,EAAE;qCACvC,gBAAgB,cAAc,KAAK,SAAS,UAAU,IAAI,CAAC,CAAC,EAAE;GAChG;CAED,OAAO,EACL,6BAA6B,MAAM,KAAK,IAAI,EAC9C;AACF"}
|
|
1
|
+
{"version":3,"file":"virtual.mjs","names":[],"sources":["../../../src/context/internal/virtual.ts"],"sourcesContent":["import {\n genArrayFromRaw,\n genExport,\n genImport,\n genObjectFromRaw,\n genObjectFromRawEntries,\n genSafeVariableName,\n genString,\n} from \"knitwork\";\nimport type { DatasourceInfo, MigrationOptions } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\nimport { script } from \"./format\";\n\nfunction genConnectorModuleVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`dbModule${dbModuleIndex}`);\n}\n\nfunction genMergeSchemaVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`mergedSchema${dbModuleIndex}`);\n}\n\nconst genSchemaModuleVariableName = (dbModuleIndex: number, schemaIndex: number) =>\n genSafeVariableName(`schemaModule${dbModuleIndex}_${schemaIndex}`);\n\nfunction mergeSchemaModules(schemaIds: readonly string[], dbModuleIndex: number) {\n return /* js */ `\n Object.assign(\n ${[\n /* js */ `{}`,\n ...schemaIds.map((_, schemaModuleIdIndex) =>\n genSchemaModuleVariableName(dbModuleIndex, schemaModuleIdIndex),\n ),\n ].join(\",\")}\n )\n `;\n}\n\nexport type RuntimeVirtualModuleOptions = {\n /** Whether to use the legacy Nitro API (nitropack/runtime) instead of the modern one (nitro/runtime-config). */\n legacyNitro: boolean;\n /** The property name in the runtime config where drizzle configuration is stored. */\n runtimeConfigProp: string;\n /** Hooks that are allowed to trigger the \"drizzle:init\" hook. */\n initHooks?: readonly string[];\n};\n\n/**\n * Generates the runtime virtual module code for datasource management.\n * @param datasources - The resolved datasource information\n * @param options - Runtime virtual module options\n * @returns The virtual module code string\n */\nexport function runtimeVirtualModule(\n datasources: readonly DatasourceInfo[],\n { legacyNitro, runtimeConfigProp, initHooks }: RuntimeVirtualModuleOptions,\n) {\n const datasourceRegistryParts = datasources\n .filter((datasource) => datasource.enabled)\n .flatMap(({ name, drivers }) => {\n return drivers.map((driver) => {\n return {\n name,\n driver,\n };\n });\n })\n .map(({ name, driver }, datasourceIndex) => {\n const connectorVarName = genConnectorModuleVariableName(datasourceIndex);\n\n const imports = [\n genImport(driver.imports.connector, connectorVarName),\n ...driver.imports.schema.map((schemaModuleId, schemaIndex) => {\n return genImport(schemaModuleId, {\n name: \"*\",\n as: genSchemaModuleVariableName(datasourceIndex, schemaIndex),\n });\n }),\n ];\n\n const mergedSchemaVariableName = genMergeSchemaVariableName(datasourceIndex);\n const mergedSchemaObject = mergeSchemaModules(driver.imports.schema, datasourceIndex);\n\n const schemaDefinitions = [\n /* js */ `const ${mergedSchemaVariableName} = ${mergedSchemaObject};`,\n ];\n\n const factoryObject = {\n name,\n driver: driver.name,\n factory: {\n create: /* js */ `(config) => ${connectorVarName}(config, ${mergedSchemaVariableName})`,\n schema: mergedSchemaVariableName,\n dialect: genString(driver.dialect),\n },\n };\n\n return {\n imports,\n schemaDefinitions,\n factoryObject,\n };\n })\n .reduce(\n (acc, { imports, schemaDefinitions, factoryObject }) => {\n const accFactoryObject = acc.factoryObject;\n accFactoryObject[factoryObject.name] ||= {};\n accFactoryObject[factoryObject.name][factoryObject.driver] = factoryObject.factory;\n\n return {\n imports: [...acc.imports, ...imports],\n schemaDefinitions: [...acc.schemaDefinitions, ...schemaDefinitions],\n factoryObject: accFactoryObject,\n };\n },\n {\n imports: [] as string[],\n schemaDefinitions: [] as string[],\n factoryObject: {} as { [name: string]: { [driver: string]: object } },\n },\n );\n\n const datasourceRegistryVarName = genSafeVariableName(\"datasourceRegistry\");\n\n const nitroRuntimeParts = {\n imports: [\n legacyNitro\n ? genImport(\"nitropack/runtime\", [\"useNitroApp\"])\n : genImport(\"nitro/app\", [\"useNitroHooks\"]),\n genImport(legacyNitro ? \"nitropack/runtime\" : \"nitro/runtime-config\", [\n {\n name: \"useRuntimeConfig\",\n as: \"useNitroRuntimeConfig\",\n },\n ]),\n ],\n declarations: [\n script /* js */ `\n export function useRuntimeConfig() {\n const runtimeConfig = useNitroRuntimeConfig();\n return runtimeConfig[${genString(runtimeConfigProp)}]\n }\n\n ${\n legacyNitro\n ? script /* js */ `\n function useNitroHooks() {\n return useNitroApp().hooks;\n }\n `\n : \"\"\n }\n\n export function onServerClose(cb) {\n return useNitroHooks().hook(\"close\", cb);\n }\n\n export function callConfigHook(...args) {\n return useNitroHooks().callHook(\"drizzle:config\", ...args);\n }\n `,\n ],\n exports: [genExport(legacyNitro ? \"nitropack/runtime\" : \"nitro/storage\", [\"useStorage\"])],\n };\n\n return script /* js */ `\n ${datasourceRegistryParts.imports.join(\"\\n\")}\n ${nitroRuntimeParts.imports.join(\"\\n\")}\n \n ${datasourceRegistryParts.schemaDefinitions.join(\"\\n\")}\n \n const ${datasourceRegistryVarName} = ${genObjectFromRaw(datasourceRegistryParts.factoryObject)};\n\n export function useDatasourceRegistry() {\n return ${datasourceRegistryVarName};\n }\n\n ${nitroRuntimeParts.declarations.join(\"\\n\")}\n\n ${nitroRuntimeParts.exports.join(\"\\n\")}\n\n export const initHooks = ${JSON.stringify(initHooks || [])};\n `;\n}\n\n// Replaced with aliases\nexport function dialectVirtualModules(\n datasources: readonly DatasourceInfo[],\n): VirtualModules<`#nitro-drizzle/${string}`> {\n return Object.fromEntries(\n datasources\n .filter((d) => d.enabled)\n .map(({ name }) => {\n return [\n `#nitro-drizzle/dialects/${name}`,\n `export {};`,\n // genExport(`nitro-drizzle/dialects/${dialect}`, \"*\"),\n ] as const;\n }),\n );\n}\n\nexport function migrationsVirtualModule(\n datasources: readonly DatasourceInfo[],\n options: MigrationOptions | undefined,\n): VirtualModules<`#nitro-drizzle/${string}`> {\n if (!options) {\n return {};\n }\n\n const parts: string[] = [];\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n parts.push(/*js*/ `\n export const migrationConfig = ${genObjectFromRawEntries(\n enabledDatasources.map(({ name, drivers }) => {\n return [\n name,\n genObjectFromRawEntries(\n drivers.map((driver) => {\n return [driver.name, JSON.stringify(driver.migrations.config)];\n }),\n ),\n ];\n }),\n )};\n `);\n\n let migrateOnInit = enabledDatasources.map((d) => d.name);\n if (options && Array.isArray(options.migrateOnInit)) {\n migrateOnInit = migrateOnInit.filter((name) =>\n (options.migrateOnInit as readonly string[]).includes(name),\n );\n }\n\n parts.push(script /*js*/ `\n export const MIGRATIONS_STORAGE_BASE = ${genString(options.storageBase)};\n export const MIGRATE_ON_INIT = ${genArrayFromRaw(migrateOnInit.map((name) => genString(name)))};\n `);\n\n return {\n \"#nitro-drizzle/migrations\": parts.join(\"\\n\"),\n };\n}\n"],"mappings":";;;AAaA,SAAS,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QAC3B,YAEF;CACF,CAAC,CACL;AACF;AAEA,SAAgB,wBACd,aACA,SAC4C;CAC5C,IAAI,CAAC,SACH,OAAO,CAAC;CAGV,MAAM,QAAkB,CAAC;CAEzB,MAAM,qBAAqB,YAAY,QAAQ,MAAM,EAAE,OAAO;CAE9D,MAAM,KAAY;qCACiB,wBAC/B,mBAAmB,KAAK,EAAE,MAAM,cAAc;EAC5C,OAAO,CACL,MACA,wBACE,QAAQ,KAAK,WAAW;GACtB,OAAO,CAAC,OAAO,MAAM,KAAK,UAAU,OAAO,WAAW,MAAM,CAAC;EAC/D,CAAC,CACH,CACF;CACF,CAAC,CACH,EAAE;GACH;CAED,IAAI,gBAAgB,mBAAmB,KAAK,MAAM,EAAE,IAAI;CACxD,IAAI,WAAW,MAAM,QAAQ,QAAQ,aAAa,GAChD,gBAAgB,cAAc,QAAQ,SACnC,QAAQ,cAAoC,SAAS,IAAI,CAC5D;CAGF,MAAM,KAAK,MAAc;6CACkB,UAAU,QAAQ,WAAW,EAAE;qCACvC,gBAAgB,cAAc,KAAK,SAAS,UAAU,IAAI,CAAC,CAAC,EAAE;GAChG;CAED,OAAO,EACL,6BAA6B,MAAM,KAAK,IAAI,EAC9C;AACF"}
|
package/dist/context.d.mts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { Config } from "drizzle-kit";
|
|
2
1
|
import { ConsolaInstance } from "consola";
|
|
3
|
-
import { MaybePromise, VirtualModules } from "nitro-drizzle/shared";
|
|
2
|
+
import { MaybePromise, NitroHookName, VirtualModules } from "nitro-drizzle/shared";
|
|
3
|
+
import { Config } from "drizzle-kit";
|
|
4
4
|
import { ServerAssetDir } from "nitropack/types";
|
|
5
|
+
import { ServerAssetDir as ServerAssetDir$1 } from "nitro/types";
|
|
5
6
|
//#region src/context/index.d.ts
|
|
6
7
|
/**
|
|
7
8
|
* Context interface for managing Drizzle datasource configurations.
|
|
@@ -60,21 +61,28 @@ interface ContextOptions {
|
|
|
60
61
|
* Connector options
|
|
61
62
|
*/
|
|
62
63
|
datasources: Record<string, {
|
|
63
|
-
|
|
64
|
+
drivers: readonly string[] | {
|
|
65
|
+
[name: string]: boolean;
|
|
66
|
+
};
|
|
64
67
|
}>;
|
|
65
68
|
migrations: MigrationOptions | undefined;
|
|
69
|
+
/**
|
|
70
|
+
* Hooks that allowed to call "drizzle:init" hook.
|
|
71
|
+
*/
|
|
72
|
+
initHooks?: readonly NitroHookName[];
|
|
66
73
|
tasks?: ContextHook<[tasks: Record<string, {
|
|
67
74
|
handler: string;
|
|
68
75
|
description: string;
|
|
69
76
|
}>]>;
|
|
70
77
|
plugins: ContextHook<[plugins: readonly string[]]>;
|
|
71
78
|
declarations: ContextHook<[declarations: {
|
|
79
|
+
shared: VirtualModules<`${string}.d.ts`>;
|
|
72
80
|
module: VirtualModules<`${string}.d.ts`>;
|
|
73
81
|
runtime: VirtualModules<`${string}.d.ts`>;
|
|
74
82
|
virtual: Record<string, VirtualModules<`${string}.d.ts`>>;
|
|
75
83
|
}]>;
|
|
76
84
|
virtualModules: ContextHook<[modules: VirtualModules]>;
|
|
77
|
-
assets: ContextHook<[assets: readonly ServerAssetDir[]]>;
|
|
85
|
+
assets: ContextHook<[assets: readonly (ServerAssetDir$1 | ServerAssetDir)[]]>;
|
|
78
86
|
externals?: ContextHook<[modules: readonly string[]]>;
|
|
79
87
|
}
|
|
80
88
|
/**
|
|
@@ -87,29 +95,28 @@ declare function createContext(options: ContextOptions): Context;
|
|
|
87
95
|
* Information about a resolved Drizzle datasource.
|
|
88
96
|
*/
|
|
89
97
|
interface DatasourceInfo {
|
|
90
|
-
/** Directory name of the datasource (derived from config file location). */
|
|
91
|
-
dirName: string;
|
|
92
98
|
/** Unique name identifier for the datasource. */
|
|
93
99
|
name: string;
|
|
94
100
|
/** Whether the datasource is enabled (filtered by connector configuration). */
|
|
95
101
|
enabled: boolean;
|
|
96
|
-
/**
|
|
102
|
+
/** Driver configurations for this datasource. */
|
|
103
|
+
drivers: readonly DriverOptions[];
|
|
104
|
+
}
|
|
105
|
+
/** Options for a specific driver within a datasource. */
|
|
106
|
+
type DriverOptions = {
|
|
107
|
+
name: string;
|
|
97
108
|
dialect: string;
|
|
98
|
-
/** Driver type if specified in config, otherwise undefined. */
|
|
99
|
-
driver: string | undefined;
|
|
100
|
-
/** Import paths for schema, connector, and helpers. */
|
|
101
109
|
imports: {
|
|
102
|
-
|
|
103
|
-
schema: string[];
|
|
110
|
+
schema: readonly string[];
|
|
104
111
|
connector: string;
|
|
105
112
|
helpers: string;
|
|
106
113
|
};
|
|
107
|
-
/** Migration configuration for this datasource. */
|
|
114
|
+
/** Migration configuration for this datasource driver. */
|
|
108
115
|
migrations: {
|
|
109
116
|
assets?: string;
|
|
110
117
|
config?: Config["migrations"];
|
|
111
118
|
};
|
|
112
|
-
}
|
|
119
|
+
};
|
|
113
120
|
//#endregion
|
|
114
|
-
export { ConfigPattern, Context, ContextHook, ContextOptions, DatasourceInfo, MigrationOptions, Resolver, createContext };
|
|
121
|
+
export { ConfigPattern, Context, ContextHook, ContextOptions, DatasourceInfo, DriverOptions, MigrationOptions, Resolver, createContext };
|
|
115
122
|
//# sourceMappingURL=context.d.mts.map
|
package/dist/context.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { mapAsync } from "./context/internal/async.mjs";
|
|
2
2
|
import { accent } from "./context/internal/logger.mjs";
|
|
3
3
|
import { resolveFiles } from "./context/internal/fs.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import { genReference } from "./context/internal/codegen.mjs";
|
|
5
|
+
import { dialectDeclarations, moduleTypeDeclarations, runtimeDeclarations, sharedTypeDeclarations } from "./context/internal/templates.mjs";
|
|
5
6
|
import { transformDrizzleConfig } from "./context/internal/config.mjs";
|
|
6
7
|
import { dialectVirtualModules, migrationsVirtualModule, runtimeVirtualModule } from "./context/internal/virtual.mjs";
|
|
7
8
|
import { join } from "pathe";
|
|
@@ -18,7 +19,8 @@ var DefaultContext = class {
|
|
|
18
19
|
async init() {
|
|
19
20
|
const datasources = await this.datasources();
|
|
20
21
|
await this.#options.plugins(this.enabledPlugins());
|
|
21
|
-
const [virtualModules, virtualTypes, moduleTypes, runtimeTypes] = await Promise.all([
|
|
22
|
+
const [sharedTypes, virtualModules, virtualTypes, moduleTypes, runtimeTypes] = await Promise.all([
|
|
23
|
+
sharedTypeDeclarations(datasources),
|
|
22
24
|
this.virtualModules(datasources),
|
|
23
25
|
this.virtualTypeDeclarations(datasources),
|
|
24
26
|
this.moduleTypeDeclarations(datasources),
|
|
@@ -26,9 +28,10 @@ var DefaultContext = class {
|
|
|
26
28
|
]);
|
|
27
29
|
await this.#options.virtualModules(virtualModules);
|
|
28
30
|
await this.#options.declarations({
|
|
29
|
-
|
|
31
|
+
shared: sharedTypes,
|
|
30
32
|
module: moduleTypes,
|
|
31
|
-
runtime: runtimeTypes
|
|
33
|
+
runtime: runtimeTypes,
|
|
34
|
+
virtual: virtualTypes
|
|
32
35
|
});
|
|
33
36
|
if (this.#options.migrations) {
|
|
34
37
|
const assets = await this.migrationAssets(datasources);
|
|
@@ -53,21 +56,41 @@ var DefaultContext = class {
|
|
|
53
56
|
const { logger, baseDir, configPattern, resolver, datasources: datasourceOptions } = this.#options;
|
|
54
57
|
if (!this.#datasources) {
|
|
55
58
|
logger?.info("Searching drizzle datasources in", colorize("blue", baseDir));
|
|
56
|
-
|
|
57
|
-
const { config } = await loadConfig({ configFile: path });
|
|
59
|
+
const drizzleConfigs = [...await mapAsync(await resolveFiles(baseDir, [configPattern].flat().map((pattern) => "*/" + pattern)), async (path) => {
|
|
58
60
|
const [_, dirName] = path.match(/(.+\/(.+))\/.+$/).slice(1, 3);
|
|
61
|
+
const { config } = await loadConfig({ configFile: path });
|
|
59
62
|
return await transformDrizzleConfig(config, {
|
|
60
63
|
cwd: this.#options.cwd,
|
|
61
64
|
path,
|
|
62
65
|
dirName,
|
|
63
66
|
resolver
|
|
64
67
|
});
|
|
68
|
+
})].sort((a, b) => {
|
|
69
|
+
if (a.driver && b.driver) return 0;
|
|
70
|
+
return 1;
|
|
71
|
+
});
|
|
72
|
+
const datasources = Object.entries(datasourceOptions).map(([name, options]) => {
|
|
73
|
+
return {
|
|
74
|
+
name,
|
|
75
|
+
enabled: true,
|
|
76
|
+
drivers: (Array.isArray(options.drivers) ? options.drivers : Object.entries(options.drivers).filter(([_name, enabled]) => enabled).map(([name]) => name)).map((driverName) => {
|
|
77
|
+
const dialect = driverToDialect(driverName);
|
|
78
|
+
const drizzleConfig = drizzleConfigs.find((config) => {
|
|
79
|
+
return config.name == name && config.dialect == dialect;
|
|
80
|
+
});
|
|
81
|
+
return {
|
|
82
|
+
name: driverName,
|
|
83
|
+
dialect,
|
|
84
|
+
imports: {
|
|
85
|
+
connector: `nitro-drizzle/drivers/${driverName}`,
|
|
86
|
+
helpers: `nitro-drizzle/dialects/${dialect}`,
|
|
87
|
+
schema: drizzleConfig?.imports.schema || []
|
|
88
|
+
},
|
|
89
|
+
migrations: { ...drizzleConfig?.migrations }
|
|
90
|
+
};
|
|
91
|
+
})
|
|
92
|
+
};
|
|
65
93
|
});
|
|
66
|
-
datasources = Object.entries(datasourceOptions).reduce((_datasources, [name, options]) => {
|
|
67
|
-
const datasource = datasources.find((d) => d.name == name && options.connector == (d.driver ? d.driver : d.dialect));
|
|
68
|
-
if (!datasource) return _datasources;
|
|
69
|
-
return [..._datasources, datasource];
|
|
70
|
-
}, []);
|
|
71
94
|
logger?.info("Found drizzle datasources:", datasources.toSorted((datasource) => {
|
|
72
95
|
return datasource.enabled ? -1 : 1;
|
|
73
96
|
}).map((datasource) => {
|
|
@@ -82,7 +105,7 @@ var DefaultContext = class {
|
|
|
82
105
|
}).join(", "));
|
|
83
106
|
const enabledDatasources = datasources.filter((d) => d.enabled);
|
|
84
107
|
logger?.info(accent`Using ${enabledDatasources.length} of ${datasources.length} resolved datasources` + (enabledDatasources.length > 0 ? ":" : ""), enabledDatasources.map((datasource) => {
|
|
85
|
-
return [colorize("greenBright", datasource.name), colorize("yellow", "(" +
|
|
108
|
+
return [colorize("greenBright", datasource.name), colorize("yellow", "(" + datasource.drivers.map((driver) => driver.name).join(", ") + ")")].join(" ");
|
|
86
109
|
}).join(", "));
|
|
87
110
|
this.#datasources = datasources;
|
|
88
111
|
}
|
|
@@ -91,10 +114,23 @@ var DefaultContext = class {
|
|
|
91
114
|
async migrationAssets(datasources) {
|
|
92
115
|
const migrationOptions = this.#options.migrations;
|
|
93
116
|
if (!migrationOptions) return [];
|
|
94
|
-
return datasources.
|
|
117
|
+
return datasources.flatMap((datasource) => {
|
|
118
|
+
return datasource.drivers.map((driver) => {
|
|
119
|
+
return {
|
|
120
|
+
name: datasource.name,
|
|
121
|
+
driver: driver.name,
|
|
122
|
+
dialect: driver.dialect,
|
|
123
|
+
migrations: driver.migrations
|
|
124
|
+
};
|
|
125
|
+
});
|
|
126
|
+
}).reduce((acc, { name, driver, migrations }) => {
|
|
95
127
|
const dir = migrations.assets;
|
|
96
128
|
if (dir) acc.push({
|
|
97
|
-
baseName:
|
|
129
|
+
baseName: [
|
|
130
|
+
migrationOptions.storageBase,
|
|
131
|
+
name,
|
|
132
|
+
driver
|
|
133
|
+
].join(":"),
|
|
98
134
|
dir
|
|
99
135
|
});
|
|
100
136
|
return acc;
|
|
@@ -131,7 +167,8 @@ var DefaultContext = class {
|
|
|
131
167
|
return {
|
|
132
168
|
"#nitro-drizzle/runtime": runtimeVirtualModule(datasources, {
|
|
133
169
|
legacyNitro: this.#options.legacy,
|
|
134
|
-
runtimeConfigProp: "drizzle"
|
|
170
|
+
runtimeConfigProp: "drizzle",
|
|
171
|
+
initHooks: this.#options.initHooks
|
|
135
172
|
}),
|
|
136
173
|
...dialectVirtualModules(datasources),
|
|
137
174
|
...migrationsVirtualModule(datasources, this.#options.migrations)
|
|
@@ -141,6 +178,12 @@ var DefaultContext = class {
|
|
|
141
178
|
this.#datasources = null;
|
|
142
179
|
}
|
|
143
180
|
};
|
|
181
|
+
function driverToDialect(driver) {
|
|
182
|
+
let dialect = driver;
|
|
183
|
+
if (driver.startsWith("d1")) dialect = "sqlite";
|
|
184
|
+
if (driver == "pglite") dialect = "postgresql";
|
|
185
|
+
return dialect;
|
|
186
|
+
}
|
|
144
187
|
/**
|
|
145
188
|
* Creates a Context instance for managing Drizzle datasource configurations.
|
|
146
189
|
* @param options - Configuration options for the context
|
package/dist/context.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.mjs","names":["#options","#datasources"],"sources":["../src/context/index.ts"],"sourcesContent":["import type { ConsolaInstance } from \"consola\";\nimport { colorize, type ColorName } from \"consola/utils\";\nimport type { Config, Config as DrizzleConfig } from \"drizzle-kit\";\nimport { loadConfig } from \"c12\";\nimport { pkgDir, pkgName } from \"nitro-drizzle/meta\";\n\nimport { mapAsync } from \"./internal/async\";\nimport { accent } from \"./internal/logger\";\nimport { resolveFiles } from \"./internal/fs\";\nimport {\n dialectDeclarations,\n genReference,\n moduleTypeDeclarations,\n runtimeDeclarations,\n} from \"./internal/templates\";\nimport { transformDrizzleConfig } from \"./internal/config\";\nimport {\n dialectVirtualModules,\n migrationsVirtualModule,\n runtimeVirtualModule,\n} from \"./internal/virtual\";\n\nimport type { MaybePromise, VirtualModules } from \"nitro-drizzle/shared\";\nimport type { ServerAssetDir } from \"nitropack/types\";\nimport { join } from \"pathe\";\n\n/**\n * Context interface for managing Drizzle datasource configurations.\n */\nexport interface Context {\n init(): MaybePromise<void>;\n /**\n * Reloads the context, clearing any cached datasource information.\n */\n reload(): MaybePromise<void>;\n /**\n * Returns a list of all resolved datasource information.\n */\n datasources(): MaybePromise<DatasourceInfo[]>;\n}\n\nclass DefaultContext implements Context {\n #datasources: DatasourceInfo[] | null = null;\n readonly #options: ContextOptions;\n\n constructor(options: ContextOptions) {\n this.#options = options;\n }\n\n async init(): Promise<void> {\n const datasources = await this.datasources();\n\n await this.#options.plugins(this.enabledPlugins());\n\n const [virtualModules, virtualTypes, moduleTypes, runtimeTypes] = await Promise.all([\n this.virtualModules(datasources),\n this.virtualTypeDeclarations(datasources),\n this.moduleTypeDeclarations(datasources),\n this.runtimeTypeDeclarations(datasources),\n ]);\n\n await this.#options.virtualModules(virtualModules);\n\n await this.#options.declarations({\n virtual: virtualTypes,\n module: moduleTypes,\n runtime: runtimeTypes,\n });\n\n if (this.#options.migrations) {\n const assets = await this.migrationAssets(datasources);\n if (assets) {\n await this.#options.assets(assets);\n }\n\n await this.#options.tasks?.({\n \"drizzle:migrate\": {\n description: \"Run drizzle migrations for a datasource.\",\n handler: \"nitro-drizzle/migrations/task\",\n },\n });\n }\n\n if (this.#options.externals) {\n const inlineModuleIds = [\"runtime\", \"plugins\", \"migrations\"].flatMap((id) => {\n return [join(pkgName, id), join(pkgDir, \"dist\", id)];\n });\n\n await this.#options.externals(inlineModuleIds);\n }\n }\n\n async datasources() {\n const {\n logger,\n baseDir,\n configPattern,\n resolver,\n datasources: datasourceOptions,\n } = this.#options;\n\n if (!this.#datasources) {\n logger?.info(\"Searching drizzle datasources in\", colorize(\"blue\", baseDir));\n\n const drizzleConfigsResolvedPaths = await resolveFiles(\n baseDir,\n [configPattern].flat().map((pattern) => \"*/\" + pattern),\n );\n\n let datasources: DatasourceInfo[] = await mapAsync(\n drizzleConfigsResolvedPaths,\n async (path) => {\n const { config } = await loadConfig<DrizzleConfig>({\n configFile: path,\n });\n const [_, dirName] = path.match(/(.+\\/(.+))\\/.+$/)!.slice(1, 3) as [string, string];\n\n return await transformDrizzleConfig(config, {\n cwd: this.#options.cwd,\n path,\n dirName,\n resolver,\n });\n },\n );\n\n datasources = Object.entries(datasourceOptions).reduce((_datasources, [name, options]) => {\n const datasource = datasources.find(\n (d) => d.name == name && options.connector == (d.driver ? d.driver : d.dialect),\n );\n if (!datasource) {\n return _datasources;\n }\n return [..._datasources, datasource];\n }, [] as DatasourceInfo[]);\n\n logger?.info(\n \"Found drizzle datasources:\",\n datasources\n .toSorted((datasource) => {\n return datasource.enabled ? -1 : 1;\n })\n .map((datasource) => {\n let msg = [datasource.name];\n let color: ColorName;\n if (datasource.enabled) {\n color = \"greenBright\";\n } else {\n color = \"gray\";\n msg.push(\"(disabled)\");\n }\n return colorize(color, msg.join(\" \"));\n })\n .join(\", \"),\n );\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n logger?.info(\n accent`Using ${enabledDatasources.length} of ${datasources.length} resolved datasources` +\n (enabledDatasources.length > 0 ? \":\" : \"\"),\n enabledDatasources\n .map((datasource) => {\n return [\n colorize(\"greenBright\", datasource.name),\n colorize(\"yellow\", \"(\" + (datasource.driver || datasource.dialect) + \")\"),\n ].join(\" \");\n })\n .join(\", \"),\n );\n\n this.#datasources = datasources;\n }\n\n return this.#datasources;\n }\n\n private async migrationAssets(\n datasources: readonly DatasourceInfo[],\n ): Promise<readonly ServerAssetDir[]> {\n const migrationOptions = this.#options.migrations;\n\n if (!migrationOptions) {\n return [];\n }\n\n return datasources.reduce((acc, { name, migrations }) => {\n const dir = migrations.assets;\n if (dir) {\n acc.push({\n baseName: `${migrationOptions.storageBase}:${name}`,\n dir,\n /**\n * @todo Doesn't work in dev mode - 'fs' driver does not support 'pattern'\n * Disabled - include all files to use with meta/_journal.json\n */\n // pattern: '*.sql',\n });\n }\n return acc;\n }, [] as ServerAssetDir[]);\n }\n\n private async virtualTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<Record<string, VirtualModules<`${string}.d.ts`>>> {\n return {\n \"#nitro-drizzle/*\": {\n \"nitro-drizzle/virtual.d.ts\": [dialectDeclarations(datasources)].join(\"\\n\"),\n },\n };\n }\n\n private enabledPlugins(): readonly string[] {\n const plugins: (\"init\" | \"migrate\")[] = [];\n\n const migrationOptions = this.#options.migrations;\n const enableMigrationPlugin = migrationOptions\n ? Array.isArray(migrationOptions)\n ? 0 < migrationOptions.length\n : true == migrationOptions.migrateOnInit\n : false;\n\n if (enableMigrationPlugin) {\n plugins.push(\"migrate\");\n }\n\n plugins.push(\"init\");\n\n let pluginIds: readonly string[] = plugins;\n if (this.#options.legacy) {\n pluginIds = pluginIds.map((pluginName) => `legacy/${pluginName}`);\n }\n pluginIds = pluginIds.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);\n\n return pluginIds;\n }\n\n private async moduleTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules> {\n return moduleTypeDeclarations(datasources);\n }\n\n private async runtimeTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`${string}.d.ts`>> {\n const references = new Set([\n { types: \"nitro-drizzle/runtime\" },\n ...this.enabledPlugins().map((pluginId) => {\n return { types: pluginId };\n }),\n ]);\n if (!this.#options.legacy) {\n references.add({ types: \"nitro-drizzle/middleware/context\" });\n }\n const content = [\n ...[...references.values()].map((reference) => genReference(reference)),\n runtimeDeclarations(datasources),\n /* ts */ `export {};`,\n ].join(\"\\n\");\n return {\n \"nitro-drizzle/runtime.d.ts\": content,\n };\n }\n\n private async virtualModules(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`#nitro-drizzle/${string}`>> {\n return {\n \"#nitro-drizzle/runtime\": runtimeVirtualModule(datasources, {\n legacyNitro: this.#options.legacy,\n runtimeConfigProp: \"drizzle\",\n }),\n ...dialectVirtualModules(datasources),\n ...migrationsVirtualModule(datasources, this.#options.migrations),\n };\n }\n\n reload() {\n this.#datasources = null;\n }\n}\n\n/**\n * Glob pattern or array of patterns to match Drizzle configuration files.\n */\nexport type ConfigPattern = string | readonly string[];\n\n/**\n * Resolver interface for importing modules and resolving paths.\n */\nexport interface Resolver {\n /**\n * Resolves a module ID to its full path.\n */\n resolve(id: string): string;\n}\n\nexport type ContextHook<TArgs extends readonly any[] = []> = (\n this: void,\n ...args: TArgs\n) => MaybePromise<void>;\n\nexport interface MigrationOptions {\n /** Base storage key path for migrations. */\n storageBase: string;\n /** Whether and which datasources to migrate on initialization. */\n migrateOnInit: boolean | readonly string[];\n}\n\nexport interface ContextOptions {\n legacy: boolean;\n\n logger?: ConsolaInstance;\n /**\n * Current working directory\n */\n cwd: string;\n /**\n * Base project directory to search drizzle config files\n */\n baseDir: string;\n /**\n * Pattern for drizzle config files\n */\n configPattern: ConfigPattern;\n /**\n * Nuxt Kit resolver\n */\n resolver: Resolver;\n /**\n * Connector options\n */\n datasources: Record<string, { connector: string }>;\n\n migrations: MigrationOptions | undefined;\n\n tasks?: ContextHook<\n [\n tasks: Record<\n string,\n {\n handler: string;\n description: string;\n }\n >,\n ]\n >;\n\n plugins: ContextHook<[plugins: readonly string[]]>;\n\n declarations: ContextHook<\n [\n declarations: {\n module: VirtualModules<`${string}.d.ts`>;\n runtime: VirtualModules<`${string}.d.ts`>;\n virtual: Record<string, VirtualModules<`${string}.d.ts`>>;\n },\n ]\n >;\n\n virtualModules: ContextHook<[modules: VirtualModules]>;\n\n assets: ContextHook<[assets: readonly ServerAssetDir[]]>;\n\n externals?: ContextHook<[modules: readonly string[]]>;\n}\n\n/**\n * Creates a Context instance for managing Drizzle datasource configurations.\n * @param options - Configuration options for the context\n * @returns A Context instance\n */\nexport function createContext(options: ContextOptions): Context {\n return new DefaultContext(options);\n}\n\n/**\n * Information about a resolved Drizzle datasource.\n */\nexport interface DatasourceInfo {\n /** Directory name of the datasource (derived from config file location). */\n dirName: string;\n /** Unique name identifier for the datasource. */\n name: string;\n /** Whether the datasource is enabled (filtered by connector configuration). */\n enabled: boolean;\n /** Database dialect (e.g., 'sqlite', 'postgresql', 'mysql'). */\n dialect: string;\n /** Driver type if specified in config, otherwise undefined. */\n driver: string | undefined;\n /** Import paths for schema, connector, and helpers. */\n imports: {\n config: string;\n schema: string[];\n connector: string;\n helpers: string;\n };\n /** Migration configuration for this datasource. */\n migrations: {\n assets?: string;\n config?: Config[\"migrations\"];\n };\n}\n"],"mappings":";;;;;;;;;;;AAyCA,IAAM,iBAAN,MAAwC;CACtC,eAAwC;CACxC;CAEA,YAAY,SAAyB;EACnC,KAAKA,WAAW;CAClB;CAEA,MAAM,OAAsB;EAC1B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,0BAA0B,qBAAqB,aAAa;IAC1D,aAAa,KAAKA,SAAS;IAC3B,mBAAmB;GACrB,CAAC;GACD,GAAG,sBAAsB,WAAW;GACpC,GAAG,wBAAwB,aAAa,KAAKA,SAAS,UAAU;EAClE;CACF;CAEA,SAAS;EACP,KAAKC,eAAe;CACtB;AACF;;;;;;AA4FA,SAAgB,cAAc,SAAkC;CAC9D,OAAO,IAAI,eAAe,OAAO;AACnC"}
|
|
1
|
+
{"version":3,"file":"context.mjs","names":["#options","#datasources"],"sources":["../src/context/index.ts"],"sourcesContent":["import type { ConsolaInstance } from \"consola\";\nimport { colorize, type ColorName } from \"consola/utils\";\nimport type { Config, Config as DrizzleConfig } from \"drizzle-kit\";\nimport { loadConfig } from \"c12\";\nimport { pkgDir, pkgName } from \"nitro-drizzle/meta\";\n\nimport { mapAsync } from \"./internal/async\";\nimport { accent } from \"./internal/logger\";\nimport { resolveFiles } from \"./internal/fs\";\nimport {\n dialectDeclarations,\n moduleTypeDeclarations,\n runtimeDeclarations,\n sharedTypeDeclarations,\n} from \"./internal/templates\";\nimport { transformDrizzleConfig } from \"./internal/config\";\nimport {\n dialectVirtualModules,\n migrationsVirtualModule,\n runtimeVirtualModule,\n} from \"./internal/virtual\";\n\nimport type { MaybePromise, NitroHookName, VirtualModules } from \"nitro-drizzle/shared\";\nimport type { ServerAssetDir as LegacyServerAssetDir } from \"nitropack/types\";\nimport type { ServerAssetDir } from \"nitro/types\";\nimport { join } from \"pathe\";\nimport { genReference } from \"./internal/codegen\";\n\n/**\n * Context interface for managing Drizzle datasource configurations.\n */\nexport interface Context {\n init(): MaybePromise<void>;\n /**\n * Reloads the context, clearing any cached datasource information.\n */\n reload(): MaybePromise<void>;\n /**\n * Returns a list of all resolved datasource information.\n */\n datasources(): MaybePromise<DatasourceInfo[]>;\n}\n\nclass DefaultContext implements Context {\n #datasources: DatasourceInfo[] | null = null;\n readonly #options: ContextOptions;\n\n constructor(options: ContextOptions) {\n this.#options = options;\n }\n\n async init(): Promise<void> {\n const datasources = await this.datasources();\n\n await this.#options.plugins(this.enabledPlugins());\n\n const [sharedTypes, virtualModules, virtualTypes, moduleTypes, runtimeTypes] =\n await Promise.all([\n sharedTypeDeclarations(datasources),\n this.virtualModules(datasources),\n this.virtualTypeDeclarations(datasources),\n this.moduleTypeDeclarations(datasources),\n this.runtimeTypeDeclarations(datasources),\n ]);\n\n await this.#options.virtualModules(virtualModules);\n\n await this.#options.declarations({\n shared: sharedTypes,\n module: moduleTypes,\n runtime: runtimeTypes,\n virtual: virtualTypes,\n });\n\n if (this.#options.migrations) {\n const assets = await this.migrationAssets(datasources);\n if (assets) {\n await this.#options.assets(assets);\n }\n\n await this.#options.tasks?.({\n \"drizzle:migrate\": {\n description: \"Run drizzle migrations for a datasource.\",\n handler: \"nitro-drizzle/migrations/task\",\n },\n });\n }\n\n if (this.#options.externals) {\n const inlineModuleIds = [\"runtime\", \"plugins\", \"migrations\"].flatMap((id) => {\n return [join(pkgName, id), join(pkgDir, \"dist\", id)];\n });\n\n await this.#options.externals(inlineModuleIds);\n }\n }\n\n async datasources() {\n const {\n logger,\n baseDir,\n configPattern,\n resolver,\n datasources: datasourceOptions,\n } = this.#options;\n\n if (!this.#datasources) {\n logger?.info(\"Searching drizzle datasources in\", colorize(\"blue\", baseDir));\n\n const drizzleConfigsResolvedPaths = await resolveFiles(\n baseDir,\n [configPattern].flat().map((pattern) => \"*/\" + pattern),\n );\n\n const drizzleConfigs = [\n ...(await mapAsync(drizzleConfigsResolvedPaths, async (path) => {\n const [_, dirName] = path.match(/(.+\\/(.+))\\/.+$/)!.slice(1, 3) as [string, string];\n const { config } = await loadConfig<DrizzleConfig>({\n configFile: path,\n });\n\n return await transformDrizzleConfig(config, {\n cwd: this.#options.cwd,\n path,\n dirName,\n resolver,\n });\n })),\n ].sort((a, b) => {\n if (a.driver && b.driver) {\n return 0;\n }\n return 1;\n });\n\n const datasources: DatasourceInfo[] = Object.entries(datasourceOptions).map(\n ([name, options]) => {\n const drivers: readonly string[] = Array.isArray(options.drivers)\n ? options.drivers\n : Object.entries(options.drivers as { [name: string]: boolean })\n .filter(([_name, enabled]) => enabled)\n .map(([name]) => name);\n return {\n name,\n enabled: true,\n drivers: drivers.map((driverName) => {\n const dialect = driverToDialect(driverName);\n const drizzleConfig = drizzleConfigs.find((config) => {\n return config.name == name && config.dialect == dialect;\n });\n return {\n name: driverName,\n dialect,\n imports: {\n connector: `nitro-drizzle/drivers/${driverName}`,\n helpers: `nitro-drizzle/dialects/${dialect}`,\n schema: drizzleConfig?.imports.schema || [],\n },\n migrations: {\n ...drizzleConfig?.migrations,\n },\n };\n }),\n } satisfies DatasourceInfo;\n },\n );\n\n logger?.info(\n \"Found drizzle datasources:\",\n datasources\n .toSorted((datasource) => {\n return datasource.enabled ? -1 : 1;\n })\n .map((datasource) => {\n let msg = [datasource.name];\n let color: ColorName;\n if (datasource.enabled) {\n color = \"greenBright\";\n } else {\n color = \"gray\";\n msg.push(\"(disabled)\");\n }\n return colorize(color, msg.join(\" \"));\n })\n .join(\", \"),\n );\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n logger?.info(\n accent`Using ${enabledDatasources.length} of ${datasources.length} resolved datasources` +\n (enabledDatasources.length > 0 ? \":\" : \"\"),\n enabledDatasources\n .map((datasource) => {\n return [\n colorize(\"greenBright\", datasource.name),\n colorize(\n \"yellow\",\n \"(\" + datasource.drivers.map((driver) => driver.name).join(\", \") + \")\",\n ),\n ].join(\" \");\n })\n .join(\", \"),\n );\n\n this.#datasources = datasources;\n }\n\n return this.#datasources;\n }\n\n private async migrationAssets(\n datasources: readonly DatasourceInfo[],\n ): Promise<readonly (ServerAssetDir | LegacyServerAssetDir)[]> {\n const migrationOptions = this.#options.migrations;\n\n if (!migrationOptions) {\n return [];\n }\n\n return datasources\n .flatMap((datasource) => {\n return datasource.drivers.map((driver) => {\n return {\n name: datasource.name,\n driver: driver.name,\n dialect: driver.dialect,\n migrations: driver.migrations,\n };\n });\n })\n .reduce(\n (acc, { name, driver, migrations }) => {\n const dir = migrations.assets;\n if (dir) {\n acc.push({\n baseName: [migrationOptions.storageBase, name, driver].join(\":\"),\n dir,\n /**\n * @todo Doesn't work in dev mode - 'fs' driver does not support 'pattern'\n * Disabled - include all files to use with meta/_journal.json\n */\n // pattern: '*.sql',\n });\n }\n return acc;\n },\n [] as (ServerAssetDir | LegacyServerAssetDir)[],\n );\n }\n\n private async virtualTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<Record<string, VirtualModules<`${string}.d.ts`>>> {\n return {\n \"#nitro-drizzle/*\": {\n \"nitro-drizzle/virtual.d.ts\": [dialectDeclarations(datasources)].join(\"\\n\"),\n },\n };\n }\n\n private enabledPlugins(): readonly string[] {\n const plugins: (\"init\" | \"migrate\")[] = [];\n\n const migrationOptions = this.#options.migrations;\n const enableMigrationPlugin = migrationOptions\n ? Array.isArray(migrationOptions)\n ? 0 < migrationOptions.length\n : true == migrationOptions.migrateOnInit\n : false;\n\n if (enableMigrationPlugin) {\n plugins.push(\"migrate\");\n }\n\n plugins.push(\"init\");\n\n let pluginIds: readonly string[] = plugins;\n if (this.#options.legacy) {\n pluginIds = pluginIds.map((pluginName) => `legacy/${pluginName}`);\n }\n pluginIds = pluginIds.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);\n\n return pluginIds;\n }\n\n private async moduleTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules> {\n return moduleTypeDeclarations(datasources);\n }\n\n private async runtimeTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`${string}.d.ts`>> {\n const references = new Set([\n { types: \"nitro-drizzle/runtime\" },\n ...this.enabledPlugins().map((pluginId) => {\n return { types: pluginId };\n }),\n ]);\n if (!this.#options.legacy) {\n references.add({ types: \"nitro-drizzle/middleware/context\" });\n }\n const content = [\n ...[...references.values()].map((reference) => genReference(reference)),\n runtimeDeclarations(datasources),\n /* ts */ `export {};`,\n ].join(\"\\n\");\n return {\n \"nitro-drizzle/runtime.d.ts\": content,\n };\n }\n\n private async virtualModules(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`#nitro-drizzle/${string}`>> {\n return {\n \"#nitro-drizzle/runtime\": runtimeVirtualModule(datasources, {\n legacyNitro: this.#options.legacy,\n runtimeConfigProp: \"drizzle\",\n initHooks: this.#options.initHooks,\n }),\n ...dialectVirtualModules(datasources),\n ...migrationsVirtualModule(datasources, this.#options.migrations),\n };\n }\n\n reload() {\n this.#datasources = null;\n }\n}\n\nfunction driverToDialect(driver: string) {\n let dialect = driver;\n if (driver.startsWith(\"d1\")) {\n dialect = \"sqlite\";\n }\n if (driver == \"pglite\") {\n dialect = \"postgresql\";\n }\n return dialect;\n}\n\n/**\n * Glob pattern or array of patterns to match Drizzle configuration files.\n */\nexport type ConfigPattern = string | readonly string[];\n\n/**\n * Resolver interface for importing modules and resolving paths.\n */\nexport interface Resolver {\n /**\n * Resolves a module ID to its full path.\n */\n resolve(id: string): string;\n}\n\nexport type ContextHook<TArgs extends readonly any[] = []> = (\n this: void,\n ...args: TArgs\n) => MaybePromise<void>;\n\nexport interface MigrationOptions {\n /** Base storage key path for migrations. */\n storageBase: string;\n /** Whether and which datasources to migrate on initialization. */\n migrateOnInit: boolean | readonly string[];\n}\n\nexport interface ContextOptions {\n legacy: boolean;\n\n logger?: ConsolaInstance;\n /**\n * Current working directory\n */\n cwd: string;\n /**\n * Base project directory to search drizzle config files\n */\n baseDir: string;\n /**\n * Pattern for drizzle config files\n */\n configPattern: ConfigPattern;\n /**\n * Nuxt Kit resolver\n */\n resolver: Resolver;\n /**\n * Connector options\n */\n datasources: Record<string, { drivers: readonly string[] | { [name: string]: boolean } }>;\n\n migrations: MigrationOptions | undefined;\n\n /**\n * Hooks that allowed to call \"drizzle:init\" hook.\n */\n initHooks?: readonly NitroHookName[];\n\n tasks?: ContextHook<\n [\n tasks: Record<\n string,\n {\n handler: string;\n description: string;\n }\n >,\n ]\n >;\n\n plugins: ContextHook<[plugins: readonly string[]]>;\n\n declarations: ContextHook<\n [\n declarations: {\n shared: VirtualModules<`${string}.d.ts`>;\n module: VirtualModules<`${string}.d.ts`>;\n runtime: VirtualModules<`${string}.d.ts`>;\n virtual: Record<string, VirtualModules<`${string}.d.ts`>>;\n },\n ]\n >;\n\n virtualModules: ContextHook<[modules: VirtualModules]>;\n\n assets: ContextHook<[assets: readonly (ServerAssetDir | LegacyServerAssetDir)[]]>;\n\n externals?: ContextHook<[modules: readonly string[]]>;\n}\n\n/**\n * Creates a Context instance for managing Drizzle datasource configurations.\n * @param options - Configuration options for the context\n * @returns A Context instance\n */\nexport function createContext(options: ContextOptions): Context {\n return new DefaultContext(options);\n}\n\n/**\n * Information about a resolved Drizzle datasource.\n */\nexport interface DatasourceInfo {\n /** Unique name identifier for the datasource. */\n name: string;\n /** Whether the datasource is enabled (filtered by connector configuration). */\n enabled: boolean;\n /** Driver configurations for this datasource. */\n drivers: readonly DriverOptions[];\n}\n\n/** Options for a specific driver within a datasource. */\nexport type DriverOptions = {\n name: string;\n dialect: string;\n imports: {\n // config: string;\n schema: readonly string[];\n connector: string;\n helpers: string;\n };\n /** Migration configuration for this datasource driver. */\n migrations: {\n assets?: string;\n config?: Config[\"migrations\"];\n };\n};\n"],"mappings":";;;;;;;;;;;;AA2CA,IAAM,iBAAN,MAAwC;CACtC,eAAwC;CACxC;CAEA,YAAY,SAAyB;EACnC,KAAKA,WAAW;CAClB;CAEA,MAAM,OAAsB;EAC1B,MAAM,cAAc,MAAM,KAAK,YAAY;EAE3C,MAAM,KAAKA,SAAS,QAAQ,KAAK,eAAe,CAAC;EAEjD,MAAM,CAAC,aAAa,gBAAgB,cAAc,aAAa,gBAC7D,MAAM,QAAQ,IAAI;GAChB,uBAAuB,WAAW;GAClC,KAAK,eAAe,WAAW;GAC/B,KAAK,wBAAwB,WAAW;GACxC,KAAK,uBAAuB,WAAW;GACvC,KAAK,wBAAwB,WAAW;EAC1C,CAAC;EAEH,MAAM,KAA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AAI,CACzB,EAAE,OAAO,wBAAwB,GACjC,GAAG,KAAK,eAAe,CAAC,CAAC,KAAK,aAAa;GACzC,OAAO,EAAE,OAAO,SAAS;EAC3B,CAAC,CACH,CAAC;EACD,IAAI,CAAC,KAAKA,SAAS,QACjB,WAAW,IAAI,EAAE,OAAO,mCAAmC,CAAC;EAO9D,OAAO,EACL,8BANc;GACd,GAAG,CAAC,GAAG,WAAW,OAAO,CAAC,CAAC,CAAC,KAAK,cAAc,aAAa,SAAS,CAAC;GACtE,oBAAoB,WAAW;GACtB;EACX,CAAC,CAAC,KAAK,IAE+B,EACtC;CACF;CAEA,MAAc,eACZ,aACqD;EACrD,OAAO;GACL,0BAA0B,qBAAqB,aAAa;IAC1D,aAAa,KAAKA,SAAS;IAC3B,mBAAmB;IACnB,WAAW,KAAKA,SAAS;GAC3B,CAAC;GACD,GAAG,sBAAsB,WAAW;GACpC,GAAG,wBAAwB,aAAa,KAAKA,SAAS,UAAU;EAClE;CACF;CAEA,SAAS;EACP,KAAKC,eAAe;CACtB;AACF;AAEA,SAAS,gBAAgB,QAAgB;CACvC,IAAI,UAAU;CACd,IAAI,OAAO,WAAW,IAAI,GACxB,UAAU;CAEZ,IAAI,UAAU,UACZ,UAAU;CAEZ,OAAO;AACT;;;;;;AAkGA,SAAgB,cAAc,SAAkC;CAC9D,OAAO,IAAI,eAAe,OAAO;AACnC"}
|
|
@@ -13,11 +13,11 @@ declare function onConflictDoUpdate<TInsert extends SQLiteInsertBase<any, any, a
|
|
|
13
13
|
/**
|
|
14
14
|
* Adds an ON CONFLICT DO NOTHING clause to a SQLite insert statement.
|
|
15
15
|
* @template TInsert - The insert type
|
|
16
|
-
* @param
|
|
16
|
+
* @param target - Partial object of columns
|
|
17
17
|
* @param insert - The insert statement
|
|
18
18
|
* @returns The modified insert statement with DO NOTHING
|
|
19
19
|
*/
|
|
20
|
-
declare function onConflictDoNothing<TInsert extends SQLiteInsertBase<any, any, any, any, any, any>>(
|
|
20
|
+
declare function onConflictDoNothing<TInsert extends SQLiteInsertBase<any, any, any, any, any, any>>(target: Partial<InferColumns<InferTable<TInsert>>>, insert: TInsert): TInsert;
|
|
21
21
|
/**
|
|
22
22
|
* Infers the table type from a SQLite insert statement.
|
|
23
23
|
* @template T - The insert type
|
package/dist/dialects/sqlite.mjs
CHANGED
|
@@ -16,12 +16,12 @@ function onConflictDoUpdate(target, insert, options) {
|
|
|
16
16
|
/**
|
|
17
17
|
* Adds an ON CONFLICT DO NOTHING clause to a SQLite insert statement.
|
|
18
18
|
* @template TInsert - The insert type
|
|
19
|
-
* @param
|
|
19
|
+
* @param target - Partial object of columns
|
|
20
20
|
* @param insert - The insert statement
|
|
21
21
|
* @returns The modified insert statement with DO NOTHING
|
|
22
22
|
*/
|
|
23
|
-
function onConflictDoNothing(
|
|
24
|
-
return insert.onConflictDoNothing();
|
|
23
|
+
function onConflictDoNothing(target, insert) {
|
|
24
|
+
return insert.onConflictDoNothing({ target: Object.values(target) });
|
|
25
25
|
}
|
|
26
26
|
//#endregion
|
|
27
27
|
export { onConflictDoNothing, onConflictDoUpdate };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite.mjs","names":[],"sources":["../../src/dialects/sqlite.ts"],"sourcesContent":["import type { SQLiteInsertBase } from \"drizzle-orm/sqlite-core\";\nimport type { InferColumns, InferTable, OnConflictDoUpdateOptions } from \".\";\n\n/**\n * Adds an ON CONFLICT DO UPDATE clause to a SQLite insert statement.\n * @template TInsert - The insert type\n * @param target - Partial object of columns to target for conflict detection\n * @param insert - The insert statement\n * @param options - Options containing the SET values\n * @returns The modified insert statement\n */\nexport function onConflictDoUpdate<TInsert extends SQLiteInsertBase<any, any, any, any, any, any>>(\n target: Partial<InferColumns<InferTable<TInsert>>>,\n insert: TInsert,\n options: OnConflictDoUpdateOptions<TInsert>,\n): TInsert {\n return insert.onConflictDoUpdate({\n target: Object.values(target),\n set: options.set,\n });\n}\n\n/**\n * Adds an ON CONFLICT DO NOTHING clause to a SQLite insert statement.\n * @template TInsert - The insert type\n * @param
|
|
1
|
+
{"version":3,"file":"sqlite.mjs","names":[],"sources":["../../src/dialects/sqlite.ts"],"sourcesContent":["import type { SQLiteInsertBase } from \"drizzle-orm/sqlite-core\";\nimport type { InferColumns, InferTable, OnConflictDoUpdateOptions } from \".\";\n\n/**\n * Adds an ON CONFLICT DO UPDATE clause to a SQLite insert statement.\n * @template TInsert - The insert type\n * @param target - Partial object of columns to target for conflict detection\n * @param insert - The insert statement\n * @param options - Options containing the SET values\n * @returns The modified insert statement\n */\nexport function onConflictDoUpdate<TInsert extends SQLiteInsertBase<any, any, any, any, any, any>>(\n target: Partial<InferColumns<InferTable<TInsert>>>,\n insert: TInsert,\n options: OnConflictDoUpdateOptions<TInsert>,\n): TInsert {\n return insert.onConflictDoUpdate({\n target: Object.values(target),\n set: options.set,\n });\n}\n\n/**\n * Adds an ON CONFLICT DO NOTHING clause to a SQLite insert statement.\n * @template TInsert - The insert type\n * @param target - Partial object of columns\n * @param insert - The insert statement\n * @returns The modified insert statement with DO NOTHING\n */\nexport function onConflictDoNothing<TInsert extends SQLiteInsertBase<any, any, any, any, any, any>>(\n target: Partial<InferColumns<InferTable<TInsert>>>,\n insert: TInsert,\n): TInsert {\n return insert.onConflictDoNothing({\n target: Object.values(target),\n });\n}\n\n/**\n * Infers the table type from a SQLite insert statement.\n * @template T - The insert type\n */\nexport type InferSqliteTable<T extends SQLiteInsertBase<any, any, any, any, any, any>> =\n T extends SQLiteInsertBase<infer TTable, any, any, any, any, any> ? TTable : never;\n"],"mappings":";;;;;;;;;AAWA,SAAgB,mBACd,QACA,QACA,SACS;CACT,OAAO,OAAO,mBAAmB;EAC/B,QAAQ,OAAO,OAAO,MAAM;EAC5B,KAAK,QAAQ;CACf,CAAC;AACH;;;;;;;;AASA,SAAgB,oBACd,QACA,QACS;CACT,OAAO,OAAO,oBAAoB,EAChC,QAAQ,OAAO,OAAO,MAAM,EAC9B,CAAC;AACH"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { sql } from "drizzle-orm";
|
|
2
2
|
import { SQLiteAsyncDialect } from "drizzle-orm/sqlite-core";
|
|
3
3
|
import { SQLiteRaw } from "drizzle-orm/sqlite-core/query-builders/raw";
|
|
4
|
-
//#region src/drivers/
|
|
4
|
+
//#region src/drivers/d1/dialect.ts
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
6
|
+
* SQLite dialect for Cloudflare D1 that uses batching instead of transactions for migrations.
|
|
7
|
+
* D1 does not support transactions, so migrations are executed as a batch.
|
|
7
8
|
* @see [Cloudflare D1 transaction not supported #2463](https://github.com/drizzle-team/drizzle-orm/issues/2463)
|
|
8
9
|
*/
|
|
9
10
|
var SQLiteD1Dialect = class extends SQLiteAsyncDialect {
|
|
@@ -38,4 +39,4 @@ function createBatchItem({ session, dialect, sql }) {
|
|
|
38
39
|
//#endregion
|
|
39
40
|
export { SQLiteD1Dialect };
|
|
40
41
|
|
|
41
|
-
//# sourceMappingURL=
|
|
42
|
+
//# sourceMappingURL=dialect.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dialect.mjs","names":[],"sources":["../../../src/drivers/d1/dialect.ts"],"sourcesContent":["import { sql, type SQL } from \"drizzle-orm\";\nimport type { BatchItem } from \"drizzle-orm/batch\";\nimport type { SQLiteD1Session } from \"drizzle-orm/d1\";\nimport type { MigrationMeta, MigrationConfig } from \"drizzle-orm/migrator\";\nimport { SQLiteAsyncDialect, type SQLiteSession } from \"drizzle-orm/sqlite-core\";\nimport { SQLiteRaw } from \"drizzle-orm/sqlite-core/query-builders/raw\";\n\n/**\n * SQLite dialect for Cloudflare D1 that uses batching instead of transactions for migrations.\n * D1 does not support transactions, so migrations are executed as a batch.\n * @see [Cloudflare D1 transaction not supported #2463](https://github.com/drizzle-team/drizzle-orm/issues/2463)\n */\nexport class SQLiteD1Dialect extends SQLiteAsyncDialect {\n override async migrate(\n migrations: Iterable<MigrationMeta>,\n session: SQLiteD1Session<any, any>,\n config?: MigrationConfig,\n ): Promise<void> {\n const migrationsTable = config?.migrationsTable || \"__drizzle_migrations\";\n const migrationTableCreate = sql`\n CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (\n id SERIAL PRIMARY KEY,\n hash text NOT NULL,\n created_at numeric\n )\n `;\n await session.run(migrationTableCreate);\n const dbMigrations = await session.values(\n sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`,\n );\n const lastDbMigration = dbMigrations[0] ?? void 0;\n\n const statementsToBatch: SQL[] = [];\n for (const migration of migrations) {\n if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {\n for (const stmt of migration.sql) {\n statementsToBatch.push(sql.raw(stmt));\n }\n statementsToBatch.push(\n sql`INSERT INTO ${sql.identifier(migrationsTable)} (\"hash\", \"created_at\") VALUES(${sql.raw(`'${migration.hash}'`)}, ${sql.raw(`${migration.folderMillis}`)})`,\n );\n }\n }\n if (statementsToBatch.length > 0) {\n await session.batch(\n statementsToBatch.map((sql) => {\n return createBatchItem({ session, dialect: this, sql });\n }),\n );\n }\n }\n}\n\nfunction createBatchItem<TResult>({\n session,\n dialect,\n sql,\n}: CreateBatchItemOptions): BatchItem<\"sqlite\"> {\n return new SQLiteRaw<TResult>(\n async () => await session.run(sql),\n () => sql,\n \"run\",\n dialect,\n (result) => result,\n );\n}\n\ntype CreateBatchItemOptions = {\n session: SQLiteSession<\"async\", any, any, any>;\n dialect: SQLiteAsyncDialect;\n sql: SQL<unknown>;\n};\n"],"mappings":";;;;;;;;;AAYA,IAAa,kBAAb,cAAqC,mBAAmB;CACtD,MAAe,QACb,YACA,SACA,QACe;EACf,MAAM,kBAAkB,QAAQ,mBAAmB;EACnD,MAAM,uBAAuB,GAAG;mCACD,IAAI,WAAW,eAAe,EAAE;;;;;;EAM/D,MAAM,QAAQ,IAAI,oBAAoB;EAItC,MAAM,mBAAkB,MAHG,QAAQ,OACjC,GAAG,oCAAoC,IAAI,WAAW,eAAe,EAAE,kCACzE,EAAA,CACqC,MAAM,KAAK;EAEhD,MAAM,oBAA2B,CAAC;EAClC,KAAK,MAAM,aAAa,YACtB,IAAI,CAAC,mBAAmB,OAAO,gBAAgB,EAAE,IAAI,UAAU,cAAc;GAC3E,KAAK,MAAM,QAAQ,UAAU,KAC3B,kBAAkB,KAAK,IAAI,IAAI,IAAI,CAAC;GAEtC,kBAAkB,KAChB,GAAG,eAAe,IAAI,WAAW,eAAe,EAAE,iCAAiC,IAAI,IAAI,IAAI,UAAU,KAAK,EAAE,EAAE,IAAI,IAAI,IAAI,GAAG,UAAU,cAAc,EAAE,EAC7J;EACF;EAEF,IAAI,kBAAkB,SAAS,GAC7B,MAAM,QAAQ,MACZ,kBAAkB,KAAK,QAAQ;GAC7B,OAAO,gBAAgB;IAAE;IAAS,SAAS;IAAM;GAAI,CAAC;EACxD,CAAC,CACH;CAEJ;AACF;AAEA,SAAS,gBAAyB,EAChC,SACA,SACA,OAC8C;CAC9C,OAAO,IAAI,UACT,YAAY,MAAM,QAAQ,IAAI,GAAG,SAC3B,KACN,OACA,UACC,WAAW,MACd;AACF"}
|
|
@@ -39,5 +39,5 @@ declare function d1HttpDriver(options: D1HttpOptions): D1HttpDriver;
|
|
|
39
39
|
declare function drizzle<TSchema extends Record<string, unknown> = Record<string, never>>(callback: RemoteCallback, config?: DrizzleConfig<TSchema>): SqliteRemoteDatabase<TSchema>;
|
|
40
40
|
declare function drizzle<TSchema extends Record<string, unknown> = Record<string, never>>(callback: RemoteCallback, batchCallback?: AsyncBatchRemoteCallback, config?: DrizzleConfig<TSchema>): SqliteRemoteDatabase<TSchema>;
|
|
41
41
|
//#endregion
|
|
42
|
-
export { d1HttpDriver, driver as default, drizzle };
|
|
42
|
+
export { D1HttpDriver, D1HttpOptions, d1HttpDriver, driver as default, drizzle };
|
|
43
43
|
//# sourceMappingURL=d1-http.d.mts.map
|
package/dist/drivers/d1-http.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { SQLiteD1Dialect } from "./
|
|
1
|
+
import { defineConnector } from "./index.mjs";
|
|
2
|
+
import { SQLiteD1Dialect } from "./d1/dialect.mjs";
|
|
3
3
|
import { SELECT_1 } from "./internal/sql.mjs";
|
|
4
4
|
import { DefaultLogger, createTableRelationsHelpers, extractTablesRelationalConfig } from "drizzle-orm";
|
|
5
5
|
import { SQLiteRemoteSession, SqliteRemoteDatabase } from "drizzle-orm/sqlite-proxy";
|
|
@@ -11,7 +11,7 @@ import { SQLiteRemoteSession, SqliteRemoteDatabase } from "drizzle-orm/sqlite-pr
|
|
|
11
11
|
* @param schema - The Drizzle schema
|
|
12
12
|
* @returns A Datasource instance
|
|
13
13
|
*/
|
|
14
|
-
const driver =
|
|
14
|
+
const driver = defineConnector((options, schema) => {
|
|
15
15
|
const { callback, batchCallback } = d1HttpDriver(options);
|
|
16
16
|
const database = drizzle(callback, batchCallback, { schema });
|
|
17
17
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"d1-http.mjs","names":[],"sources":["../../src/drivers/d1-http.ts"],"sourcesContent":["import {\n type AsyncRemoteCallback,\n type AsyncBatchRemoteCallback,\n SqliteRemoteDatabase,\n SQLiteRemoteSession,\n type RemoteCallback,\n} from \"drizzle-orm/sqlite-proxy\";\nimport {
|
|
1
|
+
{"version":3,"file":"d1-http.mjs","names":[],"sources":["../../src/drivers/d1-http.ts"],"sourcesContent":["import {\n type AsyncRemoteCallback,\n type AsyncBatchRemoteCallback,\n SqliteRemoteDatabase,\n SQLiteRemoteSession,\n type RemoteCallback,\n} from \"drizzle-orm/sqlite-proxy\";\nimport { defineConnector, type Schema } from \".\";\nimport {\n type DrizzleConfig,\n DefaultLogger,\n type RelationalSchemaConfig,\n type TablesRelationalConfig,\n extractTablesRelationalConfig,\n createTableRelationsHelpers,\n} from \"drizzle-orm\";\nimport { SQLiteD1Dialect } from \"./d1/dialect\";\nimport { SELECT_1 } from \"./internal/sql\";\n\n/**\n * Cloudflare D1 HTTP datasource driver for remote connections.\n * @template TSchema - The schema type\n * @param options - Driver configuration options\n * @param schema - The Drizzle schema\n * @returns A Datasource instance\n */\nconst driver = defineConnector(\n <TSchema extends Schema>(options: D1HttpOptions, schema: TSchema) => {\n const { callback, batchCallback } = d1HttpDriver(options);\n const database = drizzle(callback, batchCallback, { schema });\n return {\n database,\n schema,\n async waitReady() {\n await database.run(SELECT_1);\n },\n async close() {},\n };\n },\n);\n\nexport default driver;\n\n/** Configuration options for the Cloudflare D1 HTTP driver. */\nexport type D1HttpOptions = {\n /** Cloudflare account ID. */\n accountId: string;\n /** D1 database ID. */\n databaseId: string;\n /** API token for authentication. */\n token: string;\n};\n\n/** Internal type for the HTTP driver callback functions. */\nexport type D1HttpDriver = {\n callback: AsyncRemoteCallback;\n batchCallback: AsyncBatchRemoteCallback;\n};\n\ntype D1Response =\n | {\n success: true;\n result: [Result, ...Result[]];\n }\n | {\n success: false;\n errors: { code: number; message: string }[];\n };\n\ntype Result = {\n results:\n | any[]\n | {\n columns: string[];\n rows: any[][];\n };\n};\n\ntype D1HttpQuery = {\n sql: string;\n params: any[];\n};\n\ntype FetchD1Body =\n | {\n batch: D1HttpQuery[];\n }\n | D1HttpQuery;\n\nasync function fetchD1(url: string | URL, body: FetchD1Body, options: D1HttpOptions) {\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${options.token}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n });\n\n const data = (await res.json()) as D1Response;\n\n if (!data.success) {\n throw new Error(data.errors.map((it) => `${it.code}: ${it.message}`).join(\"\\n\"));\n }\n\n const result = data.result[0].results;\n const rows = Array.isArray(result) ? result : result.rows;\n\n return { rows };\n}\n\n/**\n * Creates an HTTP driver for Cloudflare D1 API.\n * @param options - D1 HTTP configuration options\n * @returns Object containing callback and batchCallback functions\n * @see [Cloudflare API docs](https://developers.cloudflare.com/api/resources/d1/subresources/database/methods/raw/)\n */\nexport function d1HttpDriver(options: D1HttpOptions): D1HttpDriver {\n const url = new URL(\n `accounts/${options.accountId}/d1/database/${options.databaseId}/raw`,\n \"https://api.cloudflare.com/client/v4/\",\n );\n return {\n async callback(sql, params, _) {\n const body = { sql, params };\n const res = await fetchD1(url, body, options);\n return res;\n },\n async batchCallback(batch) {\n const body = {\n batch: batch.map(({ sql, params }) => {\n return {\n sql,\n params,\n };\n }),\n };\n const res = await fetchD1(url, body, options);\n return [res];\n },\n };\n}\n\nexport function drizzle<TSchema extends Record<string, unknown> = Record<string, never>>(\n callback: RemoteCallback,\n config?: DrizzleConfig<TSchema>,\n): SqliteRemoteDatabase<TSchema>;\nexport function drizzle<TSchema extends Record<string, unknown> = Record<string, never>>(\n callback: RemoteCallback,\n batchCallback?: AsyncBatchRemoteCallback,\n config?: DrizzleConfig<TSchema>,\n): SqliteRemoteDatabase<TSchema>;\nexport function drizzle<TSchema extends Record<string, unknown> = Record<string, never>>(\n callback: RemoteCallback,\n batchCallback?: AsyncBatchRemoteCallback | DrizzleConfig<TSchema>,\n config?: DrizzleConfig<TSchema>,\n): SqliteRemoteDatabase<TSchema> {\n const dialect = new SQLiteD1Dialect({ casing: config?.casing });\n let logger;\n let cache;\n let _batchCallback: AsyncBatchRemoteCallback | undefined;\n let _config: DrizzleConfig<TSchema> = {};\n\n if (batchCallback) {\n if (typeof batchCallback === \"function\") {\n _batchCallback = batchCallback as AsyncBatchRemoteCallback;\n _config = config ?? {};\n } else {\n _batchCallback = undefined;\n _config = batchCallback as DrizzleConfig<TSchema>;\n }\n\n if (_config.logger === true) {\n logger = new DefaultLogger();\n } else if (_config.logger !== false) {\n logger = _config.logger;\n cache = _config.cache;\n }\n }\n\n let schema: RelationalSchemaConfig<TablesRelationalConfig> | undefined;\n if (_config.schema) {\n const tablesConfig = extractTablesRelationalConfig(_config.schema, createTableRelationsHelpers);\n schema = {\n fullSchema: _config.schema,\n schema: tablesConfig.tables,\n tableNamesMap: tablesConfig.tableNamesMap,\n };\n }\n\n const session = new SQLiteRemoteSession(callback, dialect, schema, _batchCallback, {\n logger,\n cache,\n });\n const db = new SqliteRemoteDatabase(\n \"async\",\n dialect,\n session,\n schema,\n ) as SqliteRemoteDatabase<TSchema>;\n (<any>db).$cache = cache;\n if ((<any>db).$cache) {\n (<any>db).$cache[\"invalidate\"] = cache?.onMutate;\n }\n return db;\n}\n"],"mappings":";;;;;;;;;;;;;AA0BA,MAAM,SAAS,iBACY,SAAwB,WAAoB;CACnE,MAAM,EAAE,UAAU,kBAAkB,aAAa,OAAO;CACxD,MAAM,WAAW,QAAQ,UAAU,eAAe,EAAE,OAAO,CAAC;CAC5D,OAAO;EACL;EACA;EACA,MAAM,YAAY;GAChB,MAAM,SAAS,IAAI,QAAQ;EAC7B;EACA,MAAM,QAAQ,CAAC;CACjB;AACF,CACF;AAkDA,eAAe,QAAQ,KAAmB,MAAmB,SAAwB;CAUnF,MAAM,OAAQ,OAAM,MATF,MAAM,KAAK;EAC3B,QAAQ;EACR,SAAS;GACP,eAAe,UAAU,QAAQ;GACjC,gBAAgB;EAClB;EACA,MAAM,KAAK,UAAU,IAAI;CAC3B,CAAC,EAAA,CAEuB,KAAK;CAE7B,IAAI,CAAC,KAAK,SACR,MAAM,IAAI,MAAM,KAAK,OAAO,KAAK,OAAO,GAAG,GAAG,KAAK,IAAI,GAAG,SAAS,CAAC,CAAC,KAAK,IAAI,CAAC;CAGjF,MAAM,SAAS,KAAK,OAAO,EAAE,CAAC;CAG9B,OAAO,EAAE,MAFI,MAAM,QAAQ,MAAM,IAAI,SAAS,OAAO,KAEvC;AAChB;;;;;;;AAQA,SAAgB,aAAa,SAAsC;CACjE,MAAM,MAAM,IAAI,IACd,YAAY,QAAQ,UAAU,eAAe,QAAQ,WAAW,OAChE,uCACF;CACA,OAAO;EACL,MAAM,SAAS,KAAK,QAAQ,GAAG;GAG7B,OAAO,MADW,QAAQ,KAAK;IADhB;IAAK;GACc,GAAG,OAAO;EAE9C;EACA,MAAM,cAAc,OAAO;GACzB,MAAM,OAAO,EACX,OAAO,MAAM,KAAK,EAAE,KAAK,aAAa;IACpC,OAAO;KACL;KACA;IACF;GACF,CAAC,EACH;GAEA,OAAO,CAAC,MADU,QAAQ,KAAK,MAAM,OAAO,CACjC;EACb;CACF;AACF;AAWA,SAAgB,QACd,UACA,eACA,QAC+B;CAC/B,MAAM,UAAU,IAAI,gBAAgB,EAAE,QAAQ,QAAQ,OAAO,CAAC;CAC9D,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,UAAkC,CAAC;CAEvC,IAAI,eAAe;EACjB,IAAI,OAAO,kBAAkB,YAAY;GACvC,iBAAiB;GACjB,UAAU,UAAU,CAAC;EACvB,OAAO;GACL,iBAAiB,KAAA;GACjB,UAAU;EACZ;EAEA,IAAI,QAAQ,WAAW,MACrB,SAAS,IAAI,cAAc;OACtB,IAAI,QAAQ,WAAW,OAAO;GACnC,SAAS,QAAQ;GACjB,QAAQ,QAAQ;EAClB;CACF;CAEA,IAAI;CACJ,IAAI,QAAQ,QAAQ;EAClB,MAAM,eAAe,8BAA8B,QAAQ,QAAQ,2BAA2B;EAC9F,SAAS;GACP,YAAY,QAAQ;GACpB,QAAQ,aAAa;GACrB,eAAe,aAAa;EAC9B;CACF;CAMA,MAAM,KAAK,IAAI,qBACb,SACA,SACA,IAPkB,oBAAoB,UAAU,SAAS,QAAQ,gBAAgB;EACjF;EACA;CACF,CAIQ,GACN,MACF;CACA,GAAU,SAAS;CACnB,IAAU,GAAI,QACZ,GAAU,OAAO,gBAAgB,OAAO;CAE1C,OAAO;AACT"}
|
package/dist/drivers/d1.d.mts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Schema } from "./index.mjs";
|
|
1
2
|
import { DrizzleD1Database } from "drizzle-orm/d1";
|
|
2
3
|
import { D1Database } from "@cloudflare/workers-types";
|
|
3
4
|
//#region src/drivers/d1.d.ts
|
|
@@ -8,7 +9,7 @@ import { D1Database } from "@cloudflare/workers-types";
|
|
|
8
9
|
* @param schema - The Drizzle schema
|
|
9
10
|
* @returns A Datasource instance
|
|
10
11
|
*/
|
|
11
|
-
declare const _default: <TSchema extends
|
|
12
|
+
declare const _default: <TSchema extends Schema>(options: D1Options, schema: TSchema) => Promise<{
|
|
12
13
|
database: DrizzleD1Database<TSchema> & {
|
|
13
14
|
$client: D1Database;
|
|
14
15
|
};
|
package/dist/drivers/d1.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { SQLiteD1Dialect } from "./
|
|
1
|
+
import { defineConnector } from "./index.mjs";
|
|
2
|
+
import { SQLiteD1Dialect } from "./d1/dialect.mjs";
|
|
3
3
|
import { SELECT_1 } from "./internal/sql.mjs";
|
|
4
4
|
import { DefaultLogger, createTableRelationsHelpers, extractTablesRelationalConfig } from "drizzle-orm";
|
|
5
5
|
import cloudflareD1Connector from "db0/connectors/cloudflare-d1";
|
|
@@ -12,7 +12,7 @@ import { DrizzleD1Database, SQLiteD1Session } from "drizzle-orm/d1";
|
|
|
12
12
|
* @param schema - The Drizzle schema
|
|
13
13
|
* @returns A Datasource instance
|
|
14
14
|
*/
|
|
15
|
-
var d1_default =
|
|
15
|
+
var d1_default = defineConnector(async (options, schema) => {
|
|
16
16
|
const database = drizzle(await cloudflareD1Connector({ bindingName: options.binding }).getInstance(), { schema });
|
|
17
17
|
return {
|
|
18
18
|
database,
|
package/dist/drivers/d1.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"d1.mjs","names":[],"sources":["../../src/drivers/d1.ts"],"sourcesContent":["import cloudflareD1Connector from \"db0/connectors/cloudflare-d1\";\nimport {
|
|
1
|
+
{"version":3,"file":"d1.mjs","names":[],"sources":["../../src/drivers/d1.ts"],"sourcesContent":["import cloudflareD1Connector from \"db0/connectors/cloudflare-d1\";\nimport { defineConnector, type Schema } from \".\";\nimport type { D1Database } from \"@cloudflare/workers-types\";\nimport type { DrizzleConfig, RelationalSchemaConfig, TablesRelationalConfig } from \"drizzle-orm\";\nimport {\n DefaultLogger,\n extractTablesRelationalConfig,\n createTableRelationsHelpers,\n} from \"drizzle-orm\";\nimport { DrizzleD1Database, SQLiteD1Session, type AnyD1Database } from \"drizzle-orm/d1\";\nimport { SQLiteD1Dialect } from \"./d1/dialect\";\nimport { SELECT_1 } from \"./internal/sql\";\n\n/**\n * Cloudflare D1 datasource driver.\n * @template TSchema - The schema type\n * @param options - Driver configuration options\n * @param schema - The Drizzle schema\n * @returns A Datasource instance\n */\nexport default defineConnector(\n async <TSchema extends Schema>(options: D1Options, schema: TSchema) => {\n const connector = cloudflareD1Connector({\n bindingName: options.binding,\n });\n const client = await connector.getInstance();\n const database = drizzle(client, { schema });\n return {\n database,\n schema,\n async waitReady() {\n await database.run(SELECT_1);\n },\n async close() {},\n };\n },\n);\n\n/** Configuration options for the Cloudflare D1 driver. */\nexport type D1Options = {\n /** The binding name for the D1 database in Cloudflare Workers. */\n binding: string;\n};\n\nfunction drizzle<\n TSchema extends Record<string, unknown> = Record<string, never>,\n TClient extends AnyD1Database = AnyD1Database,\n>(\n client: TClient,\n config: DrizzleConfig<TSchema> = {},\n): DrizzleD1Database<TSchema> & {\n $client: TClient;\n} {\n const dialect = new SQLiteD1Dialect({ casing: config.casing });\n let logger;\n if (config.logger === true) {\n logger = new DefaultLogger();\n } else if (config.logger !== false) {\n logger = config.logger;\n }\n\n let schema: RelationalSchemaConfig<TablesRelationalConfig> | undefined;\n if (config.schema) {\n const tablesConfig = extractTablesRelationalConfig(config.schema, createTableRelationsHelpers);\n schema = {\n fullSchema: config.schema,\n schema: tablesConfig.tables,\n tableNamesMap: tablesConfig.tableNamesMap,\n };\n }\n\n const session = new SQLiteD1Session(client as D1Database, dialect, schema, {\n logger,\n cache: config.cache,\n });\n const db = new DrizzleD1Database(\"async\", dialect, session, schema) as DrizzleD1Database<TSchema>;\n (<any>db).$client = client;\n (<any>db).$cache = config.cache;\n if ((<any>db).$cache) {\n (<any>db).$cache[\"invalidate\"] = config.cache?.onMutate;\n }\n\n return db as any;\n}\n"],"mappings":";;;;;;;;;;;;;;AAoBA,IAAA,aAAe,gBACb,OAA+B,SAAoB,WAAoB;CAKrE,MAAM,WAAW,QAAQ,MAJP,sBAAsB,EACtC,aAAa,QAAQ,QACvB,CAC6B,CAAC,CAAC,YAAY,GACV,EAAE,OAAO,CAAC;CAC3C,OAAO;EACL;EACA;EACA,MAAM,YAAY;GAChB,MAAM,SAAS,IAAI,QAAQ;EAC7B;EACA,MAAM,QAAQ,CAAC;CACjB;AACF,CACF;AAQA,SAAS,QAIP,QACA,SAAiC,CAAC,GAGlC;CACA,MAAM,UAAU,IAAI,gBAAgB,EAAE,QAAQ,OAAO,OAAO,CAAC;CAC7D,IAAI;CACJ,IAAI,OAAO,WAAW,MACpB,SAAS,IAAI,cAAc;MACtB,IAAI,OAAO,WAAW,OAC3B,SAAS,OAAO;CAGlB,IAAI;CACJ,IAAI,OAAO,QAAQ;EACjB,MAAM,eAAe,8BAA8B,OAAO,QAAQ,2BAA2B;EAC7F,SAAS;GACP,YAAY,OAAO;GACnB,QAAQ,aAAa;GACrB,eAAe,aAAa;EAC9B;CACF;CAMA,MAAM,KAAK,IAAI,kBAAkB,SAAS,SAAS,IAJ/B,gBAAgB,QAAsB,SAAS,QAAQ;EACzE;EACA,OAAO,OAAO;CAChB,CACyD,GAAG,MAAM;CAClE,GAAU,UAAU;CACpB,GAAU,SAAS,OAAO;CAC1B,IAAU,GAAI,QACZ,GAAU,OAAO,gBAAgB,OAAO,OAAO;CAGjD,OAAO;AACT"}
|
package/dist/drivers/db0.d.mts
CHANGED
|
@@ -6,12 +6,14 @@ import { Schema } from "./index.mjs";
|
|
|
6
6
|
* @returns A Datasource instance using Nitro's database configuration
|
|
7
7
|
*/
|
|
8
8
|
declare const _default: <TSchema extends Schema>(options: Options, schema: TSchema) => {
|
|
9
|
+
dialect: string;
|
|
9
10
|
database: import("db0/integrations/drizzle").DrizzleDatabase<TSchema>;
|
|
10
11
|
schema: TSchema;
|
|
11
12
|
close: () => Promise<void>;
|
|
12
13
|
waitReady: () => Promise<void>;
|
|
13
14
|
};
|
|
14
15
|
type Options = {
|
|
16
|
+
/** The name of the database to use from Nitro's built-in database configuration. */
|
|
15
17
|
name?: string;
|
|
16
18
|
};
|
|
17
19
|
//#endregion
|
package/dist/drivers/db0.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { defineConnector } from "./index.mjs";
|
|
2
2
|
import { SELECT_1 } from "./internal/sql.mjs";
|
|
3
3
|
import { useDatabase } from "nitropack/runtime";
|
|
4
4
|
import { drizzle } from "db0/integrations/drizzle";
|
|
@@ -8,9 +8,10 @@ import { drizzle } from "db0/integrations/drizzle";
|
|
|
8
8
|
* @template TSchema - The schema type
|
|
9
9
|
* @returns A Datasource instance using Nitro's database configuration
|
|
10
10
|
*/
|
|
11
|
-
var db0_default =
|
|
11
|
+
var db0_default = defineConnector((options, schema) => {
|
|
12
12
|
const db0 = useDatabase(options.name);
|
|
13
13
|
return {
|
|
14
|
+
dialect: "sqlite",
|
|
14
15
|
database: drizzle(db0),
|
|
15
16
|
schema,
|
|
16
17
|
close: async () => {
|
package/dist/drivers/db0.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"db0.mjs","names":[],"sources":["../../src/drivers/db0.ts"],"sourcesContent":["import { useDatabase } from \"nitropack/runtime\";\nimport {
|
|
1
|
+
{"version":3,"file":"db0.mjs","names":[],"sources":["../../src/drivers/db0.ts"],"sourcesContent":["import { useDatabase } from \"nitropack/runtime\";\nimport { defineConnector, type Schema } from \".\";\nimport { drizzle } from \"db0/integrations/drizzle\";\nimport { SELECT_1 } from \"./internal/sql\";\n\n/**\n * DB0 datasource driver for Nitro's built-in database configuration.\n * @template TSchema - The schema type\n * @returns A Datasource instance using Nitro's database configuration\n */\nexport default defineConnector(<TSchema extends Schema>(options: Options, schema: TSchema) => {\n const db0 = useDatabase(options.name);\n const database = drizzle<TSchema>(db0);\n return {\n dialect: \"sqlite\",\n database,\n schema,\n close: async () => {\n await db0.dispose();\n },\n waitReady: async () => {\n await db0.exec(SELECT_1);\n },\n };\n});\n\nexport type Options = {\n /** The name of the database to use from Nitro's built-in database configuration. */\n name?: string;\n};\n"],"mappings":";;;;;;;;;;AAUA,IAAA,cAAe,iBAAyC,SAAkB,WAAoB;CAC5F,MAAM,MAAM,YAAY,QAAQ,IAAI;CAEpC,OAAO;EACL,SAAS;EACT,UAHe,QAAiB,GAGzB;EACP;EACA,OAAO,YAAY;GACjB,MAAM,IAAI,QAAQ;EACpB;EACA,WAAW,YAAY;GACrB,MAAM,IAAI,KAAK,QAAQ;EACzB;CACF;AACF,CAAC"}
|