@guren/orm 1.2.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 +50 -7
- package/dist/index.js +311 -77
- 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.*`).
|
|
@@ -1632,6 +1634,47 @@ interface D1DatabaseHandle {
|
|
|
1632
1634
|
*/
|
|
1633
1635
|
declare function createD1Database(options: D1DatabaseOptions): D1DatabaseHandle;
|
|
1634
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
|
+
|
|
1635
1678
|
interface SeederContext {
|
|
1636
1679
|
db: PostgresJsDatabase;
|
|
1637
1680
|
}
|
|
@@ -1654,4 +1697,4 @@ declare function serializeRecord(record: PlainObject, options: {
|
|
|
1654
1697
|
/** Serialize an array of records. */
|
|
1655
1698
|
declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
|
|
1656
1699
|
|
|
1657
|
-
export { type AccessorDefinitions, type AccessorFn, 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, createD1Database, 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
|
@@ -2696,6 +2696,76 @@ function warnIgnoredFlatSqlMigrations(migrationsFolder) {
|
|
|
2696
2696
|
);
|
|
2697
2697
|
}
|
|
2698
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
|
+
}
|
|
2699
2769
|
function listLocalMigrations(migrationsFolder) {
|
|
2700
2770
|
if (!existsSync(migrationsFolder)) {
|
|
2701
2771
|
return [];
|
|
@@ -2830,6 +2900,7 @@ function createPostgresDatabase(options) {
|
|
|
2830
2900
|
if (migrationsPromise) {
|
|
2831
2901
|
return migrationsPromise;
|
|
2832
2902
|
}
|
|
2903
|
+
let endpoint;
|
|
2833
2904
|
const promise = (async () => {
|
|
2834
2905
|
if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
|
|
2835
2906
|
warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
|
|
@@ -2837,6 +2908,7 @@ function createPostgresDatabase(options) {
|
|
|
2837
2908
|
}
|
|
2838
2909
|
const { drizzle, migrate, postgres: postgresFactory } = await loadPostgresModules();
|
|
2839
2910
|
const url = resolveConnectionString();
|
|
2911
|
+
endpoint = describeConnectionEndpoint(url);
|
|
2840
2912
|
const migrationClient = postgresFactory(url, {
|
|
2841
2913
|
max: 1,
|
|
2842
2914
|
...clientOptions
|
|
@@ -2850,8 +2922,7 @@ function createPostgresDatabase(options) {
|
|
|
2850
2922
|
})();
|
|
2851
2923
|
migrationsPromise = promise.catch((error) => {
|
|
2852
2924
|
migrationsPromise = void 0;
|
|
2853
|
-
|
|
2854
|
-
throw new Error(`Failed to run database migrations: ${reason}`);
|
|
2925
|
+
throw migrationFailure(error, endpoint);
|
|
2855
2926
|
});
|
|
2856
2927
|
await migrationsPromise;
|
|
2857
2928
|
}
|
|
@@ -2908,16 +2979,23 @@ function createPostgresDatabase(options) {
|
|
|
2908
2979
|
throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createPostgresDatabase().');
|
|
2909
2980
|
}
|
|
2910
2981
|
const db = await getDatabase();
|
|
2911
|
-
|
|
2982
|
+
try {
|
|
2983
|
+
await runSeeders(db, resolvedSeedersFolder);
|
|
2984
|
+
} catch (error) {
|
|
2985
|
+
throw seedFailure(error, describeConnectionEndpoint(resolveConnectionString()));
|
|
2986
|
+
}
|
|
2912
2987
|
}
|
|
2913
2988
|
async function withAdminClient(callback) {
|
|
2914
2989
|
const { postgres: postgresFactory } = await loadPostgresModules();
|
|
2915
|
-
const
|
|
2990
|
+
const url = resolveConnectionString();
|
|
2991
|
+
const adminClient = postgresFactory(url, {
|
|
2916
2992
|
max: 1,
|
|
2917
2993
|
...clientOptions
|
|
2918
2994
|
});
|
|
2919
2995
|
try {
|
|
2920
2996
|
return await callback(adminClient);
|
|
2997
|
+
} catch (error) {
|
|
2998
|
+
throw new Error(describeDatabaseFailure(error, describeConnectionEndpoint(url)));
|
|
2921
2999
|
} finally {
|
|
2922
3000
|
await adminClient.end({ timeout: 0 });
|
|
2923
3001
|
}
|
|
@@ -2940,7 +3018,8 @@ function createPostgresDatabase(options) {
|
|
|
2940
3018
|
const record = row;
|
|
2941
3019
|
return { name: record.name, appliedAt: null };
|
|
2942
3020
|
});
|
|
2943
|
-
} catch {
|
|
3021
|
+
} catch (error) {
|
|
3022
|
+
if (isConnectionFailure(error)) throw error;
|
|
2944
3023
|
return [];
|
|
2945
3024
|
}
|
|
2946
3025
|
});
|
|
@@ -2962,11 +3041,12 @@ import { resolve as resolve4 } from "path";
|
|
|
2962
3041
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
2963
3042
|
async function loadMySqlModules() {
|
|
2964
3043
|
try {
|
|
2965
|
-
const [{ drizzle }, { migrate }] = await Promise.all([
|
|
3044
|
+
const [{ drizzle }, { migrate }, { createPool }] = await Promise.all([
|
|
2966
3045
|
import("drizzle-orm/mysql2"),
|
|
2967
|
-
import("drizzle-orm/mysql2/migrator")
|
|
3046
|
+
import("drizzle-orm/mysql2/migrator"),
|
|
3047
|
+
import("mysql2")
|
|
2968
3048
|
]);
|
|
2969
|
-
return { drizzle, migrate };
|
|
3049
|
+
return { drizzle, migrate, createPool };
|
|
2970
3050
|
} catch (error) {
|
|
2971
3051
|
const reason = error instanceof Error ? error.message : String(error);
|
|
2972
3052
|
throw new Error(
|
|
@@ -2980,7 +3060,7 @@ function createMySqlDatabase(options) {
|
|
|
2980
3060
|
const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath3(seedersFolder) : resolve4(String(seedersFolder));
|
|
2981
3061
|
let migrationsPromise;
|
|
2982
3062
|
let databasePromise;
|
|
2983
|
-
let
|
|
3063
|
+
let client;
|
|
2984
3064
|
let activeKey;
|
|
2985
3065
|
const callSite = new Error().stack;
|
|
2986
3066
|
function resolveConnectionString() {
|
|
@@ -2995,31 +3075,29 @@ function createMySqlDatabase(options) {
|
|
|
2995
3075
|
if (migrationsPromise) {
|
|
2996
3076
|
return migrationsPromise;
|
|
2997
3077
|
}
|
|
3078
|
+
let endpoint;
|
|
2998
3079
|
const promise = (async () => {
|
|
2999
3080
|
if (!hasDrizzleMigrations(resolvedMigrationsFolder)) {
|
|
3000
3081
|
warnIgnoredFlatSqlMigrations(resolvedMigrationsFolder);
|
|
3001
3082
|
return;
|
|
3002
3083
|
}
|
|
3003
|
-
const { drizzle, migrate } = await loadMySqlModules();
|
|
3084
|
+
const { drizzle, migrate, createPool } = await loadMySqlModules();
|
|
3004
3085
|
const url = resolveConnectionString();
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
uri: url,
|
|
3008
|
-
...clientOptions
|
|
3009
|
-
},
|
|
3010
|
-
mode: "default",
|
|
3011
|
-
...relations ? { relations } : {}
|
|
3012
|
-
});
|
|
3086
|
+
endpoint = describeConnectionEndpoint(url);
|
|
3087
|
+
const migrationClient = createPool({ uri: url, ...clientOptions });
|
|
3013
3088
|
try {
|
|
3089
|
+
const migrationDb = drizzle({
|
|
3090
|
+
client: migrationClient,
|
|
3091
|
+
...relations ? { relations } : {}
|
|
3092
|
+
});
|
|
3014
3093
|
await migrate(migrationDb, { migrationsFolder: resolvedMigrationsFolder });
|
|
3015
3094
|
} finally {
|
|
3016
|
-
await
|
|
3095
|
+
await closePool(migrationClient);
|
|
3017
3096
|
}
|
|
3018
3097
|
})();
|
|
3019
3098
|
migrationsPromise = promise.catch((error) => {
|
|
3020
3099
|
migrationsPromise = void 0;
|
|
3021
|
-
|
|
3022
|
-
throw new Error(`Failed to run database migrations: ${reason}`);
|
|
3100
|
+
throw migrationFailure(error, endpoint);
|
|
3023
3101
|
});
|
|
3024
3102
|
await migrationsPromise;
|
|
3025
3103
|
}
|
|
@@ -3029,22 +3107,18 @@ function createMySqlDatabase(options) {
|
|
|
3029
3107
|
}
|
|
3030
3108
|
const promise = (async () => {
|
|
3031
3109
|
await migrateOnce();
|
|
3032
|
-
const { drizzle } = await loadMySqlModules();
|
|
3110
|
+
const { drizzle, createPool } = await loadMySqlModules();
|
|
3033
3111
|
const url = resolveConnectionString();
|
|
3034
|
-
const
|
|
3035
|
-
|
|
3036
|
-
uri: url,
|
|
3037
|
-
...clientOptions
|
|
3038
|
-
},
|
|
3039
|
-
mode: "default",
|
|
3040
|
-
...relations ? { relations } : {}
|
|
3041
|
-
});
|
|
3042
|
-
database2 = db;
|
|
3112
|
+
const activeClient = createPool({ uri: url, ...clientOptions });
|
|
3113
|
+
client = activeClient;
|
|
3043
3114
|
activeKey = hotReloadKey("mysql", callSite, url);
|
|
3044
3115
|
if (activeKey) {
|
|
3045
3116
|
await replaceActiveConnection(activeKey, closeDatabase);
|
|
3046
3117
|
}
|
|
3047
|
-
return
|
|
3118
|
+
return drizzle({
|
|
3119
|
+
client: activeClient,
|
|
3120
|
+
...relations ? { relations } : {}
|
|
3121
|
+
});
|
|
3048
3122
|
})();
|
|
3049
3123
|
databasePromise = promise.catch((error) => {
|
|
3050
3124
|
databasePromise = void 0;
|
|
@@ -3053,15 +3127,15 @@ function createMySqlDatabase(options) {
|
|
|
3053
3127
|
return databasePromise;
|
|
3054
3128
|
}
|
|
3055
3129
|
async function closeDatabase() {
|
|
3056
|
-
if (!
|
|
3130
|
+
if (!client) {
|
|
3057
3131
|
return;
|
|
3058
3132
|
}
|
|
3059
3133
|
const key = activeKey;
|
|
3060
3134
|
activeKey = void 0;
|
|
3061
3135
|
try {
|
|
3062
|
-
await
|
|
3136
|
+
await closePool(client);
|
|
3063
3137
|
} finally {
|
|
3064
|
-
|
|
3138
|
+
client = void 0;
|
|
3065
3139
|
databasePromise = void 0;
|
|
3066
3140
|
if (key) {
|
|
3067
3141
|
releaseActiveConnection(key, closeDatabase);
|
|
@@ -3077,21 +3151,23 @@ function createMySqlDatabase(options) {
|
|
|
3077
3151
|
throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createMySqlDatabase().');
|
|
3078
3152
|
}
|
|
3079
3153
|
const db = await getDatabase();
|
|
3080
|
-
|
|
3154
|
+
try {
|
|
3155
|
+
await runSeeders(db, resolvedSeedersFolder);
|
|
3156
|
+
} catch (error) {
|
|
3157
|
+
throw seedFailure(error, describeConnectionEndpoint(resolveConnectionString()));
|
|
3158
|
+
}
|
|
3081
3159
|
}
|
|
3082
3160
|
async function withAdminDb(callback) {
|
|
3083
|
-
const { drizzle } = await loadMySqlModules();
|
|
3084
|
-
const
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
...clientOptions
|
|
3088
|
-
},
|
|
3089
|
-
mode: "default"
|
|
3090
|
-
});
|
|
3161
|
+
const { drizzle, createPool } = await loadMySqlModules();
|
|
3162
|
+
const url = resolveConnectionString();
|
|
3163
|
+
const adminClient = createPool({ uri: url, ...clientOptions });
|
|
3164
|
+
const adminDb = drizzle({ client: adminClient });
|
|
3091
3165
|
try {
|
|
3092
3166
|
return await callback(adminDb);
|
|
3167
|
+
} catch (error) {
|
|
3168
|
+
throw new Error(describeDatabaseFailure(error, describeConnectionEndpoint(url)));
|
|
3093
3169
|
} finally {
|
|
3094
|
-
await
|
|
3170
|
+
await closePool(adminClient);
|
|
3095
3171
|
}
|
|
3096
3172
|
}
|
|
3097
3173
|
async function resetDatabase() {
|
|
@@ -3121,7 +3197,8 @@ function createMySqlDatabase(options) {
|
|
|
3121
3197
|
sql.raw("SELECT name, applied_at FROM __drizzle_migrations")
|
|
3122
3198
|
);
|
|
3123
3199
|
return rows.map((row) => ({ name: row.name, appliedAt: row.applied_at }));
|
|
3124
|
-
} catch {
|
|
3200
|
+
} catch (error) {
|
|
3201
|
+
if (isConnectionFailure(error)) throw error;
|
|
3125
3202
|
return [];
|
|
3126
3203
|
}
|
|
3127
3204
|
});
|
|
@@ -3137,34 +3214,11 @@ function createMySqlDatabase(options) {
|
|
|
3137
3214
|
migrationStatus
|
|
3138
3215
|
};
|
|
3139
3216
|
}
|
|
3140
|
-
async function
|
|
3141
|
-
if (typeof db !== "object" || db === null) {
|
|
3142
|
-
return;
|
|
3143
|
-
}
|
|
3144
|
-
const maybeClient = db.$client;
|
|
3145
|
-
if (!maybeClient || typeof maybeClient.end !== "function") {
|
|
3146
|
-
return;
|
|
3147
|
-
}
|
|
3148
|
-
if (maybeClient.end.length === 0) {
|
|
3149
|
-
const maybePromise = maybeClient.end();
|
|
3150
|
-
if (isPromiseLike2(maybePromise)) {
|
|
3151
|
-
await maybePromise;
|
|
3152
|
-
}
|
|
3153
|
-
return;
|
|
3154
|
-
}
|
|
3217
|
+
async function closePool(pool) {
|
|
3155
3218
|
await new Promise((resolveClose, rejectClose) => {
|
|
3156
|
-
|
|
3157
|
-
if (error) {
|
|
3158
|
-
rejectClose(error);
|
|
3159
|
-
return;
|
|
3160
|
-
}
|
|
3161
|
-
resolveClose();
|
|
3162
|
-
});
|
|
3219
|
+
pool.end((error) => error ? rejectClose(error) : resolveClose());
|
|
3163
3220
|
});
|
|
3164
3221
|
}
|
|
3165
|
-
function isPromiseLike2(value) {
|
|
3166
|
-
return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
|
|
3167
|
-
}
|
|
3168
3222
|
|
|
3169
3223
|
// src/sqlite.ts
|
|
3170
3224
|
import { resolve as resolve5 } from "path";
|
|
@@ -3234,8 +3288,7 @@ function createSqliteDatabase(options) {
|
|
|
3234
3288
|
})();
|
|
3235
3289
|
migrationsPromise = migrationsPromise.catch((error) => {
|
|
3236
3290
|
migrationsPromise = void 0;
|
|
3237
|
-
|
|
3238
|
-
throw new Error(`Failed to run database migrations: ${reason}`);
|
|
3291
|
+
throw migrationFailure(error);
|
|
3239
3292
|
});
|
|
3240
3293
|
await migrationsPromise;
|
|
3241
3294
|
}
|
|
@@ -3282,10 +3335,14 @@ function createSqliteDatabase(options) {
|
|
|
3282
3335
|
throw new Error('No seeders folder configured. Provide "seedersFolder" when calling createSqliteDatabase().');
|
|
3283
3336
|
}
|
|
3284
3337
|
const database2 = await ensureDatabase2();
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
|
|
3288
|
-
|
|
3338
|
+
try {
|
|
3339
|
+
await runSeeders(
|
|
3340
|
+
database2,
|
|
3341
|
+
resolvedSeedersFolder
|
|
3342
|
+
);
|
|
3343
|
+
} catch (error) {
|
|
3344
|
+
throw seedFailure(error);
|
|
3345
|
+
}
|
|
3289
3346
|
}
|
|
3290
3347
|
};
|
|
3291
3348
|
}
|
|
@@ -3346,6 +3403,182 @@ function createD1Database(options) {
|
|
|
3346
3403
|
}
|
|
3347
3404
|
};
|
|
3348
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;
|
|
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
|
|
3576
|
+
};
|
|
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
|
+
}
|
|
3349
3582
|
export {
|
|
3350
3583
|
DrizzleAdapter,
|
|
3351
3584
|
GlobalScopeRegistry,
|
|
@@ -3357,6 +3590,7 @@ export {
|
|
|
3357
3590
|
applyAccessors,
|
|
3358
3591
|
applyMutators,
|
|
3359
3592
|
buildDrizzleConditions,
|
|
3593
|
+
createAwsDataApiDatabase,
|
|
3360
3594
|
createD1Database,
|
|
3361
3595
|
createMySqlDatabase,
|
|
3362
3596
|
createPostgresDatabase,
|
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",
|