nitro-drizzle 0.3.0-beta.2 → 0.3.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/context/internal/config.mjs +3 -4
- package/dist/context/internal/config.mjs.map +1 -1
- package/dist/context/internal/templates.mjs +82 -29
- package/dist/context/internal/templates.mjs.map +1 -1
- package/dist/context/internal/virtual.mjs +45 -26
- package/dist/context/internal/virtual.mjs.map +1 -1
- package/dist/context.d.mts +18 -15
- package/dist/context.mjs +57 -15
- package/dist/context.mjs.map +1 -1
- package/dist/drivers/{internal/d1-dialect.mjs → d1/dialect.mjs} +2 -2
- package/dist/drivers/d1/dialect.mjs.map +1 -0
- 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 +1 -0
- package/dist/drivers/db0.mjs +3 -2
- package/dist/drivers/db0.mjs.map +1 -1
- package/dist/drivers/index.d.mts +9 -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/migrations/migrate.mjs +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/utils/assets.mjs +2 -0
- package/dist/module/utils/assets.mjs.map +1 -1
- package/dist/module.d.mts +7 -2
- package/dist/module.mjs +9 -0
- 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 +7 -6
- package/dist/runtime/internal/config.mjs.map +1 -1
- package/dist/runtime/internal/createDatasource.mjs +15 -5
- package/dist/runtime/internal/createDatasource.mjs.map +1 -1
- package/dist/runtime/useConfig.d.mts +9 -0
- package/dist/runtime/useConfig.mjs +16 -0
- package/dist/runtime/useConfig.mjs.map +1 -0
- package/dist/runtime/useDatasource.d.mts +2 -1
- package/dist/runtime/useDatasource.mjs.map +1 -1
- package/dist/runtime/useDialect.d.mts +14 -0
- package/dist/runtime/useDialect.mjs +12 -0
- package/dist/runtime/useDialect.mjs.map +1 -0
- package/dist/runtime.d.mts +32 -26
- package/dist/runtime.mjs +3 -1
- package/dist/shared/variants.d.mts +18 -0
- package/dist/shared/variants.mjs +12 -0
- package/dist/shared/variants.mjs.map +1 -0
- package/dist/shared.d.mts +8 -3
- package/dist/shared.mjs +2 -1
- package/package.json +4 -4
- package/dist/drivers/internal/d1-dialect.mjs.map +0 -1
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,MAAM,cAAc,MAAM,KAAK,YAAY;EAE3C,MAAM,KAAKA,SAAS,QAAQ,KAAK,eAAe,CAAC;EAEjD,MAAM,CAAC,gBAAgB,cAAc,aAAa,gBAAgB,MAAM,QAAQ,IAAI;GAClF,KAAK,eAAe,WAAW;GAC/B,KAAK,wBAAwB,WAAW;GACxC,KAAK,uBAAuB,WAAW;GACvC,KAAK,wBAAwB,WAAW;EAC1C,CAAC;EAED,MAAM,KAAKA,SAAS,eAAe,cAAc;EAEjD,MAAM,KAAKA,SAAS,aAAa;GAC/B,SAAS;GACT,QAAQ;GACR,SAAS;EACX,CAAC;EAED,IAAI,KAAKA,SAAS,YAAY;GAC5B,MAAM,SAAS,MAAM,KAAK,gBAAgB,WAAW;GACrD,IAAI,QACF,MAAM,KAAKA,SAAS,OAAO,MAAM;GAGnC,MAAM,KAAKA,SAAS,QAAQ,EAC1B,mBAAmB;IACjB,aAAa;IACb,SAAS;GACX,EACF,CAAC;EACH;EAEA,IAAI,KAAKA,SAAS,WAAW;GAC3B,MAAM,kBAAkB;IAAC;IAAW;IAAW;GAAY,CAAC,CAAC,SAAS,OAAO;IAC3E,OAAO,CAAC,KAAK,SAAS,EAAE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AuB,WAAW;CAC3C;CAEA,MAAc,wBACZ,aAC2C;EAC3C,MAAM,6BAAa,IAAI,IAAI,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;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 genReference,\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\";\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 return {\n name,\n enabled: true,\n drivers: options.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[] }>;\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 drivers: readonly DriverOptions[];\n}\n\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,MA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AK,eAAe,yBAAyB,YAAY;EAE/E,OAAO;CACT;CAEA,MAAc,uBACZ,aACyB;EACzB,OAAO,uBAAuB,WAAW;CAC3C;CAEA,MAAc,wBACZ,aAC2C;EAC3C,MAAM,6BAAa,IAAI,IAAI,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"}
|
|
@@ -1,7 +1,7 @@
|
|
|
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
|
* Dialect for Cloudflare D1 with batching instead of transaction for migrations.
|
|
7
7
|
* @see [Cloudflare D1 transaction not supported #2463](https://github.com/drizzle-team/drizzle-orm/issues/2463)
|
|
@@ -38,4 +38,4 @@ function createBatchItem({ session, dialect, sql }) {
|
|
|
38
38
|
//#endregion
|
|
39
39
|
export { SQLiteD1Dialect };
|
|
40
40
|
|
|
41
|
-
//# sourceMappingURL=
|
|
41
|
+
//# 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 * Dialect for Cloudflare D1 with batching instead of transaction for migrations.\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":";;;;;;;;AAWA,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"}
|
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. */\ntype 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. */\ntype 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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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,6 +6,7 @@ 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>;
|
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 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"}
|
package/dist/drivers/index.d.mts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { MaybePromise, UnionToIntersection } from "nitro-drizzle/shared";
|
|
1
2
|
//#region src/drivers/index.d.ts
|
|
2
3
|
/**
|
|
3
4
|
* Schema type representing database tables.
|
|
@@ -7,29 +8,30 @@ type Schema = Record<string, any>;
|
|
|
7
8
|
* Factory function type for creating Drizzle datasource instances.
|
|
8
9
|
* @template TDatabase - The database type
|
|
9
10
|
*/
|
|
10
|
-
type
|
|
11
|
+
type Connector<TDialect extends string, TDatabase, TSchema extends Schema, TConfig, TDatasource extends Datasource<TDialect, TDatabase, TSchema> = Datasource<TDialect, TDatabase, TSchema>> = (config: TConfig, schema: TSchema) => MaybePromise<TDatasource>;
|
|
12
|
+
type MergeSchema<T extends readonly Schema[], Indices extends keyof T & number> = [Indices] extends [never] ? {} : UnionToIntersection<{ [K in Indices]: K extends keyof T ? T[K] : never; }[Indices]>;
|
|
11
13
|
/**
|
|
12
14
|
* Defines a driver factory function.
|
|
13
|
-
* @template
|
|
15
|
+
* @template TConnector - The driver factory type
|
|
14
16
|
* @param create - The driver factory function
|
|
15
17
|
* @returns The same driver factory function
|
|
16
18
|
*/
|
|
17
|
-
declare function
|
|
19
|
+
declare function defineConnector<TDialect extends string, TSchema extends Schema, TConnector extends Connector<TDialect, any, TSchema, any>>(create: TConnector): TConnector;
|
|
18
20
|
/**
|
|
19
21
|
* Datasource interface representing a connected database with schema.
|
|
20
22
|
* @template TDatabase - The database client type
|
|
21
23
|
* @template TSchema - The schema type
|
|
22
24
|
*/
|
|
23
|
-
interface Datasource<TDatabase, TSchema extends Schema> {
|
|
25
|
+
interface Datasource<_TDialect, TDatabase, TSchema extends Schema> {
|
|
24
26
|
/** The database client instance. */
|
|
25
27
|
database: TDatabase;
|
|
26
28
|
/** The schema definition. */
|
|
27
29
|
schema: TSchema;
|
|
28
30
|
/** Waits for the database connection to be ready. */
|
|
29
|
-
waitReady: () =>
|
|
31
|
+
waitReady: () => MaybePromise<void>;
|
|
30
32
|
/** Closes the database connection. */
|
|
31
|
-
close: () =>
|
|
33
|
+
close: () => MaybePromise<void>;
|
|
32
34
|
}
|
|
33
35
|
//#endregion
|
|
34
|
-
export { Datasource,
|
|
36
|
+
export { Connector, Datasource, MergeSchema, Schema, defineConnector };
|
|
35
37
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/drivers/index.mjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
//#region src/drivers/index.ts
|
|
2
2
|
/**
|
|
3
3
|
* Defines a driver factory function.
|
|
4
|
-
* @template
|
|
4
|
+
* @template TConnector - The driver factory type
|
|
5
5
|
* @param create - The driver factory function
|
|
6
6
|
* @returns The same driver factory function
|
|
7
7
|
*/
|
|
8
|
-
function
|
|
8
|
+
function defineConnector(create) {
|
|
9
9
|
return create;
|
|
10
10
|
}
|
|
11
11
|
//#endregion
|
|
12
|
-
export {
|
|
12
|
+
export { defineConnector };
|
|
13
13
|
|
|
14
14
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/drivers/index.ts"],"sourcesContent":["/**\n * Schema type representing database tables.\n */\nexport type Schema = Record<string, any>;\n\n/**\n * Factory function type for creating Drizzle datasource instances.\n * @template TDatabase - The database type\n */\nexport type
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/drivers/index.ts"],"sourcesContent":["import type { MaybePromise, UnionToIntersection } from \"nitro-drizzle/shared\";\n\n/**\n * Schema type representing database tables.\n */\nexport type Schema = Record<string, any>;\n\n/**\n * Factory function type for creating Drizzle datasource instances.\n * @template TDatabase - The database type\n */\nexport type Connector<\n TDialect extends string,\n TDatabase,\n TSchema extends Schema,\n TConfig,\n TDatasource extends Datasource<TDialect, TDatabase, TSchema> = Datasource<\n TDialect,\n TDatabase,\n TSchema\n >,\n> = (config: TConfig, schema: TSchema) => MaybePromise<TDatasource>;\n\nexport type MergeSchema<T extends readonly Schema[], Indices extends keyof T & number> = [\n Indices,\n] extends [never]\n ? {}\n : UnionToIntersection<\n {\n [K in Indices]: K extends keyof T ? T[K] : never;\n }[Indices]\n >;\n\n/**\n * Defines a driver factory function.\n * @template TConnector - The driver factory type\n * @param create - The driver factory function\n * @returns The same driver factory function\n */\nexport function defineConnector<\n TDialect extends string,\n TSchema extends Schema,\n TConnector extends Connector<TDialect, any, TSchema, any>,\n>(create: TConnector): TConnector {\n return create;\n}\n\n/**\n * Datasource interface representing a connected database with schema.\n * @template TDatabase - The database client type\n * @template TSchema - The schema type\n */\nexport interface Datasource<_TDialect, TDatabase, TSchema extends Schema> {\n /** The database client instance. */\n database: TDatabase;\n /** The schema definition. */\n schema: TSchema;\n /** Waits for the database connection to be ready. */\n waitReady: () => MaybePromise<void>;\n /** Closes the database connection. */\n close: () => MaybePromise<void>;\n}\n"],"mappings":";;;;;;;AAuCA,SAAgB,gBAId,QAAgC;CAChC,OAAO;AACT"}
|
package/dist/drivers/mysql.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 { drizzle } from "drizzle-orm/mysql2";
|
|
4
4
|
import { createConnection } from "mysql2/promise";
|
|
@@ -10,7 +10,7 @@ import { createConnection } from "mysql2/promise";
|
|
|
10
10
|
* @param schema - The Drizzle schema
|
|
11
11
|
* @returns A Datasource instance
|
|
12
12
|
*/
|
|
13
|
-
var mysql_default =
|
|
13
|
+
var mysql_default = defineConnector(async (config, schema) => {
|
|
14
14
|
const database = drizzle(await createConnection(config.url), {
|
|
15
15
|
schema,
|
|
16
16
|
mode: "default"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mysql.mjs","names":[],"sources":["../../src/drivers/mysql.ts"],"sourcesContent":["import { drizzle } from \"drizzle-orm/mysql2\";\nimport { createConnection } from \"mysql2/promise\";\nimport {
|
|
1
|
+
{"version":3,"file":"mysql.mjs","names":[],"sources":["../../src/drivers/mysql.ts"],"sourcesContent":["import { drizzle } from \"drizzle-orm/mysql2\";\nimport { createConnection } from \"mysql2/promise\";\nimport { defineConnector, type Schema } from \".\";\nimport { SELECT_1 } from \"./internal/sql\";\n\n/**\n * MySQL datasource driver using mysql2.\n * @template TSchema - The schema type\n * @param config - Driver configuration options\n * @param schema - The Drizzle schema\n * @returns A Datasource instance\n */\nexport default defineConnector(async <TSchema extends Schema>(config: Options, schema: TSchema) => {\n const connection = await createConnection(config.url);\n const database = drizzle(connection, { schema, mode: \"default\" });\n return {\n database,\n schema,\n waitReady: async () => {\n await database.execute(SELECT_1);\n },\n close: async () => {\n await database.$client.end();\n },\n };\n});\n\n/**\n * Configuration options for the MySQL driver.\n */\nexport type Options = {\n /** Database connection URL. */\n url: string;\n};\n"],"mappings":";;;;;;;;;;;;AAYA,IAAA,gBAAe,gBAAgB,OAA+B,QAAiB,WAAoB;CAEjG,MAAM,WAAW,QAAQ,MADA,iBAAiB,OAAO,GAAG,GACf;EAAE;EAAQ,MAAM;CAAU,CAAC;CAChE,OAAO;EACL;EACA;EACA,WAAW,YAAY;GACrB,MAAM,SAAS,QAAQ,QAAQ;EACjC;EACA,OAAO,YAAY;GACjB,MAAM,SAAS,QAAQ,IAAI;EAC7B;CACF;AACF,CAAC"}
|
|
@@ -9,6 +9,7 @@ import { PGlite, PGliteOptions } from "@electric-sql/pglite";
|
|
|
9
9
|
* @returns A Datasource instance
|
|
10
10
|
*/
|
|
11
11
|
declare const _default: <TSchema extends Schema>(options: PGliteOptions, schema: TSchema) => {
|
|
12
|
+
dialect: string;
|
|
12
13
|
database: import("drizzle-orm/pglite").PgliteDatabase<TSchema> & {
|
|
13
14
|
$client: PGlite;
|
|
14
15
|
};
|
package/dist/drivers/pglite.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { defineConnector } from "./index.mjs";
|
|
2
2
|
import { drizzle } from "drizzle-orm/pglite";
|
|
3
3
|
import { PGlite } from "@electric-sql/pglite";
|
|
4
4
|
//#region src/drivers/pglite.ts
|
|
@@ -9,9 +9,10 @@ import { PGlite } from "@electric-sql/pglite";
|
|
|
9
9
|
* @param schema - The Drizzle schema
|
|
10
10
|
* @returns A Datasource instance
|
|
11
11
|
*/
|
|
12
|
-
var pglite_default =
|
|
12
|
+
var pglite_default = defineConnector((options, schema) => {
|
|
13
13
|
const database = drizzle(new PGlite(options), { schema });
|
|
14
14
|
return {
|
|
15
|
+
dialect: "postgresql",
|
|
15
16
|
database,
|
|
16
17
|
schema,
|
|
17
18
|
async waitReady() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pglite.mjs","names":[],"sources":["../../src/drivers/pglite.ts"],"sourcesContent":["import { drizzle } from \"drizzle-orm/pglite\";\nimport { PGlite, type PGliteOptions } from \"@electric-sql/pglite\";\nimport {
|
|
1
|
+
{"version":3,"file":"pglite.mjs","names":[],"sources":["../../src/drivers/pglite.ts"],"sourcesContent":["import { drizzle } from \"drizzle-orm/pglite\";\nimport { PGlite, type PGliteOptions } from \"@electric-sql/pglite\";\nimport { defineConnector, type Schema } from \".\";\n\n/**\n * PGlite datasource driver for PostgreSQL in the browser.\n * @template TSchema - The schema type\n * @param options - PGlite configuration options\n * @param schema - The Drizzle schema\n * @returns A Datasource instance\n */\nexport default defineConnector(\n <TSchema extends Schema>(options: PGliteOptions, schema: TSchema) => {\n const driver = new PGlite(options);\n const database = drizzle(driver, { schema });\n return {\n dialect: \"postgresql\",\n database,\n schema,\n async waitReady() {\n await database.$client.waitReady;\n },\n async close() {\n await database.$client.close();\n },\n };\n },\n);\n"],"mappings":";;;;;;;;;;;AAWA,IAAA,iBAAe,iBACY,SAAwB,WAAoB;CAEnE,MAAM,WAAW,QAAQ,IADN,OAAO,OACI,GAAG,EAAE,OAAO,CAAC;CAC3C,OAAO;EACL,SAAS;EACT;EACA;EACA,MAAM,YAAY;GAChB,MAAM,SAAS,QAAQ;EACzB;EACA,MAAM,QAAQ;GACZ,MAAM,SAAS,QAAQ,MAAM;EAC/B;CACF;AACF,CACF"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Schema } from "./index.mjs";
|
|
1
2
|
import createPostgres, { Options as Options$1 } from "postgres";
|
|
2
3
|
//#region src/drivers/postgresql.d.ts
|
|
3
4
|
/**
|
|
@@ -7,7 +8,7 @@ import createPostgres, { Options as Options$1 } from "postgres";
|
|
|
7
8
|
* @param schema - The Drizzle schema
|
|
8
9
|
* @returns A Datasource instance
|
|
9
10
|
*/
|
|
10
|
-
declare const _default: <TSchema extends
|
|
11
|
+
declare const _default: <TSchema extends Schema>(options: Options, schema: TSchema) => {
|
|
11
12
|
database: import("drizzle-orm/postgres-js").PostgresJsDatabase<TSchema> & {
|
|
12
13
|
$client: createPostgres.Sql<{}>;
|
|
13
14
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { defineConnector } from "./index.mjs";
|
|
2
2
|
import { SELECT_1 } from "./internal/sql.mjs";
|
|
3
3
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
4
4
|
import createPostgres from "postgres";
|
|
@@ -10,7 +10,7 @@ import createPostgres from "postgres";
|
|
|
10
10
|
* @param schema - The Drizzle schema
|
|
11
11
|
* @returns A Datasource instance
|
|
12
12
|
*/
|
|
13
|
-
var postgresql_default =
|
|
13
|
+
var postgresql_default = defineConnector((options, schema) => {
|
|
14
14
|
const { url, ...other } = options;
|
|
15
15
|
const database = drizzle(url ? createPostgres(url, other) : createPostgres(other), { schema });
|
|
16
16
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgresql.mjs","names":[],"sources":["../../src/drivers/postgresql.ts"],"sourcesContent":["import { drizzle } from \"drizzle-orm/postgres-js\";\nimport createPostgres, { type Options as PostgresOptions } from \"postgres\";\nimport {
|
|
1
|
+
{"version":3,"file":"postgresql.mjs","names":[],"sources":["../../src/drivers/postgresql.ts"],"sourcesContent":["import { drizzle } from \"drizzle-orm/postgres-js\";\nimport createPostgres, { type Options as PostgresOptions } from \"postgres\";\nimport { defineConnector, type Schema } from \".\";\nimport { SELECT_1 } from \"./internal/sql\";\n\n/**\n * PostgreSQL datasource driver using postgres.js.\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(<TSchema extends Schema>(options: Options, schema: TSchema) => {\n const { url, ...other } = options;\n const client = url ? createPostgres(url, other) : createPostgres(other);\n const database = drizzle(client, { schema });\n return {\n database,\n schema,\n async waitReady() {\n await database.execute(SELECT_1);\n },\n async close() {\n await database.$client.end();\n },\n };\n});\n\n/**\n * Configuration options for the PostgreSQL driver.\n */\nexport type Options = PostgresOptions<Record<string, createPostgres.PostgresType>> & {\n /** Connection URL string (optional if connection config is provided). */\n url?: string;\n};\n"],"mappings":";;;;;;;;;;;;AAYA,IAAA,qBAAe,iBAAyC,SAAkB,WAAoB;CAC5F,MAAM,EAAE,KAAK,GAAG,UAAU;CAE1B,MAAM,WAAW,QADF,MAAM,eAAe,KAAK,KAAK,IAAI,eAAe,KAAK,GACrC,EAAE,OAAO,CAAC;CAC3C,OAAO;EACL;EACA;EACA,MAAM,YAAY;GAChB,MAAM,SAAS,QAAQ,QAAQ;EACjC;EACA,MAAM,QAAQ;GACZ,MAAM,SAAS,QAAQ,IAAI;EAC7B;CACF;AACF,CAAC"}
|
package/dist/drivers/sqlite.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 sqlite3 from "better-sqlite3";
|
|
4
4
|
import { drizzle } from "drizzle-orm/better-sqlite3";
|
|
@@ -10,7 +10,7 @@ import { drizzle } from "drizzle-orm/better-sqlite3";
|
|
|
10
10
|
* @param schema - The Drizzle schema
|
|
11
11
|
* @returns A Datasource instance
|
|
12
12
|
*/
|
|
13
|
-
var sqlite_default =
|
|
13
|
+
var sqlite_default = defineConnector((config, schema) => {
|
|
14
14
|
const { url, ...options } = config;
|
|
15
15
|
const database = drizzle(sqlite3(url, options), { schema });
|
|
16
16
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite.mjs","names":[],"sources":["../../src/drivers/sqlite.ts"],"sourcesContent":["import sqlite3, { type Options as BetterSqlite3Options } from \"better-sqlite3\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport {
|
|
1
|
+
{"version":3,"file":"sqlite.mjs","names":[],"sources":["../../src/drivers/sqlite.ts"],"sourcesContent":["import sqlite3, { type Options as BetterSqlite3Options } from \"better-sqlite3\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { defineConnector, type Schema } from \".\";\nimport { SELECT_1 } from \"./internal/sql\";\n\n/**\n * SQLite datasource driver using better-sqlite3.\n * @template TSchema - The schema type\n * @param config - Driver configuration options\n * @param schema - The Drizzle schema\n * @returns A Datasource instance\n */\nexport default defineConnector(<TSchema extends Schema>(config: Options, schema: TSchema) => {\n const { url, ...options } = config;\n const sqlite = sqlite3(url, options);\n const database = drizzle(sqlite, { schema });\n return {\n database,\n schema,\n async waitReady() {\n if (!database.$client.open) {\n database.run(SELECT_1);\n }\n },\n async close() {\n database.$client.close();\n },\n };\n});\n\n/**\n * Configuration options for the SQLite driver.\n */\nexport type Options = {\n /** Database file path or URL. */\n url: string;\n} & BetterSqlite3Options;\n"],"mappings":";;;;;;;;;;;;AAYA,IAAA,iBAAe,iBAAyC,QAAiB,WAAoB;CAC3F,MAAM,EAAE,KAAK,GAAG,YAAY;CAE5B,MAAM,WAAW,QADF,QAAQ,KAAK,OACE,GAAG,EAAE,OAAO,CAAC;CAC3C,OAAO;EACL;EACA;EACA,MAAM,YAAY;GAChB,IAAI,CAAC,SAAS,QAAQ,MACpB,SAAS,IAAI,QAAQ;EAEzB;EACA,MAAM,QAAQ;GACZ,SAAS,QAAQ,MAAM;EACzB;CACF;AACF,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useMigrations } from "./useMigrations.mjs";
|
|
2
2
|
import { migrateDatabase } from "./internal/migrate.mjs";
|
|
3
|
-
import { migrationConfig } from "#nitro-drizzle/migrations";
|
|
4
3
|
import { useDatasource } from "nitro-drizzle/runtime";
|
|
4
|
+
import { migrationConfig } from "#nitro-drizzle/migrations";
|
|
5
5
|
//#region src/migrations/migrate.ts
|
|
6
6
|
/**
|
|
7
7
|
* Runs migrations for a specific datasource.
|
|
@@ -8,7 +8,7 @@ import { Storage } from "unstorage";
|
|
|
8
8
|
* @param name - The datasource name
|
|
9
9
|
* @returns Storage instance for migrations
|
|
10
10
|
*/
|
|
11
|
-
declare function useMigrationsStorage<TName extends keyof DatasourceRegistry>(name: TName): Storage<string>;
|
|
11
|
+
declare function useMigrationsStorage<TName extends keyof DatasourceRegistry & string>(name: TName): Storage<string>;
|
|
12
12
|
/** Storage key for the migration journal. */
|
|
13
13
|
declare const JOURNAL_STORAGE_KEY: "meta/_journal.json";
|
|
14
14
|
/**
|
|
@@ -18,7 +18,7 @@ declare const JOURNAL_STORAGE_KEY: "meta/_journal.json";
|
|
|
18
18
|
* @returns Async iterable of migrations
|
|
19
19
|
* @throws If migration journal is not found
|
|
20
20
|
*/
|
|
21
|
-
declare function useMigrations<TName extends keyof DatasourceRegistry>(name: TName): Promise<AsyncIterable<Migration>>;
|
|
21
|
+
declare function useMigrations<TName extends keyof DatasourceRegistry & string>(name: TName): Promise<AsyncIterable<Migration>>;
|
|
22
22
|
/** Single entry in the migration journal. */
|
|
23
23
|
interface MigrationJournalItem {
|
|
24
24
|
/** Migration index/order number. */
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { useStorage } from "#nitro-drizzle/runtime";
|
|
2
|
+
import { useConfig } from "nitro-drizzle/runtime";
|
|
2
3
|
import { digest } from "ohash";
|
|
3
4
|
import { MIGRATIONS_STORAGE_BASE } from "#nitro-drizzle/migrations";
|
|
4
5
|
//#region src/migrations/useMigrations.ts
|
|
@@ -9,7 +10,8 @@ import { MIGRATIONS_STORAGE_BASE } from "#nitro-drizzle/migrations";
|
|
|
9
10
|
* @returns Storage instance for migrations
|
|
10
11
|
*/
|
|
11
12
|
function useMigrationsStorage(name) {
|
|
12
|
-
|
|
13
|
+
const { driver } = useConfig(name);
|
|
14
|
+
return useStorage(`assets:${MIGRATIONS_STORAGE_BASE}:${name}:${driver}`);
|
|
13
15
|
}
|
|
14
16
|
/** Storage key for the migration journal. */
|
|
15
17
|
const JOURNAL_STORAGE_KEY = "meta/_journal.json";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useMigrations.mjs","names":[],"sources":["../../src/migrations/useMigrations.ts"],"sourcesContent":["import type { Storage } from \"unstorage\";\nimport { digest } from \"ohash\";\nimport type { DatasourceRegistry } from \"nitro-drizzle/runtime\";\nimport { MIGRATIONS_STORAGE_BASE } from \"#nitro-drizzle/migrations\";\nimport { useStorage } from \"#nitro-drizzle/runtime\";\nimport type { Migration } from \"./internal/migrate\";\n\n/**\n * Gets the storage for a specific datasource's migrations.\n * @template TName - The datasource name\n * @param name - The datasource name\n * @returns Storage instance for migrations\n */\nexport function useMigrationsStorage<TName extends keyof DatasourceRegistry>(\n name: TName,\n): Storage<string> {\n return useStorage(`assets:${MIGRATIONS_STORAGE_BASE}:${name}`);\n}\n\n/** Storage key for the migration journal. */\nexport const JOURNAL_STORAGE_KEY = \"meta/_journal.json\" as const;\n\n/**\n * Gets an async iterable of migrations for a specific datasource.\n * @template TName - The datasource name\n * @param name - The datasource name\n * @returns Async iterable of migrations\n * @throws If migration journal is not found\n */\nexport async function useMigrations<TName extends keyof DatasourceRegistry>(\n name: TName,\n): Promise<AsyncIterable<Migration>> {\n const storage = useMigrationsStorage(name);\n const journal = await storage.getItem<MigrationJournal>(JOURNAL_STORAGE_KEY);\n if (!journal) {\n throw new Error(`Cannot find migration journal for '${name}'`);\n }\n\n return generate(journal, storage);\n}\n\nconst STATEMENT_BREAKPOINT = \"--> statement-breakpoint\" as const;\n\nasync function* generate(journal: MigrationJournal, storage: Storage<string>) {\n for (const { idx, when, tag, breakpoints } of journal.entries) {\n const filename = tag + \".sql\";\n const query = await storage.getItem<string>(filename);\n\n if (!query) {\n throw new Error(`Cannot find migration filename: ${filename}`);\n }\n\n const migration: Migration = {\n filename,\n idx,\n sql: query.split(STATEMENT_BREAKPOINT),\n hash: digest(query),\n folderMillis: when,\n bps: breakpoints,\n };\n\n yield migration;\n }\n}\n\n/** Single entry in the migration journal. */\nexport interface MigrationJournalItem {\n /** Migration index/order number. */\n idx: number;\n /** Migration version string. */\n version: string;\n /** Timestamp when migration was created. */\n when: number;\n /** Migration tag/identifier. */\n tag: string;\n /** Indicates if this entry has breakpoints. */\n breakpoints: true;\n}\n\n/**\n * Migration journal containing all migration entries.\n * @see https://github.com/drizzle-team/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/utils.ts#L63\n */\nexport interface MigrationJournal {\n /** List of migration entries. */\n entries: Iterable<MigrationJournalItem>;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useMigrations.mjs","names":[],"sources":["../../src/migrations/useMigrations.ts"],"sourcesContent":["import type { Storage } from \"unstorage\";\nimport { digest } from \"ohash\";\nimport type { DatasourceRegistry } from \"nitro-drizzle/runtime\";\nimport { MIGRATIONS_STORAGE_BASE } from \"#nitro-drizzle/migrations\";\nimport { useStorage } from \"#nitro-drizzle/runtime\";\nimport type { Migration } from \"./internal/migrate\";\nimport { useConfig } from \"nitro-drizzle/runtime\";\n\n/**\n * Gets the storage for a specific datasource's migrations.\n * @template TName - The datasource name\n * @param name - The datasource name\n * @returns Storage instance for migrations\n */\nexport function useMigrationsStorage<TName extends keyof DatasourceRegistry & string>(\n name: TName,\n): Storage<string> {\n const { driver } = useConfig(name);\n return useStorage(`assets:${MIGRATIONS_STORAGE_BASE}:${name}:${driver}`);\n}\n\n/** Storage key for the migration journal. */\nexport const JOURNAL_STORAGE_KEY = \"meta/_journal.json\" as const;\n\n/**\n * Gets an async iterable of migrations for a specific datasource.\n * @template TName - The datasource name\n * @param name - The datasource name\n * @returns Async iterable of migrations\n * @throws If migration journal is not found\n */\nexport async function useMigrations<TName extends keyof DatasourceRegistry & string>(\n name: TName,\n): Promise<AsyncIterable<Migration>> {\n const storage = useMigrationsStorage(name);\n const journal = await storage.getItem<MigrationJournal>(JOURNAL_STORAGE_KEY);\n if (!journal) {\n throw new Error(`Cannot find migration journal for '${name}'`);\n }\n\n return generate(journal, storage);\n}\n\nconst STATEMENT_BREAKPOINT = \"--> statement-breakpoint\" as const;\n\nasync function* generate(journal: MigrationJournal, storage: Storage<string>) {\n for (const { idx, when, tag, breakpoints } of journal.entries) {\n const filename = tag + \".sql\";\n const query = await storage.getItem<string>(filename);\n\n if (!query) {\n throw new Error(`Cannot find migration filename: ${filename}`);\n }\n\n const migration: Migration = {\n filename,\n idx,\n sql: query.split(STATEMENT_BREAKPOINT),\n hash: digest(query),\n folderMillis: when,\n bps: breakpoints,\n };\n\n yield migration;\n }\n}\n\n/** Single entry in the migration journal. */\nexport interface MigrationJournalItem {\n /** Migration index/order number. */\n idx: number;\n /** Migration version string. */\n version: string;\n /** Timestamp when migration was created. */\n when: number;\n /** Migration tag/identifier. */\n tag: string;\n /** Indicates if this entry has breakpoints. */\n breakpoints: true;\n}\n\n/**\n * Migration journal containing all migration entries.\n * @see https://github.com/drizzle-team/drizzle-orm/blob/48e5406027103a9fca6eb66417187c4a8b5c6aa3/drizzle-kit/src/utils.ts#L63\n */\nexport interface MigrationJournal {\n /** List of migration entries. */\n entries: Iterable<MigrationJournalItem>;\n}\n"],"mappings":";;;;;;;;;;;AAcA,SAAgB,qBACd,MACiB;CACjB,MAAM,EAAE,WAAW,UAAU,IAAI;CACjC,OAAO,WAAW,UAAU,wBAAwB,GAAG,KAAK,GAAG,QAAQ;AACzE;;AAGA,MAAa,sBAAsB;;;;;;;;AASnC,eAAsB,cACpB,MACmC;CACnC,MAAM,UAAU,qBAAqB,IAAI;CACzC,MAAM,UAAU,MAAM,QAAQ,QAA0B,mBAAmB;CAC3E,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,sCAAsC,KAAK,EAAE;CAG/D,OAAO,SAAS,SAAS,OAAO;AAClC;AAEA,MAAM,uBAAuB;AAE7B,gBAAgB,SAAS,SAA2B,SAA0B;CAC5E,KAAK,MAAM,EAAE,KAAK,MAAM,KAAK,iBAAiB,QAAQ,SAAS;EAC7D,MAAM,WAAW,MAAM;EACvB,MAAM,QAAQ,MAAM,QAAQ,QAAgB,QAAQ;EAEpD,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,mCAAmC,UAAU;EAY/D,MAAM;GARJ;GACA;GACA,KAAK,MAAM,MAAM,oBAAoB;GACrC,MAAM,OAAO,KAAK;GAClB,cAAc;GACd,KAAK;EAGO;CAChB;AACF"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { consola } from "consola";
|
|
1
2
|
//#region src/module/utils/assets.ts
|
|
2
3
|
function updateServerAssets(config, assets) {
|
|
4
|
+
consola.withTag("updateServerAssets").debug(assets);
|
|
3
5
|
config.serverAssets ||= [];
|
|
4
6
|
config.serverAssets = config.serverAssets.filter((_assets) => {
|
|
5
7
|
const baseName = _assets?.baseName;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assets.mjs","names":[],"sources":["../../../src/module/utils/assets.ts"],"sourcesContent":["import type {\n NitroConfig as LegacyNitroConfig,\n ServerAssetDir as LegacyServerAssetDir,\n} from \"nitropack/types\";\nimport type { NitroConfig, ServerAssetDir } from \"nitro/types\";\n\nexport function updateServerAssets(\n config: NitroConfig | LegacyNitroConfig,\n assets: readonly (ServerAssetDir | LegacyServerAssetDir)[],\n) {\n config.serverAssets ||= [];\n config.serverAssets = config.serverAssets\n .filter((_assets) => {\n const baseName = _assets?.baseName;\n if (!baseName) {\n return true;\n }\n return assets.some((assets) => baseName == assets.baseName);\n })\n .concat(assets);\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"assets.mjs","names":[],"sources":["../../../src/module/utils/assets.ts"],"sourcesContent":["import type {\n NitroConfig as LegacyNitroConfig,\n ServerAssetDir as LegacyServerAssetDir,\n} from \"nitropack/types\";\nimport type { NitroConfig, ServerAssetDir } from \"nitro/types\";\nimport { consola } from \"consola\";\n\nexport function updateServerAssets(\n config: NitroConfig | LegacyNitroConfig,\n assets: readonly (ServerAssetDir | LegacyServerAssetDir)[],\n) {\n consola.withTag(\"updateServerAssets\").debug(assets);\n config.serverAssets ||= [];\n config.serverAssets = config.serverAssets\n .filter((_assets) => {\n const baseName = _assets?.baseName;\n if (!baseName) {\n return true;\n }\n return assets.some((assets) => baseName == assets.baseName);\n })\n .concat(assets);\n}\n"],"mappings":";;AAOA,SAAgB,mBACd,QACA,QACA;CACA,QAAQ,QAAQ,oBAAoB,CAAC,CAAC,MAAM,MAAM;CAClD,OAAO,iBAAiB,CAAC;CACzB,OAAO,eAAe,OAAO,aAC1B,QAAQ,YAAY;EACnB,MAAM,WAAW,SAAS;EAC1B,IAAI,CAAC,UACH,OAAO;EAET,OAAO,OAAO,MAAM,WAAW,YAAY,OAAO,QAAQ;CAC5D,CAAC,CAAC,CACD,OAAO,MAAM;AAClB"}
|
package/dist/module.d.mts
CHANGED
|
@@ -2,14 +2,19 @@ import { updateServerAssets } from "./module/utils/assets.mjs";
|
|
|
2
2
|
import { addInlineExternals } from "./module/utils/externals.mjs";
|
|
3
3
|
import { isLegacy } from "./module/utils/nitro.mjs";
|
|
4
4
|
import { ConfigPattern, MigrationOptions } from "nitro-drizzle/context";
|
|
5
|
+
import { ConnectorSpecifier, ConnectorVariants, ExpandVariants, Variant } from "nitro-drizzle/shared";
|
|
5
6
|
import { NitroModule } from "nitropack/types";
|
|
6
7
|
import { NitroModule as NitroModule$1 } from "nitro/types";
|
|
8
|
+
import { Connector } from "nitro-drizzle/drivers";
|
|
7
9
|
//#region src/module/index.d.ts
|
|
8
10
|
/**
|
|
9
11
|
* Datasource-specific configuration options.
|
|
10
|
-
* This interface is augmented by the module with connector-specific options.
|
|
11
12
|
*/
|
|
12
|
-
|
|
13
|
+
type DatasourceOptionsMapper<T extends Variant<Connector<any, any, any, any>, ConnectorSpecifier>> = T extends any ? Variant<{
|
|
14
|
+
drivers: readonly string[];
|
|
15
|
+
}, Pick<T["selector"], "name">> : never;
|
|
16
|
+
type DatasourceOptionsVariants = DatasourceOptionsMapper<ConnectorVariants>;
|
|
17
|
+
type DatasourceOptions = ExpandVariants<DatasourceOptionsVariants, ["name"]>;
|
|
13
18
|
declare module "nitropack/types" {
|
|
14
19
|
interface NitroOptions {
|
|
15
20
|
drizzle?: ModuleOptions;
|