@guren/orm 1.1.0 → 1.3.0
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/index.d.ts +90 -7
- package/dist/index.js +509 -87
- package/package.json +6 -1
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ import { SQL } from 'drizzle-orm';
|
|
|
2
2
|
import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
|
|
3
3
|
import postgres from 'postgres';
|
|
4
4
|
import { MySql2Database } from 'drizzle-orm/mysql2';
|
|
5
|
+
import * as drizzle_orm_aws_data_api_pg from 'drizzle-orm/aws-data-api/pg';
|
|
6
|
+
import { RDSDataClientConfig } from '@aws-sdk/client-rds-data';
|
|
5
7
|
|
|
6
8
|
/** Accessor function: transforms a record field value after reading from DB. */
|
|
7
9
|
type AccessorFn<T = unknown> = (record: PlainObject) => T;
|
|
@@ -1513,10 +1515,10 @@ interface MigrationStatusEntry {
|
|
|
1513
1515
|
appliedAt: Date | null;
|
|
1514
1516
|
}
|
|
1515
1517
|
|
|
1516
|
-
type ConnectionResolver$
|
|
1518
|
+
type ConnectionResolver$3 = string | (() => string | undefined);
|
|
1517
1519
|
interface PostgresDatabaseOptions {
|
|
1518
1520
|
migrationsFolder: string | URL;
|
|
1519
|
-
connectionString?: ConnectionResolver$
|
|
1521
|
+
connectionString?: ConnectionResolver$3;
|
|
1520
1522
|
clientOptions?: postgres.Options<Record<string, never>>;
|
|
1521
1523
|
seedersFolder?: string | URL;
|
|
1522
1524
|
/**
|
|
@@ -1539,11 +1541,11 @@ interface PostgresDatabase {
|
|
|
1539
1541
|
}
|
|
1540
1542
|
declare function createPostgresDatabase(options: PostgresDatabaseOptions): PostgresDatabase;
|
|
1541
1543
|
|
|
1542
|
-
type ConnectionResolver$
|
|
1544
|
+
type ConnectionResolver$2 = string | (() => string | undefined);
|
|
1543
1545
|
type MySqlConnectionOptions = Record<string, unknown>;
|
|
1544
1546
|
interface MySqlDatabaseOptions {
|
|
1545
1547
|
migrationsFolder: string | URL;
|
|
1546
|
-
connectionString?: ConnectionResolver$
|
|
1548
|
+
connectionString?: ConnectionResolver$2;
|
|
1547
1549
|
clientOptions?: MySqlConnectionOptions;
|
|
1548
1550
|
seedersFolder?: string | URL;
|
|
1549
1551
|
/**
|
|
@@ -1566,11 +1568,11 @@ interface MySqlDatabase {
|
|
|
1566
1568
|
}
|
|
1567
1569
|
declare function createMySqlDatabase(options: MySqlDatabaseOptions): MySqlDatabase;
|
|
1568
1570
|
|
|
1569
|
-
type ConnectionResolver = string | (() => string | undefined);
|
|
1571
|
+
type ConnectionResolver$1 = string | (() => string | undefined);
|
|
1570
1572
|
interface SqliteDatabaseOptions {
|
|
1571
1573
|
migrationsFolder: string | URL;
|
|
1572
1574
|
/** Path to the SQLite database file. Defaults to `./data/guren.db`. */
|
|
1573
|
-
filename?: ConnectionResolver;
|
|
1575
|
+
filename?: ConnectionResolver$1;
|
|
1574
1576
|
seedersFolder?: string | URL;
|
|
1575
1577
|
/**
|
|
1576
1578
|
* Drizzle relations for RQB v2 (`db.query.*`).
|
|
@@ -1592,6 +1594,87 @@ interface SqliteDatabase {
|
|
|
1592
1594
|
}
|
|
1593
1595
|
declare function createSqliteDatabase(options: SqliteDatabaseOptions): SqliteDatabase;
|
|
1594
1596
|
|
|
1597
|
+
interface D1DatabaseOptions {
|
|
1598
|
+
/**
|
|
1599
|
+
* Resolver returning the Cloudflare D1 binding. Bindings arrive with the
|
|
1600
|
+
* first request on Workers, so this must be a deferred closure, e.g.
|
|
1601
|
+
* `binding: () => getWorkersEnv<Env>().DB`.
|
|
1602
|
+
*/
|
|
1603
|
+
binding: () => unknown;
|
|
1604
|
+
/**
|
|
1605
|
+
* Drizzle-kit migrations folder. D1 migrations are applied out-of-band via
|
|
1606
|
+
* `wrangler d1 migrations apply` (point `d1_databases[].migrations_dir` at
|
|
1607
|
+
* this folder); the factory only references it in error guidance.
|
|
1608
|
+
*/
|
|
1609
|
+
migrationsFolder?: string | URL;
|
|
1610
|
+
/**
|
|
1611
|
+
* Drizzle relations for RQB v2 (`db.query.*`).
|
|
1612
|
+
* Build with `defineRelations(schema, ...)` from `drizzle-orm`,
|
|
1613
|
+
* or with `relations()` from `drizzle-orm/_relations` for the RQB v1 partial-upgrade path.
|
|
1614
|
+
*/
|
|
1615
|
+
relations?: Record<string, unknown>;
|
|
1616
|
+
}
|
|
1617
|
+
interface D1DatabaseHandle {
|
|
1618
|
+
getDatabase(): Promise<unknown>;
|
|
1619
|
+
/** Always throws: D1 migrations are applied with `wrangler d1 migrations apply`, never at runtime. */
|
|
1620
|
+
migrateDatabase(): Promise<void>;
|
|
1621
|
+
closeDatabase(): Promise<void>;
|
|
1622
|
+
configureOrm(): Promise<void>;
|
|
1623
|
+
/** Always throws: seed with SQL through `wrangler d1 execute`. */
|
|
1624
|
+
seedDatabase(): Promise<void>;
|
|
1625
|
+
/** Always throws: recreate the database with wrangler instead. */
|
|
1626
|
+
resetDatabase(): Promise<void>;
|
|
1627
|
+
/** Always throws: wrangler's tracker is authoritative — use `wrangler d1 migrations list`. */
|
|
1628
|
+
migrationStatus(): Promise<never>;
|
|
1629
|
+
}
|
|
1630
|
+
/**
|
|
1631
|
+
* Cloudflare D1 database factory. D1 speaks the SQLite dialect, so schemas
|
|
1632
|
+
* written for `createSqliteDatabase` port unchanged; only the connection and
|
|
1633
|
+
* the migration workflow differ (wrangler owns migrations, see RFC 0003).
|
|
1634
|
+
*/
|
|
1635
|
+
declare function createD1Database(options: D1DatabaseOptions): D1DatabaseHandle;
|
|
1636
|
+
|
|
1637
|
+
type ConnectionResolver = string | (() => string | undefined);
|
|
1638
|
+
type AwsDataApiPgDatabase = drizzle_orm_aws_data_api_pg.AwsDataApiPgDatabase;
|
|
1639
|
+
interface AwsDataApiDatabaseOptions {
|
|
1640
|
+
migrationsFolder: string | URL;
|
|
1641
|
+
/** Database name. Falls back to the DATABASE_NAME environment variable. */
|
|
1642
|
+
database?: ConnectionResolver;
|
|
1643
|
+
/** Aurora cluster ARN. Falls back to the DATABASE_RESOURCE_ARN environment variable. */
|
|
1644
|
+
resourceArn?: ConnectionResolver;
|
|
1645
|
+
/** Secrets Manager secret ARN holding the credentials. Falls back to the DATABASE_SECRET_ARN environment variable. */
|
|
1646
|
+
secretArn?: ConnectionResolver;
|
|
1647
|
+
/** Extra RDSDataClient configuration (region, credentials, ...). */
|
|
1648
|
+
clientOptions?: RDSDataClientConfig;
|
|
1649
|
+
/**
|
|
1650
|
+
* Run pending migrations on the first `getDatabase()` call, like the other
|
|
1651
|
+
* database factories do. Off by default: on Lambda that check runs on every
|
|
1652
|
+
* cold start and costs several serialized Data API round trips before the
|
|
1653
|
+
* first query. Run migrations out of band instead — `db:migrate` locally,
|
|
1654
|
+
* or the console handler (`{"command": "db:migrate"}`) once deployed.
|
|
1655
|
+
*/
|
|
1656
|
+
migrateOnStart?: boolean;
|
|
1657
|
+
seedersFolder?: string | URL;
|
|
1658
|
+
/**
|
|
1659
|
+
* Drizzle relations for RQB v2 (`db.query.*`).
|
|
1660
|
+
* Build with `defineRelations(schema, ...)` from `drizzle-orm`,
|
|
1661
|
+
* or with `relations()` from `drizzle-orm/_relations` for the RQB v1 partial-upgrade path.
|
|
1662
|
+
*/
|
|
1663
|
+
relations?: Record<string, unknown>;
|
|
1664
|
+
}
|
|
1665
|
+
interface AwsDataApiDatabase {
|
|
1666
|
+
getDatabase(): Promise<AwsDataApiPgDatabase>;
|
|
1667
|
+
migrateDatabase(): Promise<void>;
|
|
1668
|
+
closeDatabase(): Promise<void>;
|
|
1669
|
+
configureOrm(): Promise<void>;
|
|
1670
|
+
seedDatabase(): Promise<void>;
|
|
1671
|
+
/** Drops the public schema (and the drizzle tracker schema) so migrations can be re-applied from scratch. */
|
|
1672
|
+
resetDatabase(): Promise<void>;
|
|
1673
|
+
/** Per-migration applied state derived from the drizzle-kit journal and drizzle.__drizzle_migrations. */
|
|
1674
|
+
migrationStatus(): Promise<MigrationStatusEntry[]>;
|
|
1675
|
+
}
|
|
1676
|
+
declare function createAwsDataApiDatabase(options: AwsDataApiDatabaseOptions): AwsDataApiDatabase;
|
|
1677
|
+
|
|
1595
1678
|
interface SeederContext {
|
|
1596
1679
|
db: PostgresJsDatabase;
|
|
1597
1680
|
}
|
|
@@ -1614,4 +1697,4 @@ declare function serializeRecord(record: PlainObject, options: {
|
|
|
1614
1697
|
/** Serialize an array of records. */
|
|
1615
1698
|
declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
|
|
1616
1699
|
|
|
1617
|
-
export { type AccessorDefinitions, type AccessorFn, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, DrizzleAdapter, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
|
|
1700
|
+
export { type AccessorDefinitions, type AccessorFn, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type D1DatabaseHandle, type D1DatabaseOptions, DrizzleAdapter, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
|
package/dist/index.js
CHANGED
|
@@ -2594,6 +2594,84 @@ function SoftDeletes(Base) {
|
|
|
2594
2594
|
import { resolve as resolve3 } from "path";
|
|
2595
2595
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
2596
2596
|
|
|
2597
|
+
// src/active-connections.ts
|
|
2598
|
+
var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("guren.orm.activeConnections");
|
|
2599
|
+
var TEARDOWN_TIMEOUT_MS = 5e3;
|
|
2600
|
+
function getRegistry() {
|
|
2601
|
+
const scope = globalThis;
|
|
2602
|
+
const existing = scope[REGISTRY_KEY];
|
|
2603
|
+
if (existing) {
|
|
2604
|
+
return existing;
|
|
2605
|
+
}
|
|
2606
|
+
const registry = /* @__PURE__ */ new Map();
|
|
2607
|
+
scope[REGISTRY_KEY] = registry;
|
|
2608
|
+
return registry;
|
|
2609
|
+
}
|
|
2610
|
+
function isHotReloadRuntime() {
|
|
2611
|
+
return typeof process !== "undefined" && Array.isArray(process.execArgv) && process.execArgv.includes("--hot");
|
|
2612
|
+
}
|
|
2613
|
+
function parseFrameLocation(frame) {
|
|
2614
|
+
return frame?.match(/\((.+?):\d+(?::\d+)?\)\s*$/)?.[1] ?? frame?.match(/^\s*at\s+(.+?):\d+(?::\d+)?\s*$/)?.[1];
|
|
2615
|
+
}
|
|
2616
|
+
function describeCallerFile(stack) {
|
|
2617
|
+
return parseFrameLocation(stack?.split("\n")[2]);
|
|
2618
|
+
}
|
|
2619
|
+
function hotReloadKey(driver, stack, target) {
|
|
2620
|
+
if (!isHotReloadRuntime()) {
|
|
2621
|
+
return void 0;
|
|
2622
|
+
}
|
|
2623
|
+
const callerFile = describeCallerFile(stack);
|
|
2624
|
+
if (!callerFile) {
|
|
2625
|
+
return void 0;
|
|
2626
|
+
}
|
|
2627
|
+
return `${driver}|${callerFile}|${target}`;
|
|
2628
|
+
}
|
|
2629
|
+
async function closeWithTimeout(teardown, timeoutMs) {
|
|
2630
|
+
let timer;
|
|
2631
|
+
try {
|
|
2632
|
+
await Promise.race([
|
|
2633
|
+
Promise.resolve(teardown()),
|
|
2634
|
+
new Promise((resolveTimeout) => {
|
|
2635
|
+
timer = setTimeout(() => {
|
|
2636
|
+
console.warn(
|
|
2637
|
+
`[guren/orm] The previous database connection did not close within ${timeoutMs}ms; continuing without it.`
|
|
2638
|
+
);
|
|
2639
|
+
resolveTimeout();
|
|
2640
|
+
}, timeoutMs);
|
|
2641
|
+
})
|
|
2642
|
+
]);
|
|
2643
|
+
} catch (error) {
|
|
2644
|
+
console.warn("[guren/orm] Failed to close the previous database connection:", error);
|
|
2645
|
+
} finally {
|
|
2646
|
+
if (timer) {
|
|
2647
|
+
clearTimeout(timer);
|
|
2648
|
+
}
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
async function replaceActiveConnection(key, teardown, timeoutMs = TEARDOWN_TIMEOUT_MS) {
|
|
2652
|
+
const registry = getRegistry();
|
|
2653
|
+
const previous = registry.get(key);
|
|
2654
|
+
if (previous?.teardown === teardown) {
|
|
2655
|
+
return;
|
|
2656
|
+
}
|
|
2657
|
+
const settled = (async () => {
|
|
2658
|
+
if (!previous) {
|
|
2659
|
+
return;
|
|
2660
|
+
}
|
|
2661
|
+
await previous.settled.catch(() => {
|
|
2662
|
+
});
|
|
2663
|
+
await closeWithTimeout(previous.teardown, timeoutMs);
|
|
2664
|
+
})();
|
|
2665
|
+
registry.set(key, { teardown, settled });
|
|
2666
|
+
await settled;
|
|
2667
|
+
}
|
|
2668
|
+
function releaseActiveConnection(key, teardown) {
|
|
2669
|
+
const registry = getRegistry();
|
|
2670
|
+
if (registry.get(key)?.teardown === teardown) {
|
|
2671
|
+
registry.delete(key);
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
|
|
2597
2675
|
// src/migration-utils.ts
|
|
2598
2676
|
import { existsSync, readdirSync } from "fs";
|
|
2599
2677
|
import { resolve } from "path";
|
|
@@ -2618,6 +2696,76 @@ function warnIgnoredFlatSqlMigrations(migrationsFolder) {
|
|
|
2618
2696
|
);
|
|
2619
2697
|
}
|
|
2620
2698
|
}
|
|
2699
|
+
var PRE_CONNECTION_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
2700
|
+
"CONNECT_TIMEOUT",
|
|
2701
|
+
"EAI_AGAIN",
|
|
2702
|
+
"ECONNREFUSED",
|
|
2703
|
+
"EHOSTUNREACH",
|
|
2704
|
+
"ENETUNREACH",
|
|
2705
|
+
"ENOTFOUND"
|
|
2706
|
+
]);
|
|
2707
|
+
function failedWhileConnecting(error) {
|
|
2708
|
+
const { code, syscall } = error;
|
|
2709
|
+
if (typeof code !== "string" || code === "") {
|
|
2710
|
+
return false;
|
|
2711
|
+
}
|
|
2712
|
+
return PRE_CONNECTION_ERROR_CODES.has(code) || syscall === "connect";
|
|
2713
|
+
}
|
|
2714
|
+
function collectCauses(error, seen = /* @__PURE__ */ new Set()) {
|
|
2715
|
+
if (error == null || typeof error !== "object" || seen.has(error)) {
|
|
2716
|
+
return [];
|
|
2717
|
+
}
|
|
2718
|
+
seen.add(error);
|
|
2719
|
+
const nested = [
|
|
2720
|
+
...Array.isArray(error.errors) ? error.errors : [],
|
|
2721
|
+
..."cause" in error ? [error.cause] : []
|
|
2722
|
+
];
|
|
2723
|
+
return [error, ...nested.flatMap((child) => collectCauses(child, seen))];
|
|
2724
|
+
}
|
|
2725
|
+
function isConnectionFailure(error) {
|
|
2726
|
+
return collectCauses(error).some(failedWhileConnecting);
|
|
2727
|
+
}
|
|
2728
|
+
function describeDatabaseFailure(error, endpoint) {
|
|
2729
|
+
const causes = collectCauses(error);
|
|
2730
|
+
const connectFailure = causes.find(failedWhileConnecting);
|
|
2731
|
+
if (connectFailure) {
|
|
2732
|
+
const target = endpoint ? `the database at ${endpoint}` : "the database";
|
|
2733
|
+
return `cannot connect to ${target} (${connectFailure.code}). Is it running and accepting connections?`;
|
|
2734
|
+
}
|
|
2735
|
+
const messages = [
|
|
2736
|
+
...new Set(
|
|
2737
|
+
causes.map((cause) => cause.message).filter((message) => typeof message === "string" && message.trim() !== "")
|
|
2738
|
+
)
|
|
2739
|
+
];
|
|
2740
|
+
if (messages.length === 0) {
|
|
2741
|
+
return error instanceof Error ? error.message : String(error);
|
|
2742
|
+
}
|
|
2743
|
+
if (messages.length === 1) {
|
|
2744
|
+
const deepestCode = causes.reduce(
|
|
2745
|
+
(found, cause) => typeof cause.code === "string" && cause.code !== "" ? cause.code : found,
|
|
2746
|
+
void 0
|
|
2747
|
+
);
|
|
2748
|
+
if (deepestCode) {
|
|
2749
|
+
return `${messages[0]} (${deepestCode})`;
|
|
2750
|
+
}
|
|
2751
|
+
}
|
|
2752
|
+
return messages.join(" \u2014 ");
|
|
2753
|
+
}
|
|
2754
|
+
function migrationFailure(error, endpoint) {
|
|
2755
|
+
return new Error(`Failed to run database migrations: ${describeDatabaseFailure(error, endpoint)}`);
|
|
2756
|
+
}
|
|
2757
|
+
function seedFailure(error, endpoint) {
|
|
2758
|
+
return new Error(`Failed to seed the database: ${describeDatabaseFailure(error, endpoint)}`);
|
|
2759
|
+
}
|
|
2760
|
+
function describeConnectionEndpoint(connectionString) {
|
|
2761
|
+
try {
|
|
2762
|
+
const { hostname, port } = new URL(connectionString);
|
|
2763
|
+
if (!hostname) return void 0;
|
|
2764
|
+
return port ? `${hostname}:${port}` : hostname;
|
|
2765
|
+
} catch {
|
|
2766
|
+
return void 0;
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2621
2769
|
function listLocalMigrations(migrationsFolder) {
|
|
2622
2770
|
if (!existsSync(migrationsFolder)) {
|
|
2623
2771
|
return [];
|
|
@@ -2738,6 +2886,8 @@ function createPostgresDatabase(options) {
|
|
|
2738
2886
|
let migrationsPromise;
|
|
2739
2887
|
let databasePromise;
|
|
2740
2888
|
let client;
|
|
2889
|
+
let activeKey;
|
|
2890
|
+
const callSite = new Error().stack;
|
|
2741
2891
|
function resolveConnectionString() {
|
|
2742
2892
|
const value = typeof connectionString === "function" ? connectionString() : connectionString;
|
|
2743
2893
|
const resolved = value ?? process.env.DATABASE_URL;
|
|
@@ -2750,6 +2900,7 @@ function createPostgresDatabase(options) {
|
|
|
2750
2900
|
if (migrationsPromise) {
|
|
2751
2901
|
return migrationsPromise;
|
|
2752
2902
|
}
|
|
2903
|
+
let endpoint;
|
|
2753
2904
|
const promise = (async () => {
|
|
2754
2905
|
if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
|
|
2755
2906
|
warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
|
|
@@ -2757,6 +2908,7 @@ function createPostgresDatabase(options) {
|
|
|
2757
2908
|
}
|
|
2758
2909
|
const { drizzle, migrate, postgres: postgresFactory } = await loadPostgresModules();
|
|
2759
2910
|
const url = resolveConnectionString();
|
|
2911
|
+
endpoint = describeConnectionEndpoint(url);
|
|
2760
2912
|
const migrationClient = postgresFactory(url, {
|
|
2761
2913
|
max: 1,
|
|
2762
2914
|
...clientOptions
|
|
@@ -2770,8 +2922,7 @@ function createPostgresDatabase(options) {
|
|
|
2770
2922
|
})();
|
|
2771
2923
|
migrationsPromise = promise.catch((error) => {
|
|
2772
2924
|
migrationsPromise = void 0;
|
|
2773
|
-
|
|
2774
|
-
throw new Error(`Failed to run database migrations: ${reason}`);
|
|
2925
|
+
throw migrationFailure(error, endpoint);
|
|
2775
2926
|
});
|
|
2776
2927
|
await migrationsPromise;
|
|
2777
2928
|
}
|
|
@@ -2783,11 +2934,19 @@ function createPostgresDatabase(options) {
|
|
|
2783
2934
|
await migrateOnce();
|
|
2784
2935
|
const { drizzle, postgres: postgresFactory } = await loadPostgresModules();
|
|
2785
2936
|
const url = resolveConnectionString();
|
|
2786
|
-
|
|
2937
|
+
const activeClient = postgresFactory(url, {
|
|
2787
2938
|
max: 1,
|
|
2788
2939
|
...clientOptions
|
|
2789
2940
|
});
|
|
2790
|
-
|
|
2941
|
+
client = activeClient;
|
|
2942
|
+
activeKey = hotReloadKey("postgres", callSite, url);
|
|
2943
|
+
if (activeKey) {
|
|
2944
|
+
await replaceActiveConnection(activeKey, closeDatabase);
|
|
2945
|
+
}
|
|
2946
|
+
return drizzle({
|
|
2947
|
+
client: activeClient,
|
|
2948
|
+
...relations ? { relations } : {}
|
|
2949
|
+
});
|
|
2791
2950
|
})();
|
|
2792
2951
|
databasePromise = promise.catch((error) => {
|
|
2793
2952
|
databasePromise = void 0;
|
|
@@ -2799,9 +2958,17 @@ function createPostgresDatabase(options) {
|
|
|
2799
2958
|
if (!client) {
|
|
2800
2959
|
return;
|
|
2801
2960
|
}
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2961
|
+
const key = activeKey;
|
|
2962
|
+
activeKey = void 0;
|
|
2963
|
+
try {
|
|
2964
|
+
await client.end({ timeout: 0 });
|
|
2965
|
+
} finally {
|
|
2966
|
+
client = void 0;
|
|
2967
|
+
databasePromise = void 0;
|
|
2968
|
+
if (key) {
|
|
2969
|
+
releaseActiveConnection(key, closeDatabase);
|
|
2970
|
+
}
|
|
2971
|
+
}
|
|
2805
2972
|
}
|
|
2806
2973
|
async function configureOrm() {
|
|
2807
2974
|
const db = await getDatabase();
|
|
@@ -2812,16 +2979,23 @@ function createPostgresDatabase(options) {
|
|
|
2812
2979
|
throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createPostgresDatabase().');
|
|
2813
2980
|
}
|
|
2814
2981
|
const db = await getDatabase();
|
|
2815
|
-
|
|
2982
|
+
try {
|
|
2983
|
+
await runSeeders(db, resolvedSeedersFolder);
|
|
2984
|
+
} catch (error) {
|
|
2985
|
+
throw seedFailure(error, describeConnectionEndpoint(resolveConnectionString()));
|
|
2986
|
+
}
|
|
2816
2987
|
}
|
|
2817
2988
|
async function withAdminClient(callback) {
|
|
2818
2989
|
const { postgres: postgresFactory } = await loadPostgresModules();
|
|
2819
|
-
const
|
|
2990
|
+
const url = resolveConnectionString();
|
|
2991
|
+
const adminClient = postgresFactory(url, {
|
|
2820
2992
|
max: 1,
|
|
2821
2993
|
...clientOptions
|
|
2822
2994
|
});
|
|
2823
2995
|
try {
|
|
2824
2996
|
return await callback(adminClient);
|
|
2997
|
+
} catch (error) {
|
|
2998
|
+
throw new Error(describeDatabaseFailure(error, describeConnectionEndpoint(url)));
|
|
2825
2999
|
} finally {
|
|
2826
3000
|
await adminClient.end({ timeout: 0 });
|
|
2827
3001
|
}
|
|
@@ -2844,7 +3018,8 @@ function createPostgresDatabase(options) {
|
|
|
2844
3018
|
const record = row;
|
|
2845
3019
|
return { name: record.name, appliedAt: null };
|
|
2846
3020
|
});
|
|
2847
|
-
} catch {
|
|
3021
|
+
} catch (error) {
|
|
3022
|
+
if (isConnectionFailure(error)) throw error;
|
|
2848
3023
|
return [];
|
|
2849
3024
|
}
|
|
2850
3025
|
});
|
|
@@ -2866,11 +3041,12 @@ import { resolve as resolve4 } from "path";
|
|
|
2866
3041
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
2867
3042
|
async function loadMySqlModules() {
|
|
2868
3043
|
try {
|
|
2869
|
-
const [{ drizzle }, { migrate }] = await Promise.all([
|
|
3044
|
+
const [{ drizzle }, { migrate }, { createPool }] = await Promise.all([
|
|
2870
3045
|
import("drizzle-orm/mysql2"),
|
|
2871
|
-
import("drizzle-orm/mysql2/migrator")
|
|
3046
|
+
import("drizzle-orm/mysql2/migrator"),
|
|
3047
|
+
import("mysql2")
|
|
2872
3048
|
]);
|
|
2873
|
-
return { drizzle, migrate };
|
|
3049
|
+
return { drizzle, migrate, createPool };
|
|
2874
3050
|
} catch (error) {
|
|
2875
3051
|
const reason = error instanceof Error ? error.message : String(error);
|
|
2876
3052
|
throw new Error(
|
|
@@ -2884,7 +3060,9 @@ function createMySqlDatabase(options) {
|
|
|
2884
3060
|
const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath3(seedersFolder) : resolve4(String(seedersFolder));
|
|
2885
3061
|
let migrationsPromise;
|
|
2886
3062
|
let databasePromise;
|
|
2887
|
-
let
|
|
3063
|
+
let client;
|
|
3064
|
+
let activeKey;
|
|
3065
|
+
const callSite = new Error().stack;
|
|
2888
3066
|
function resolveConnectionString() {
|
|
2889
3067
|
const value = typeof connectionString === "function" ? connectionString() : connectionString;
|
|
2890
3068
|
const resolved = value ?? process.env.DATABASE_URL;
|
|
@@ -2897,31 +3075,29 @@ function createMySqlDatabase(options) {
|
|
|
2897
3075
|
if (migrationsPromise) {
|
|
2898
3076
|
return migrationsPromise;
|
|
2899
3077
|
}
|
|
3078
|
+
let endpoint;
|
|
2900
3079
|
const promise = (async () => {
|
|
2901
3080
|
if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
|
|
2902
3081
|
warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
|
|
2903
3082
|
return;
|
|
2904
3083
|
}
|
|
2905
|
-
const { drizzle, migrate } = await loadMySqlModules();
|
|
3084
|
+
const { drizzle, migrate, createPool } = await loadMySqlModules();
|
|
2906
3085
|
const url = resolveConnectionString();
|
|
2907
|
-
|
|
2908
|
-
|
|
2909
|
-
uri: url,
|
|
2910
|
-
...clientOptions
|
|
2911
|
-
},
|
|
2912
|
-
mode: "default",
|
|
2913
|
-
...relations ? { relations } : {}
|
|
2914
|
-
});
|
|
3086
|
+
endpoint = describeConnectionEndpoint(url);
|
|
3087
|
+
const migrationClient = createPool({ uri: url, ...clientOptions });
|
|
2915
3088
|
try {
|
|
3089
|
+
const migrationDb = drizzle({
|
|
3090
|
+
client: migrationClient,
|
|
3091
|
+
...relations ? { relations } : {}
|
|
3092
|
+
});
|
|
2916
3093
|
await migrate(migrationDb, { migrationsFolder: resolvedMigrationsFolder });
|
|
2917
3094
|
} finally {
|
|
2918
|
-
await
|
|
3095
|
+
await closePool(migrationClient);
|
|
2919
3096
|
}
|
|
2920
3097
|
})();
|
|
2921
3098
|
migrationsPromise = promise.catch((error) => {
|
|
2922
3099
|
migrationsPromise = void 0;
|
|
2923
|
-
|
|
2924
|
-
throw new Error(`Failed to run database migrations: ${reason}`);
|
|
3100
|
+
throw migrationFailure(error, endpoint);
|
|
2925
3101
|
});
|
|
2926
3102
|
await migrationsPromise;
|
|
2927
3103
|
}
|
|
@@ -2931,18 +3107,18 @@ function createMySqlDatabase(options) {
|
|
|
2931
3107
|
}
|
|
2932
3108
|
const promise = (async () => {
|
|
2933
3109
|
await migrateOnce();
|
|
2934
|
-
const { drizzle } = await loadMySqlModules();
|
|
3110
|
+
const { drizzle, createPool } = await loadMySqlModules();
|
|
2935
3111
|
const url = resolveConnectionString();
|
|
2936
|
-
const
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
3112
|
+
const activeClient = createPool({ uri: url, ...clientOptions });
|
|
3113
|
+
client = activeClient;
|
|
3114
|
+
activeKey = hotReloadKey("mysql", callSite, url);
|
|
3115
|
+
if (activeKey) {
|
|
3116
|
+
await replaceActiveConnection(activeKey, closeDatabase);
|
|
3117
|
+
}
|
|
3118
|
+
return drizzle({
|
|
3119
|
+
client: activeClient,
|
|
2942
3120
|
...relations ? { relations } : {}
|
|
2943
3121
|
});
|
|
2944
|
-
database2 = db;
|
|
2945
|
-
return db;
|
|
2946
3122
|
})();
|
|
2947
3123
|
databasePromise = promise.catch((error) => {
|
|
2948
3124
|
databasePromise = void 0;
|
|
@@ -2951,12 +3127,20 @@ function createMySqlDatabase(options) {
|
|
|
2951
3127
|
return databasePromise;
|
|
2952
3128
|
}
|
|
2953
3129
|
async function closeDatabase() {
|
|
2954
|
-
if (!
|
|
3130
|
+
if (!client) {
|
|
2955
3131
|
return;
|
|
2956
3132
|
}
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
3133
|
+
const key = activeKey;
|
|
3134
|
+
activeKey = void 0;
|
|
3135
|
+
try {
|
|
3136
|
+
await closePool(client);
|
|
3137
|
+
} finally {
|
|
3138
|
+
client = void 0;
|
|
3139
|
+
databasePromise = void 0;
|
|
3140
|
+
if (key) {
|
|
3141
|
+
releaseActiveConnection(key, closeDatabase);
|
|
3142
|
+
}
|
|
3143
|
+
}
|
|
2960
3144
|
}
|
|
2961
3145
|
async function configureOrm() {
|
|
2962
3146
|
const db = await getDatabase();
|
|
@@ -2967,21 +3151,23 @@ function createMySqlDatabase(options) {
|
|
|
2967
3151
|
throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createMySqlDatabase().');
|
|
2968
3152
|
}
|
|
2969
3153
|
const db = await getDatabase();
|
|
2970
|
-
|
|
3154
|
+
try {
|
|
3155
|
+
await runSeeders(db, resolvedSeedersFolder);
|
|
3156
|
+
} catch (error) {
|
|
3157
|
+
throw seedFailure(error, describeConnectionEndpoint(resolveConnectionString()));
|
|
3158
|
+
}
|
|
2971
3159
|
}
|
|
2972
3160
|
async function withAdminDb(callback) {
|
|
2973
|
-
const { drizzle } = await loadMySqlModules();
|
|
2974
|
-
const
|
|
2975
|
-
|
|
2976
|
-
|
|
2977
|
-
...clientOptions
|
|
2978
|
-
},
|
|
2979
|
-
mode: "default"
|
|
2980
|
-
});
|
|
3161
|
+
const { drizzle, createPool } = await loadMySqlModules();
|
|
3162
|
+
const url = resolveConnectionString();
|
|
3163
|
+
const adminClient = createPool({ uri: url, ...clientOptions });
|
|
3164
|
+
const adminDb = drizzle({ client: adminClient });
|
|
2981
3165
|
try {
|
|
2982
3166
|
return await callback(adminDb);
|
|
3167
|
+
} catch (error) {
|
|
3168
|
+
throw new Error(describeDatabaseFailure(error, describeConnectionEndpoint(url)));
|
|
2983
3169
|
} finally {
|
|
2984
|
-
await
|
|
3170
|
+
await closePool(adminClient);
|
|
2985
3171
|
}
|
|
2986
3172
|
}
|
|
2987
3173
|
async function resetDatabase() {
|
|
@@ -3011,7 +3197,8 @@ function createMySqlDatabase(options) {
|
|
|
3011
3197
|
sql.raw("SELECT name, applied_at FROM __drizzle_migrations")
|
|
3012
3198
|
);
|
|
3013
3199
|
return rows.map((row) => ({ name: row.name, appliedAt: row.applied_at }));
|
|
3014
|
-
} catch {
|
|
3200
|
+
} catch (error) {
|
|
3201
|
+
if (isConnectionFailure(error)) throw error;
|
|
3015
3202
|
return [];
|
|
3016
3203
|
}
|
|
3017
3204
|
});
|
|
@@ -3027,38 +3214,18 @@ function createMySqlDatabase(options) {
|
|
|
3027
3214
|
migrationStatus
|
|
3028
3215
|
};
|
|
3029
3216
|
}
|
|
3030
|
-
async function
|
|
3031
|
-
if (typeof db !== "object" || db === null) {
|
|
3032
|
-
return;
|
|
3033
|
-
}
|
|
3034
|
-
const maybeClient = db.$client;
|
|
3035
|
-
if (!maybeClient || typeof maybeClient.end !== "function") {
|
|
3036
|
-
return;
|
|
3037
|
-
}
|
|
3038
|
-
if (maybeClient.end.length === 0) {
|
|
3039
|
-
const maybePromise = maybeClient.end();
|
|
3040
|
-
if (isPromiseLike2(maybePromise)) {
|
|
3041
|
-
await maybePromise;
|
|
3042
|
-
}
|
|
3043
|
-
return;
|
|
3044
|
-
}
|
|
3217
|
+
async function closePool(pool) {
|
|
3045
3218
|
await new Promise((resolveClose, rejectClose) => {
|
|
3046
|
-
|
|
3047
|
-
if (error) {
|
|
3048
|
-
rejectClose(error);
|
|
3049
|
-
return;
|
|
3050
|
-
}
|
|
3051
|
-
resolveClose();
|
|
3052
|
-
});
|
|
3219
|
+
pool.end((error) => error ? rejectClose(error) : resolveClose());
|
|
3053
3220
|
});
|
|
3054
3221
|
}
|
|
3055
|
-
function isPromiseLike2(value) {
|
|
3056
|
-
return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
|
|
3057
|
-
}
|
|
3058
3222
|
|
|
3059
3223
|
// src/sqlite.ts
|
|
3060
3224
|
import { resolve as resolve5 } from "path";
|
|
3061
3225
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
3226
|
+
function isInMemory(dbPath) {
|
|
3227
|
+
return dbPath === ":memory:" || dbPath === "" || dbPath.startsWith("file::memory:");
|
|
3228
|
+
}
|
|
3062
3229
|
function createSqliteDatabase(options) {
|
|
3063
3230
|
const { migrationsFolder, filename, seedersFolder, relations } = options;
|
|
3064
3231
|
const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath4(migrationsFolder) : resolve5(String(migrationsFolder));
|
|
@@ -3066,6 +3233,8 @@ function createSqliteDatabase(options) {
|
|
|
3066
3233
|
let db;
|
|
3067
3234
|
let sqliteClient;
|
|
3068
3235
|
let migrationsPromise;
|
|
3236
|
+
let activeKey;
|
|
3237
|
+
const callSite = new Error().stack;
|
|
3069
3238
|
function resolveFilename() {
|
|
3070
3239
|
const value = typeof filename === "function" ? filename() : filename;
|
|
3071
3240
|
return value ?? process.env.DATABASE_URL ?? "./data/guren.db";
|
|
@@ -3084,8 +3253,27 @@ function createSqliteDatabase(options) {
|
|
|
3084
3253
|
sqlite.exec("PRAGMA journal_mode = WAL;");
|
|
3085
3254
|
sqliteClient = sqlite;
|
|
3086
3255
|
const { drizzle } = await import("drizzle-orm/bun-sqlite");
|
|
3087
|
-
|
|
3088
|
-
|
|
3256
|
+
const database2 = drizzle({ client: sqlite, ...relations ? { relations } : {} });
|
|
3257
|
+
db = database2;
|
|
3258
|
+
activeKey = isInMemory(dbPath) ? void 0 : hotReloadKey("sqlite", callSite, resolve5(dbPath));
|
|
3259
|
+
if (activeKey) {
|
|
3260
|
+
await replaceActiveConnection(activeKey, closeDatabase);
|
|
3261
|
+
}
|
|
3262
|
+
return database2;
|
|
3263
|
+
}
|
|
3264
|
+
async function closeDatabase() {
|
|
3265
|
+
if (!db) return;
|
|
3266
|
+
const key = activeKey;
|
|
3267
|
+
activeKey = void 0;
|
|
3268
|
+
try {
|
|
3269
|
+
sqliteClient?.close();
|
|
3270
|
+
} finally {
|
|
3271
|
+
db = void 0;
|
|
3272
|
+
sqliteClient = void 0;
|
|
3273
|
+
if (key) {
|
|
3274
|
+
releaseActiveConnection(key, closeDatabase);
|
|
3275
|
+
}
|
|
3276
|
+
}
|
|
3089
3277
|
}
|
|
3090
3278
|
async function migrateOnce() {
|
|
3091
3279
|
if (migrationsPromise) return migrationsPromise;
|
|
@@ -3100,8 +3288,7 @@ function createSqliteDatabase(options) {
|
|
|
3100
3288
|
})();
|
|
3101
3289
|
migrationsPromise = migrationsPromise.catch((error) => {
|
|
3102
3290
|
migrationsPromise = void 0;
|
|
3103
|
-
|
|
3104
|
-
throw new Error(`Failed to run database migrations: ${reason}`);
|
|
3291
|
+
throw migrationFailure(error);
|
|
3105
3292
|
});
|
|
3106
3293
|
await migrationsPromise;
|
|
3107
3294
|
}
|
|
@@ -3111,11 +3298,7 @@ function createSqliteDatabase(options) {
|
|
|
3111
3298
|
return ensureDatabase2();
|
|
3112
3299
|
},
|
|
3113
3300
|
migrateDatabase: migrateOnce,
|
|
3114
|
-
|
|
3115
|
-
if (!db) return;
|
|
3116
|
-
db = void 0;
|
|
3117
|
-
sqliteClient = void 0;
|
|
3118
|
-
},
|
|
3301
|
+
closeDatabase,
|
|
3119
3302
|
async resetDatabase() {
|
|
3120
3303
|
await ensureDatabase2();
|
|
3121
3304
|
if (!sqliteClient) return;
|
|
@@ -3152,13 +3335,250 @@ function createSqliteDatabase(options) {
|
|
|
3152
3335
|
throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createSqliteDatabase().');
|
|
3153
3336
|
}
|
|
3154
3337
|
const database2 = await ensureDatabase2();
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
|
|
3338
|
+
try {
|
|
3339
|
+
await runSeeders(
|
|
3340
|
+
database2,
|
|
3341
|
+
resolvedSeedersFolder
|
|
3342
|
+
);
|
|
3343
|
+
} catch (error) {
|
|
3344
|
+
throw seedFailure(error);
|
|
3345
|
+
}
|
|
3346
|
+
}
|
|
3347
|
+
};
|
|
3348
|
+
}
|
|
3349
|
+
|
|
3350
|
+
// src/d1.ts
|
|
3351
|
+
import { relative } from "path";
|
|
3352
|
+
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
3353
|
+
function createD1Database(options) {
|
|
3354
|
+
const { binding, migrationsFolder, relations } = options;
|
|
3355
|
+
const migrationsHint = migrationsFolder == null ? "db/migrations" : migrationsFolder instanceof URL ? relative(process.cwd(), fileURLToPath5(migrationsFolder)) : migrationsFolder;
|
|
3356
|
+
let databasePromise;
|
|
3357
|
+
function ensureDatabase2() {
|
|
3358
|
+
if (databasePromise) return databasePromise;
|
|
3359
|
+
const promise = (async () => {
|
|
3360
|
+
const client = binding();
|
|
3361
|
+
if (client == null) {
|
|
3362
|
+
throw new Error(
|
|
3363
|
+
'createD1Database: the "binding" resolver returned no D1 binding. On Workers this usually means it ran before the first request \u2014 defer access (e.g. binding: () => getWorkersEnv<Env>().DB) and check the d1_databases entry in wrangler.jsonc.'
|
|
3364
|
+
);
|
|
3365
|
+
}
|
|
3366
|
+
const { drizzle } = await import("drizzle-orm/d1");
|
|
3367
|
+
return drizzle(client, relations ? { relations } : void 0);
|
|
3368
|
+
})();
|
|
3369
|
+
databasePromise = promise.catch((error) => {
|
|
3370
|
+
databasePromise = void 0;
|
|
3371
|
+
throw error;
|
|
3372
|
+
});
|
|
3373
|
+
return databasePromise;
|
|
3374
|
+
}
|
|
3375
|
+
return {
|
|
3376
|
+
getDatabase: ensureDatabase2,
|
|
3377
|
+
async migrateDatabase() {
|
|
3378
|
+
throw new Error(
|
|
3379
|
+
`D1 migrations are not applied at runtime. Run \`wrangler d1 migrations apply <database>\` (local: add --local) with d1_databases[].migrations_dir pointing at ${migrationsHint}.`
|
|
3380
|
+
);
|
|
3381
|
+
},
|
|
3382
|
+
async closeDatabase() {
|
|
3383
|
+
databasePromise = void 0;
|
|
3384
|
+
},
|
|
3385
|
+
async configureOrm() {
|
|
3386
|
+
const database2 = await ensureDatabase2();
|
|
3387
|
+
DrizzleAdapter.configure(database2);
|
|
3388
|
+
},
|
|
3389
|
+
async seedDatabase() {
|
|
3390
|
+
throw new Error(
|
|
3391
|
+
"D1 seeding runs outside the Worker: generate SQL and apply it with `wrangler d1 execute <database> --file <seed.sql>` (local: add --local)."
|
|
3158
3392
|
);
|
|
3393
|
+
},
|
|
3394
|
+
async resetDatabase() {
|
|
3395
|
+
throw new Error(
|
|
3396
|
+
"D1 databases are reset with wrangler, not at runtime: delete and recreate the database (`wrangler d1 delete` / `wrangler d1 create`), then re-apply migrations with `wrangler d1 migrations apply`."
|
|
3397
|
+
);
|
|
3398
|
+
},
|
|
3399
|
+
async migrationStatus() {
|
|
3400
|
+
throw new Error(
|
|
3401
|
+
"Wrangler's migration tracker is authoritative for D1. Use `wrangler d1 migrations list <database>` instead."
|
|
3402
|
+
);
|
|
3403
|
+
}
|
|
3404
|
+
};
|
|
3405
|
+
}
|
|
3406
|
+
|
|
3407
|
+
// src/aws-data-api.ts
|
|
3408
|
+
import { resolve as resolve6 } from "path";
|
|
3409
|
+
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
3410
|
+
async function loadAwsDataApiModules() {
|
|
3411
|
+
try {
|
|
3412
|
+
const [{ drizzle }, { migrate }] = await Promise.all([
|
|
3413
|
+
import("drizzle-orm/aws-data-api/pg"),
|
|
3414
|
+
import("drizzle-orm/aws-data-api/pg/migrator")
|
|
3415
|
+
]);
|
|
3416
|
+
return { drizzle, migrate };
|
|
3417
|
+
} catch (error) {
|
|
3418
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
3419
|
+
throw new Error(
|
|
3420
|
+
`createAwsDataApiDatabase() requires the "@aws-sdk/client-rds-data" package. Install it with \`bun add @aws-sdk/client-rds-data\`. (${reason})`
|
|
3421
|
+
);
|
|
3422
|
+
}
|
|
3423
|
+
}
|
|
3424
|
+
function createAwsDataApiDatabase(options) {
|
|
3425
|
+
const { migrationsFolder, database: database2, resourceArn, secretArn, clientOptions, migrateOnStart, seedersFolder, relations } = options;
|
|
3426
|
+
const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath6(migrationsFolder) : resolve6(String(migrationsFolder));
|
|
3427
|
+
const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath6(seedersFolder) : resolve6(String(seedersFolder));
|
|
3428
|
+
let migrationsPromise;
|
|
3429
|
+
let databasePromise;
|
|
3430
|
+
let client;
|
|
3431
|
+
let activeKey;
|
|
3432
|
+
const callSite = new Error().stack;
|
|
3433
|
+
function resolveConnection() {
|
|
3434
|
+
const resolveValue = (value, envKey) => {
|
|
3435
|
+
const resolved = typeof value === "function" ? value() : value;
|
|
3436
|
+
return resolved ?? process.env[envKey];
|
|
3437
|
+
};
|
|
3438
|
+
const resolvedDatabase = resolveValue(database2, "DATABASE_NAME");
|
|
3439
|
+
const resolvedResourceArn = resolveValue(resourceArn, "DATABASE_RESOURCE_ARN");
|
|
3440
|
+
const resolvedSecretArn = resolveValue(secretArn, "DATABASE_SECRET_ARN");
|
|
3441
|
+
const missing = [
|
|
3442
|
+
resolvedDatabase ? null : "database (DATABASE_NAME)",
|
|
3443
|
+
resolvedResourceArn ? null : "resourceArn (DATABASE_RESOURCE_ARN)",
|
|
3444
|
+
resolvedSecretArn ? null : "secretArn (DATABASE_SECRET_ARN)"
|
|
3445
|
+
].filter((entry) => entry !== null);
|
|
3446
|
+
if (missing.length > 0) {
|
|
3447
|
+
throw new Error(`Missing AWS Data API connection settings: ${missing.join(", ")}.`);
|
|
3448
|
+
}
|
|
3449
|
+
return { database: resolvedDatabase, resourceArn: resolvedResourceArn, secretArn: resolvedSecretArn };
|
|
3450
|
+
}
|
|
3451
|
+
function buildDrizzleConfig(connection) {
|
|
3452
|
+
return {
|
|
3453
|
+
connection: {
|
|
3454
|
+
...clientOptions,
|
|
3455
|
+
...connection
|
|
3456
|
+
},
|
|
3457
|
+
...relations ? { relations } : {}
|
|
3458
|
+
};
|
|
3459
|
+
}
|
|
3460
|
+
async function migrateOnce() {
|
|
3461
|
+
if (migrationsPromise) {
|
|
3462
|
+
return migrationsPromise;
|
|
3463
|
+
}
|
|
3464
|
+
const promise = (async () => {
|
|
3465
|
+
if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
|
|
3466
|
+
warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
|
|
3467
|
+
return;
|
|
3468
|
+
}
|
|
3469
|
+
const { migrate } = await loadAwsDataApiModules();
|
|
3470
|
+
await withAdminDb((db) => migrate(db, { migrationsFolder: resolvedMigrationsFolder }));
|
|
3471
|
+
})();
|
|
3472
|
+
migrationsPromise = promise.catch((error) => {
|
|
3473
|
+
migrationsPromise = void 0;
|
|
3474
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
3475
|
+
throw new Error(`Failed to run database migrations: ${reason}`);
|
|
3476
|
+
});
|
|
3477
|
+
await migrationsPromise;
|
|
3478
|
+
}
|
|
3479
|
+
async function getDatabase() {
|
|
3480
|
+
if (databasePromise) {
|
|
3481
|
+
return databasePromise;
|
|
3159
3482
|
}
|
|
3483
|
+
const promise = (async () => {
|
|
3484
|
+
if (migrateOnStart) {
|
|
3485
|
+
await migrateOnce();
|
|
3486
|
+
}
|
|
3487
|
+
const { drizzle } = await loadAwsDataApiModules();
|
|
3488
|
+
const connection = resolveConnection();
|
|
3489
|
+
const db = drizzle(buildDrizzleConfig(connection));
|
|
3490
|
+
client = db.$client;
|
|
3491
|
+
activeKey = hotReloadKey("aws-data-api", callSite, `${connection.resourceArn}/${connection.database}`);
|
|
3492
|
+
if (activeKey) {
|
|
3493
|
+
await replaceActiveConnection(activeKey, closeDatabase);
|
|
3494
|
+
}
|
|
3495
|
+
return db;
|
|
3496
|
+
})();
|
|
3497
|
+
databasePromise = promise.catch((error) => {
|
|
3498
|
+
databasePromise = void 0;
|
|
3499
|
+
throw error;
|
|
3500
|
+
});
|
|
3501
|
+
return databasePromise;
|
|
3502
|
+
}
|
|
3503
|
+
async function closeDatabase() {
|
|
3504
|
+
if (!client) {
|
|
3505
|
+
return;
|
|
3506
|
+
}
|
|
3507
|
+
const key = activeKey;
|
|
3508
|
+
activeKey = void 0;
|
|
3509
|
+
try {
|
|
3510
|
+
client.destroy?.();
|
|
3511
|
+
} finally {
|
|
3512
|
+
client = void 0;
|
|
3513
|
+
databasePromise = void 0;
|
|
3514
|
+
if (key) {
|
|
3515
|
+
releaseActiveConnection(key, closeDatabase);
|
|
3516
|
+
}
|
|
3517
|
+
}
|
|
3518
|
+
}
|
|
3519
|
+
async function configureOrm() {
|
|
3520
|
+
const db = await getDatabase();
|
|
3521
|
+
DrizzleAdapter.configure(db);
|
|
3522
|
+
}
|
|
3523
|
+
async function seedDatabase() {
|
|
3524
|
+
if (!resolvedSeedersFolder) {
|
|
3525
|
+
throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createAwsDataApiDatabase().');
|
|
3526
|
+
}
|
|
3527
|
+
const db = await getDatabase();
|
|
3528
|
+
await runSeeders(db, resolvedSeedersFolder);
|
|
3529
|
+
}
|
|
3530
|
+
async function withAdminDb(callback) {
|
|
3531
|
+
const { drizzle } = await loadAwsDataApiModules();
|
|
3532
|
+
const adminDb = drizzle(buildDrizzleConfig(resolveConnection()));
|
|
3533
|
+
try {
|
|
3534
|
+
return await callback(adminDb);
|
|
3535
|
+
} finally {
|
|
3536
|
+
adminDb.$client?.destroy?.();
|
|
3537
|
+
}
|
|
3538
|
+
}
|
|
3539
|
+
async function resetDatabase() {
|
|
3540
|
+
const { sql } = await import("drizzle-orm");
|
|
3541
|
+
await withAdminDb(async (adminDb) => {
|
|
3542
|
+
await adminDb.execute(sql.raw("DROP SCHEMA IF EXISTS public CASCADE"));
|
|
3543
|
+
await adminDb.execute(sql.raw("CREATE SCHEMA public"));
|
|
3544
|
+
await adminDb.execute(sql.raw("DROP SCHEMA IF EXISTS drizzle CASCADE"));
|
|
3545
|
+
});
|
|
3546
|
+
migrationsPromise = void 0;
|
|
3547
|
+
}
|
|
3548
|
+
async function migrationStatus() {
|
|
3549
|
+
const localMigrations = listLocalMigrations(resolvedMigrationsFolder);
|
|
3550
|
+
if (localMigrations.length === 0) return [];
|
|
3551
|
+
const { sql } = await import("drizzle-orm");
|
|
3552
|
+
const appliedRows = await withAdminDb(async (adminDb) => {
|
|
3553
|
+
try {
|
|
3554
|
+
const result = await adminDb.execute(
|
|
3555
|
+
sql.raw("SELECT name FROM drizzle.__drizzle_migrations")
|
|
3556
|
+
);
|
|
3557
|
+
const rows = Array.isArray(result) ? result : result.rows ?? [];
|
|
3558
|
+
return rows.map((row) => ({ name: row.name, appliedAt: null }));
|
|
3559
|
+
} catch (error) {
|
|
3560
|
+
if (isMissingTrackerTableError(error)) {
|
|
3561
|
+
return [];
|
|
3562
|
+
}
|
|
3563
|
+
throw error;
|
|
3564
|
+
}
|
|
3565
|
+
});
|
|
3566
|
+
return buildMigrationStatus(localMigrations, appliedRows);
|
|
3567
|
+
}
|
|
3568
|
+
return {
|
|
3569
|
+
getDatabase,
|
|
3570
|
+
migrateDatabase: migrateOnce,
|
|
3571
|
+
closeDatabase,
|
|
3572
|
+
configureOrm,
|
|
3573
|
+
seedDatabase,
|
|
3574
|
+
resetDatabase,
|
|
3575
|
+
migrationStatus
|
|
3160
3576
|
};
|
|
3161
3577
|
}
|
|
3578
|
+
function isMissingTrackerTableError(error) {
|
|
3579
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
3580
|
+
return /does not exist/i.test(message) && /drizzle|__drizzle_migrations|schema/i.test(message);
|
|
3581
|
+
}
|
|
3162
3582
|
export {
|
|
3163
3583
|
DrizzleAdapter,
|
|
3164
3584
|
GlobalScopeRegistry,
|
|
@@ -3170,6 +3590,8 @@ export {
|
|
|
3170
3590
|
applyAccessors,
|
|
3171
3591
|
applyMutators,
|
|
3172
3592
|
buildDrizzleConditions,
|
|
3593
|
+
createAwsDataApiDatabase,
|
|
3594
|
+
createD1Database,
|
|
3173
3595
|
createMySqlDatabase,
|
|
3174
3596
|
createPostgresDatabase,
|
|
3175
3597
|
createSqliteDatabase,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@guren/orm",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -40,10 +40,14 @@
|
|
|
40
40
|
"drizzle-orm": "1.0.0-rc.4"
|
|
41
41
|
},
|
|
42
42
|
"peerDependencies": {
|
|
43
|
+
"@aws-sdk/client-rds-data": "^3.0.0",
|
|
43
44
|
"mysql2": "^3.11.3",
|
|
44
45
|
"postgres": "^3.4.3"
|
|
45
46
|
},
|
|
46
47
|
"peerDependenciesMeta": {
|
|
48
|
+
"@aws-sdk/client-rds-data": {
|
|
49
|
+
"optional": true
|
|
50
|
+
},
|
|
47
51
|
"mysql2": {
|
|
48
52
|
"optional": true
|
|
49
53
|
},
|
|
@@ -52,6 +56,7 @@
|
|
|
52
56
|
}
|
|
53
57
|
},
|
|
54
58
|
"devDependencies": {
|
|
59
|
+
"@aws-sdk/client-rds-data": "^3.0.0",
|
|
55
60
|
"@types/node": "^20.14.10",
|
|
56
61
|
"mysql2": "^3.11.3",
|
|
57
62
|
"postgres": "^3.4.3",
|