drizzle-graphql-plus 0.8.32 → 0.8.33

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/index.cjs CHANGED
@@ -1,20 +1,30 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
8
10
  __defProp(target, name, { get: all[name], enumerable: true });
9
11
  };
10
- var __copyProps = (to, from, except, desc3) => {
12
+ var __copyProps = (to, from, except, desc4) => {
11
13
  if (from && typeof from === "object" || typeof from === "function") {
12
14
  for (let key of __getOwnPropNames(from))
13
15
  if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc3 = __getOwnPropDesc(from, key)) || desc3.enumerable });
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc4 = __getOwnPropDesc(from, key)) || desc4.enumerable });
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
@@ -22,6 +32,9 @@ var src_exports = {};
22
32
  __export(src_exports, {
23
33
  buildSchema: () => buildSchema,
24
34
  buildSchemaSDL: () => buildSchemaSDL,
35
+ buildSchemaSDLWithDataLoader: () => buildSchemaSDL2,
36
+ cleanupDataLoaderContext: () => cleanupDataLoaderContext,
37
+ createDataLoaderContext: () => createDataLoaderContext,
25
38
  createExportMiddleware: () => createExportMiddleware,
26
39
  makeScalarAcceptExports: () => makeScalarAcceptExports,
27
40
  setCustomGraphQL: () => setCustomGraphQL,
@@ -2462,13 +2475,13 @@ ${fields.join("\n")}
2462
2475
  );
2463
2476
  const hasDefault = column.hasDefault || column.default !== void 0;
2464
2477
  const isAutoIncrement = column.autoIncrement || column.generatedAlwaysAs;
2465
- const isNotNull3 = column.notNull;
2466
- const shouldBeOptional = hasDefault || isAutoIncrement || isPrimaryKey && !isNotNull3;
2478
+ const isNotNull4 = column.notNull;
2479
+ const shouldBeOptional = hasDefault || isAutoIncrement || isPrimaryKey && !isNotNull4;
2467
2480
  let insertFieldType;
2468
2481
  if (shouldBeOptional) {
2469
2482
  insertFieldType = typeStr.endsWith("!") ? typeStr.slice(0, -1) : typeStr;
2470
2483
  } else {
2471
- insertFieldType = isNotNull3 && !typeStr.endsWith("!") ? `${typeStr}!` : typeStr;
2484
+ insertFieldType = isNotNull4 && !typeStr.endsWith("!") ? `${typeStr}!` : typeStr;
2472
2485
  }
2473
2486
  insertFields.push(` ${columnName}: ${insertFieldType}`);
2474
2487
  }
@@ -3266,6 +3279,1223 @@ var buildSchemaSDL = (db, config) => {
3266
3279
  };
3267
3280
  };
3268
3281
 
3282
+ // src/build-schema-sdl-with-dl/index.ts
3283
+ var import_drizzle_orm19 = require("drizzle-orm");
3284
+ var import_sqlite_core7 = require("drizzle-orm/sqlite-core");
3285
+
3286
+ // src/build-schema-sdl-with-dl/generator/schema/generation.ts
3287
+ var import_drizzle_orm13 = require("drizzle-orm");
3288
+ var generateTypes2 = (db, schema) => {
3289
+ const tables = {};
3290
+ const schemaEntries = Object.entries(schema);
3291
+ const tableEntries = [];
3292
+ for (const [key, value] of schemaEntries) {
3293
+ if (value && typeof value === "object" && "getSQL" in value) {
3294
+ const table = value;
3295
+ const tableName = key;
3296
+ const columns = (0, import_drizzle_orm13.getTableColumns)(table);
3297
+ tables[tableName] = {
3298
+ name: tableName,
3299
+ table,
3300
+ columns
3301
+ };
3302
+ tableEntries.push([tableName, table]);
3303
+ }
3304
+ }
3305
+ const rawRelations = schemaEntries.filter(([key, value]) => (0, import_drizzle_orm13.is)(value, import_drizzle_orm13.Relations)).map(([key, value]) => [
3306
+ tableEntries.find(
3307
+ ([tableName, tableValue]) => tableValue === value.table
3308
+ )[0],
3309
+ value
3310
+ ]).map(([tableName, relValue]) => [
3311
+ tableName,
3312
+ relValue.config((0, import_drizzle_orm13.createTableRelationsHelpers)(tables[tableName].table))
3313
+ ]);
3314
+ const namedRelations = Object.fromEntries(
3315
+ rawRelations.map(([relName, config]) => {
3316
+ const namedConfig = Object.fromEntries(
3317
+ Object.entries(config).map(([innerRelName, innerRelValue]) => [
3318
+ innerRelName,
3319
+ {
3320
+ relation: innerRelValue,
3321
+ targetTableName: tableEntries.find(
3322
+ ([tableName, tableValue]) => tableValue === innerRelValue.referencedTable
3323
+ )[0]
3324
+ }
3325
+ ])
3326
+ );
3327
+ return [relName, namedConfig];
3328
+ })
3329
+ );
3330
+ return { tables, relations: namedRelations };
3331
+ };
3332
+
3333
+ // src/build-schema-sdl-with-dl/generator/schema/type-defs.ts
3334
+ var import_drizzle_orm14 = require("drizzle-orm");
3335
+ var import_mysql_core5 = require("drizzle-orm/mysql-core");
3336
+ var import_pg_core5 = require("drizzle-orm/pg-core");
3337
+ var import_sqlite_core6 = require("drizzle-orm/sqlite-core");
3338
+ var allowedNameChars3 = /^[a-zA-Z0-9_]+$/;
3339
+ var customScalars2 = /* @__PURE__ */ new Set();
3340
+ var enumDefinitions2 = /* @__PURE__ */ new Map();
3341
+ var requiredFieldFilters2 = /* @__PURE__ */ new Set();
3342
+ var foreignKeyTypes2 = /* @__PURE__ */ new Map();
3343
+ var columnToSDL2 = (column, columnName, tableName, forceNullable = false, isPrimaryKey = false) => {
3344
+ let baseType;
3345
+ if (column.customGraphqlType) {
3346
+ baseType = column.customGraphqlType;
3347
+ } else if (isPrimaryKey) {
3348
+ baseType = "ID";
3349
+ } else {
3350
+ const foreignKeyType = foreignKeyTypes2.get(`${tableName}.${columnName}`);
3351
+ if (foreignKeyType) {
3352
+ baseType = foreignKeyType;
3353
+ } else {
3354
+ switch (column.dataType) {
3355
+ case "boolean":
3356
+ baseType = "Boolean";
3357
+ break;
3358
+ case "json":
3359
+ if (column.columnType === "PgGeometryObject") {
3360
+ baseType = "PgGeometryObject";
3361
+ customScalars2.add("PgGeometryObject");
3362
+ } else {
3363
+ baseType = "JSON";
3364
+ customScalars2.add("JSON");
3365
+ }
3366
+ break;
3367
+ case "date":
3368
+ baseType = "Date";
3369
+ customScalars2.add("Date");
3370
+ break;
3371
+ case "string":
3372
+ if (column.enumValues?.length) {
3373
+ const enumName = `${capitalize(tableName)}${capitalize(
3374
+ columnName
3375
+ )}Enum`;
3376
+ baseType = enumName;
3377
+ if (!enumDefinitions2.has(enumName)) {
3378
+ enumDefinitions2.set(enumName, {
3379
+ name: enumName,
3380
+ values: column.enumValues.map(
3381
+ (e, index) => allowedNameChars3.test(e) ? e : `Option${index}`
3382
+ )
3383
+ });
3384
+ }
3385
+ } else {
3386
+ baseType = "String";
3387
+ }
3388
+ break;
3389
+ case "bigint":
3390
+ baseType = "BigInt";
3391
+ customScalars2.add("BigInt");
3392
+ break;
3393
+ case "number":
3394
+ if ((0, import_drizzle_orm14.is)(column, import_pg_core5.PgInteger) || (0, import_drizzle_orm14.is)(column, import_pg_core5.PgSerial) || (0, import_drizzle_orm14.is)(column, import_mysql_core5.MySqlInt) || (0, import_drizzle_orm14.is)(column, import_mysql_core5.MySqlSerial) || (0, import_drizzle_orm14.is)(column, import_sqlite_core6.SQLiteInteger)) {
3395
+ baseType = "Int";
3396
+ } else {
3397
+ baseType = "Float";
3398
+ }
3399
+ break;
3400
+ case "buffer":
3401
+ baseType = "[Int!]";
3402
+ break;
3403
+ case "array":
3404
+ if (column.columnType === "PgVector") {
3405
+ baseType = "[Float!]";
3406
+ } else if (column.columnType === "PgGeometry") {
3407
+ baseType = "[Float!]";
3408
+ } else {
3409
+ const scalarName = `${capitalize(tableName)}${capitalize(
3410
+ columnName
3411
+ )}Array`;
3412
+ baseType = scalarName;
3413
+ customScalars2.add(scalarName);
3414
+ }
3415
+ break;
3416
+ case "custom":
3417
+ default:
3418
+ if (column.columnType) {
3419
+ baseType = column.columnType;
3420
+ customScalars2.add(column.columnType);
3421
+ } else {
3422
+ const customScalarName = `${capitalize(tableName)}${capitalize(
3423
+ columnName
3424
+ )}`;
3425
+ baseType = customScalarName;
3426
+ customScalars2.add(customScalarName);
3427
+ }
3428
+ break;
3429
+ }
3430
+ }
3431
+ }
3432
+ if (!forceNullable && column.notNull) {
3433
+ return `${baseType}!`;
3434
+ }
3435
+ return baseType;
3436
+ };
3437
+ var generateTypeDefs2 = (tables, relations) => {
3438
+ const typeDefs = [];
3439
+ customScalars2.clear();
3440
+ enumDefinitions2.clear();
3441
+ requiredFieldFilters2.clear();
3442
+ foreignKeyTypes2.clear();
3443
+ for (const [tableName, tableRelations] of Object.entries(relations)) {
3444
+ const tableInfo = tables[tableName];
3445
+ if (!tableInfo)
3446
+ continue;
3447
+ for (const [relationName, relationInfo] of Object.entries(tableRelations)) {
3448
+ const relation = relationInfo.relation;
3449
+ if (!(0, import_drizzle_orm14.is)(relation, import_drizzle_orm14.One))
3450
+ continue;
3451
+ const config = relation.config;
3452
+ if (!config?.fields || !config?.references)
3453
+ continue;
3454
+ const referencedTableName = relationInfo.targetTableName;
3455
+ const referencedTable = tables[referencedTableName];
3456
+ if (!referencedTable)
3457
+ continue;
3458
+ for (let i = 0; i < config.fields.length; i++) {
3459
+ const field = config.fields[i];
3460
+ const reference = config.references[i];
3461
+ if (!field || !reference)
3462
+ continue;
3463
+ const fieldColumnName = field.name;
3464
+ const referenceColumnName = reference.name;
3465
+ const foreignKeyColumn = Object.values(tableInfo.columns).find(
3466
+ (col) => col.name === fieldColumnName
3467
+ );
3468
+ const referencedColumn = Object.values(referencedTable.columns).find(
3469
+ (col) => col.name === referenceColumnName
3470
+ );
3471
+ if (!foreignKeyColumn || !referencedColumn)
3472
+ continue;
3473
+ const foreignKeyPropertyName = Object.keys(tableInfo.columns).find(
3474
+ (key) => tableInfo.columns[key] === foreignKeyColumn
3475
+ );
3476
+ if (!foreignKeyPropertyName)
3477
+ continue;
3478
+ const referencedCustomType = referencedColumn.customGraphqlType;
3479
+ const foreignKeyHasCustomType = !!foreignKeyColumn.customGraphqlType;
3480
+ const referencedIsPrimaryKey = referencedColumn.primary || false;
3481
+ if (!foreignKeyHasCustomType) {
3482
+ if (referencedCustomType) {
3483
+ foreignKeyTypes2.set(
3484
+ `${tableName}.${foreignKeyPropertyName}`,
3485
+ referencedCustomType
3486
+ );
3487
+ } else if (referencedIsPrimaryKey) {
3488
+ foreignKeyTypes2.set(`${tableName}.${foreignKeyPropertyName}`, "ID");
3489
+ }
3490
+ }
3491
+ }
3492
+ }
3493
+ }
3494
+ for (const [tableName, tableInfo] of Object.entries(tables)) {
3495
+ const typeName = capitalize(tableName);
3496
+ const fields = [];
3497
+ for (const [columnName, column] of Object.entries(tableInfo.columns)) {
3498
+ const isPrimaryKey = column.primary || false;
3499
+ const typeStr = columnToSDL2(
3500
+ column,
3501
+ columnName,
3502
+ tableName,
3503
+ false,
3504
+ isPrimaryKey
3505
+ );
3506
+ const description = column.customGraphqlDescription;
3507
+ if (description) {
3508
+ fields.push(` """${description}"""`);
3509
+ }
3510
+ fields.push(` ${columnName}: ${typeStr}`);
3511
+ }
3512
+ const tableRelations = relations[tableName];
3513
+ if (tableRelations) {
3514
+ for (const [relationName, relationInfo] of Object.entries(
3515
+ tableRelations
3516
+ )) {
3517
+ const isOne = (0, import_drizzle_orm14.is)(relationInfo.relation, import_drizzle_orm14.One);
3518
+ const targetTableName = relationInfo.targetTableName;
3519
+ const targetTypeName = capitalize(targetTableName);
3520
+ if (isOne) {
3521
+ fields.push(
3522
+ ` ${relationName}(where: ${targetTypeName}Filters): ${targetTypeName}`
3523
+ );
3524
+ } else {
3525
+ fields.push(
3526
+ ` ${relationName}(where: ${targetTypeName}Filters, orderBy: ${targetTypeName}OrderBy, limit: Int, offset: Int): [${targetTypeName}!]!`
3527
+ );
3528
+ }
3529
+ }
3530
+ }
3531
+ typeDefs.push(`type ${typeName} {
3532
+ ${fields.join("\n")}
3533
+ }`);
3534
+ const insertFields = [];
3535
+ for (const [columnName, column] of Object.entries(tableInfo.columns)) {
3536
+ const isPrimaryKey = column.primary || false;
3537
+ const typeStr = columnToSDL2(
3538
+ column,
3539
+ columnName,
3540
+ tableName,
3541
+ false,
3542
+ isPrimaryKey
3543
+ );
3544
+ const hasDefault = column.hasDefault || column.default !== void 0;
3545
+ const isAutoIncrement = column.autoIncrement || column.generatedAlwaysAs;
3546
+ const isNotNull4 = column.notNull;
3547
+ const shouldBeOptional = hasDefault || isAutoIncrement || isPrimaryKey && !isNotNull4;
3548
+ let insertFieldType;
3549
+ if (shouldBeOptional) {
3550
+ insertFieldType = typeStr.endsWith("!") ? typeStr.slice(0, -1) : typeStr;
3551
+ } else {
3552
+ insertFieldType = isNotNull4 && !typeStr.endsWith("!") ? `${typeStr}!` : typeStr;
3553
+ }
3554
+ insertFields.push(` ${columnName}: ${insertFieldType}`);
3555
+ }
3556
+ if (insertFields.length > 0) {
3557
+ typeDefs.push(
3558
+ `input ${typeName}InsertInput {
3559
+ ${insertFields.join("\n")}
3560
+ }`
3561
+ );
3562
+ }
3563
+ const updateFields = [];
3564
+ for (const [columnName, column] of Object.entries(tableInfo.columns)) {
3565
+ const isPrimaryKey = column.primary || false;
3566
+ const typeStr = columnToSDL2(
3567
+ column,
3568
+ columnName,
3569
+ tableName,
3570
+ true,
3571
+ isPrimaryKey
3572
+ );
3573
+ updateFields.push(` ${columnName}: ${typeStr}`);
3574
+ }
3575
+ typeDefs.push(
3576
+ `input ${typeName}UpdateInput {
3577
+ ${updateFields.join("\n")}
3578
+ }`
3579
+ );
3580
+ const whereFields = [];
3581
+ for (const [columnName, column] of Object.entries(tableInfo.columns)) {
3582
+ const isPrimaryKey = column.primary || false;
3583
+ const typeStr = columnToSDL2(
3584
+ column,
3585
+ columnName,
3586
+ tableName,
3587
+ true,
3588
+ isPrimaryKey
3589
+ );
3590
+ const normalizedType = typeStr.replace(/[^a-zA-Z0-9]/g, "");
3591
+ const filterTypeName = `${normalizedType}FieldFilter`;
3592
+ requiredFieldFilters2.add(
3593
+ JSON.stringify({ normalizedType, baseType: typeStr })
3594
+ );
3595
+ whereFields.push(` ${columnName}: ${filterTypeName}`);
3596
+ }
3597
+ whereFields.push(` OR: [${typeName}Filters!]`);
3598
+ typeDefs.push(`input ${typeName}Filters {
3599
+ ${whereFields.join("\n")}
3600
+ }`);
3601
+ const orderByFields = [];
3602
+ for (const columnName of Object.keys(tableInfo.columns)) {
3603
+ orderByFields.push(` ${columnName}: InnerOrder`);
3604
+ }
3605
+ typeDefs.push(`input ${typeName}OrderBy {
3606
+ ${orderByFields.join("\n")}
3607
+ }`);
3608
+ typeDefs.push(`type ${typeName}DeleteResult {
3609
+ deletedItems: [DeletedItem!]!
3610
+ ${tableName}FindMany(where: ${typeName}Filters, orderBy: ${typeName}OrderBy, limit: Int, offset: Int): [${typeName}!]!
3611
+ }`);
3612
+ }
3613
+ const allDefs = [];
3614
+ if (customScalars2.size > 0) {
3615
+ for (const scalarName of Array.from(customScalars2).sort()) {
3616
+ allDefs.push(`scalar ${scalarName}`);
3617
+ }
3618
+ }
3619
+ if (enumDefinitions2.size > 0) {
3620
+ for (const enumDef of Array.from(enumDefinitions2.values())) {
3621
+ const valueStrings = enumDef.values.map((v) => ` ${v}`);
3622
+ allDefs.push(`enum ${enumDef.name} {
3623
+ ${valueStrings.join("\n")}
3624
+ }`);
3625
+ }
3626
+ }
3627
+ allDefs.push(`enum OrderByDirection {
3628
+ asc
3629
+ desc
3630
+ }`);
3631
+ allDefs.push(`type DeletedItem {
3632
+ id: ID!
3633
+ }`);
3634
+ allDefs.push(`input InnerOrder {
3635
+ direction: OrderByDirection!
3636
+ priority: Int!
3637
+ }`);
3638
+ const filterTypesAdded = /* @__PURE__ */ new Set();
3639
+ for (const filterInfoJson of Array.from(requiredFieldFilters2)) {
3640
+ const { normalizedType, baseType } = JSON.parse(filterInfoJson);
3641
+ const filterTypeName = `${normalizedType}FieldFilter`;
3642
+ if (filterTypesAdded.has(filterTypeName))
3643
+ continue;
3644
+ filterTypesAdded.add(filterTypeName);
3645
+ const filterFields = [];
3646
+ filterFields.push(` eq: ${baseType}`);
3647
+ filterFields.push(` ne: ${baseType}`);
3648
+ filterFields.push(` lt: ${baseType}`);
3649
+ filterFields.push(` lte: ${baseType}`);
3650
+ filterFields.push(` gt: ${baseType}`);
3651
+ filterFields.push(` gte: ${baseType}`);
3652
+ filterFields.push(` like: String`);
3653
+ filterFields.push(` notLike: String`);
3654
+ filterFields.push(` ilike: String`);
3655
+ filterFields.push(` notIlike: String`);
3656
+ filterFields.push(` inArray: [${baseType}!]`);
3657
+ filterFields.push(` notInArray: [${baseType}!]`);
3658
+ filterFields.push(` isNull: Boolean`);
3659
+ filterFields.push(` isNotNull: Boolean`);
3660
+ filterFields.push(` OR: [${filterTypeName}!]`);
3661
+ allDefs.push(`input ${filterTypeName} {
3662
+ ${filterFields.join("\n")}
3663
+ }`);
3664
+ }
3665
+ allDefs.push(...typeDefs);
3666
+ return allDefs.join("\n\n");
3667
+ };
3668
+ var generateQueryTypeDefs2 = (tables) => {
3669
+ const queryFields = [];
3670
+ for (const tableName of Object.keys(tables)) {
3671
+ const typeName = capitalize(tableName);
3672
+ queryFields.push(
3673
+ ` ${tableName}FindMany(where: ${typeName}Filters, orderBy: ${typeName}OrderBy, limit: Int, offset: Int): [${typeName}!]!`
3674
+ );
3675
+ queryFields.push(
3676
+ ` ${tableName}FindFirst(where: ${typeName}Filters, orderBy: ${typeName}OrderBy): ${typeName}`
3677
+ );
3678
+ }
3679
+ return `type Query {
3680
+ ${queryFields.join("\n")}
3681
+ }`;
3682
+ };
3683
+ var generateMutationTypeDefs2 = (tables) => {
3684
+ const mutationFields = [];
3685
+ for (const tableName of Object.keys(tables)) {
3686
+ const typeName = capitalize(tableName);
3687
+ mutationFields.push(
3688
+ ` ${tableName}InsertMany(values: [${typeName}InsertInput!]!): [${typeName}!]!`
3689
+ );
3690
+ mutationFields.push(
3691
+ ` ${tableName}UpdateMany(where: ${typeName}Filters, set: ${typeName}UpdateInput!): [${typeName}!]!`
3692
+ );
3693
+ mutationFields.push(
3694
+ ` ${tableName}DeleteMany(where: ${typeName}Filters): ${typeName}DeleteResult!`
3695
+ );
3696
+ }
3697
+ return `type Mutation {
3698
+ ${mutationFields.join("\n")}
3699
+ }`;
3700
+ };
3701
+
3702
+ // src/build-schema-sdl-with-dl/generator/queries/dataloader-resolvers.ts
3703
+ var import_graphql12 = require("graphql");
3704
+ var import_graphql_parse_resolve_info5 = require("graphql-parse-resolve-info");
3705
+ var import_drizzle_orm18 = require("drizzle-orm");
3706
+
3707
+ // src/build-schema-sdl-with-dl/generator/utils/selection.ts
3708
+ var import_drizzle_orm16 = require("drizzle-orm");
3709
+
3710
+ // src/build-schema-sdl-with-dl/generator/utils/filters.ts
3711
+ var import_drizzle_orm15 = require("drizzle-orm");
3712
+ var import_graphql11 = require("graphql");
3713
+ var extractFiltersColumn3 = (column, columnName, operators) => {
3714
+ const entries = Object.entries(operators);
3715
+ if (!entries.length)
3716
+ return void 0;
3717
+ if (operators.OR && operators.OR.length > 0) {
3718
+ if (entries.length > 1) {
3719
+ throw new import_graphql11.GraphQLError(
3720
+ `WHERE ${columnName}: Cannot specify both fields and 'OR' in column operators!`
3721
+ );
3722
+ }
3723
+ const variants2 = [];
3724
+ for (const variant of operators.OR) {
3725
+ const extracted = extractFiltersColumn3(column, columnName, variant);
3726
+ if (extracted)
3727
+ variants2.push(extracted);
3728
+ }
3729
+ return variants2.length ? variants2.length > 1 ? (0, import_drizzle_orm15.or)(...variants2) : variants2[0] : void 0;
3730
+ }
3731
+ const variants = [];
3732
+ for (const [operatorName, operatorValue] of entries) {
3733
+ if (operatorValue === null || operatorValue === false)
3734
+ continue;
3735
+ switch (operatorName) {
3736
+ case "eq":
3737
+ case "ne":
3738
+ case "gt":
3739
+ case "gte":
3740
+ case "lt":
3741
+ case "lte": {
3742
+ const singleValue = remapFromGraphQLCore(
3743
+ operatorValue,
3744
+ column,
3745
+ columnName
3746
+ );
3747
+ const opMap = { eq: import_drizzle_orm15.eq, ne: import_drizzle_orm15.ne, gt: import_drizzle_orm15.gt, gte: import_drizzle_orm15.gte, lt: import_drizzle_orm15.lt, lte: import_drizzle_orm15.lte };
3748
+ variants.push(opMap[operatorName](column, singleValue));
3749
+ break;
3750
+ }
3751
+ case "like":
3752
+ case "notLike":
3753
+ case "ilike":
3754
+ case "notIlike": {
3755
+ const opMap = { like: import_drizzle_orm15.like, notLike: import_drizzle_orm15.notLike, ilike: import_drizzle_orm15.ilike, notIlike: import_drizzle_orm15.notIlike };
3756
+ variants.push(opMap[operatorName](column, operatorValue));
3757
+ break;
3758
+ }
3759
+ case "inArray":
3760
+ case "notInArray": {
3761
+ if (!operatorValue.length) {
3762
+ throw new import_graphql11.GraphQLError(
3763
+ `WHERE ${columnName}: Unable to use operator ${operatorName} with an empty array!`
3764
+ );
3765
+ }
3766
+ const arrayValue = operatorValue.map(
3767
+ (val) => remapFromGraphQLCore(val, column, columnName)
3768
+ );
3769
+ const opMap = { inArray: import_drizzle_orm15.inArray, notInArray: import_drizzle_orm15.notInArray };
3770
+ variants.push(opMap[operatorName](column, arrayValue));
3771
+ break;
3772
+ }
3773
+ case "isNull":
3774
+ case "isNotNull": {
3775
+ const opMap = { isNull: import_drizzle_orm15.isNull, isNotNull: import_drizzle_orm15.isNotNull };
3776
+ variants.push(opMap[operatorName](column));
3777
+ break;
3778
+ }
3779
+ }
3780
+ }
3781
+ return variants.length ? variants.length > 1 ? (0, import_drizzle_orm15.and)(...variants) : variants[0] : void 0;
3782
+ };
3783
+ var buildWhereClause2 = (tableInfo, where) => {
3784
+ if (!where || Object.keys(where).length === 0) {
3785
+ return void 0;
3786
+ }
3787
+ if (where.OR && where.OR.length > 0) {
3788
+ if (Object.keys(where).length > 1) {
3789
+ throw new import_graphql11.GraphQLError(
3790
+ `WHERE ${tableInfo.name}: Cannot specify both fields and 'OR' in table filters!`
3791
+ );
3792
+ }
3793
+ const variants = [];
3794
+ for (const variant of where.OR) {
3795
+ const extracted = buildWhereClause2(tableInfo, variant);
3796
+ if (extracted)
3797
+ variants.push(extracted);
3798
+ }
3799
+ return variants.length ? variants.length > 1 ? (0, import_drizzle_orm15.or)(...variants) : variants[0] : void 0;
3800
+ }
3801
+ const conditions = [];
3802
+ for (const [columnName, operators] of Object.entries(where)) {
3803
+ if (columnName === "OR")
3804
+ continue;
3805
+ if (!operators || Object.keys(operators).length === 0)
3806
+ continue;
3807
+ const column = tableInfo.columns[columnName];
3808
+ if (!column)
3809
+ continue;
3810
+ const extracted = extractFiltersColumn3(
3811
+ column,
3812
+ columnName,
3813
+ operators
3814
+ );
3815
+ if (extracted)
3816
+ conditions.push(extracted);
3817
+ }
3818
+ if (conditions.length === 0)
3819
+ return void 0;
3820
+ if (conditions.length === 1)
3821
+ return conditions[0];
3822
+ return (0, import_drizzle_orm15.and)(...conditions);
3823
+ };
3824
+
3825
+ // src/build-schema-sdl-with-dl/generator/utils/selection.ts
3826
+ var buildOrderByClause2 = (tableInfo, orderBy) => {
3827
+ if (!orderBy || Object.keys(orderBy).length === 0) {
3828
+ return void 0;
3829
+ }
3830
+ const orderEntries = Object.entries(orderBy).map(([columnName, field]) => ({
3831
+ columnName,
3832
+ ...field
3833
+ }));
3834
+ orderEntries.sort((a, b) => a.priority - b.priority);
3835
+ const orderClauses = [];
3836
+ for (const entry of orderEntries) {
3837
+ const column = tableInfo.columns[entry.columnName];
3838
+ if (column) {
3839
+ orderClauses.push(
3840
+ entry.direction === "desc" ? (0, import_drizzle_orm16.desc)(column) : (0, import_drizzle_orm16.asc)(column)
3841
+ );
3842
+ }
3843
+ }
3844
+ return orderClauses.length > 0 ? orderClauses : void 0;
3845
+ };
3846
+
3847
+ // src/build-schema-sdl-with-dl/generator/utils/dataloader.ts
3848
+ var import_dataloader = __toESM(require("dataloader"), 1);
3849
+ var import_drizzle_orm17 = require("drizzle-orm");
3850
+ var RelationDataLoader = class {
3851
+ constructor(queryBase, tableInfo, relations) {
3852
+ this.queryBase = queryBase;
3853
+ this.tableInfo = tableInfo;
3854
+ this.relations = relations;
3855
+ }
3856
+ loaders = /* @__PURE__ */ new Map();
3857
+ createLoaderKey(key) {
3858
+ return JSON.stringify({
3859
+ relationName: key.relationName,
3860
+ foreignKey: key.foreignKey,
3861
+ isReversedRelation: key.isReversedRelation,
3862
+ where: key.where,
3863
+ orderBy: key.orderBy,
3864
+ limit: key.limit,
3865
+ offset: key.offset,
3866
+ columns: key.columns
3867
+ });
3868
+ }
3869
+ getOrCreateLoader(loaderKey) {
3870
+ if (!this.loaders.has(loaderKey)) {
3871
+ const loader = new import_dataloader.default(
3872
+ async (keys) => this.batchLoadRelations(keys)
3873
+ );
3874
+ this.loaders.set(loaderKey, loader);
3875
+ }
3876
+ return this.loaders.get(loaderKey);
3877
+ }
3878
+ async batchLoadRelations(keys) {
3879
+ const groupedKeys = /* @__PURE__ */ new Map();
3880
+ for (const key of keys) {
3881
+ const configKey = this.createLoaderKey(key);
3882
+ if (!groupedKeys.has(configKey)) {
3883
+ groupedKeys.set(configKey, []);
3884
+ }
3885
+ groupedKeys.get(configKey).push(key);
3886
+ }
3887
+ const results = [];
3888
+ for (const [configKey, groupKeys] of Array.from(groupedKeys)) {
3889
+ const firstKey = groupKeys[0];
3890
+ if (!firstKey) {
3891
+ continue;
3892
+ }
3893
+ const allParentIds = groupKeys.flatMap((key) => key.parentIds);
3894
+ const uniqueParentIds = Array.from(new Set(allParentIds));
3895
+ const whereClause = this.buildBatchWhereClause(
3896
+ uniqueParentIds,
3897
+ firstKey.isReversedRelation,
3898
+ firstKey.foreignKey,
3899
+ firstKey.where
3900
+ );
3901
+ if (!whereClause) {
3902
+ results.push(...groupKeys.map(() => []));
3903
+ continue;
3904
+ }
3905
+ let query = this.queryBase.findMany({
3906
+ columns: {
3907
+ ...firstKey.columns || {},
3908
+ // Always include the foreign key column for mapping
3909
+ [firstKey.foreignKey]: true
3910
+ },
3911
+ where: whereClause,
3912
+ orderBy: firstKey.orderBy ? buildOrderByClause2(this.tableInfo, firstKey.orderBy) : void 0,
3913
+ limit: firstKey.limit,
3914
+ offset: firstKey.offset
3915
+ });
3916
+ console.log(`DataLoader executing query for relation ${firstKey.relationName} with foreign key ${firstKey.foreignKey}`);
3917
+ const batchResults = await query;
3918
+ console.log(`DataLoader got ${batchResults.length} results:`, batchResults);
3919
+ const resultsByParentId = /* @__PURE__ */ new Map();
3920
+ for (const result of batchResults) {
3921
+ const parentId = result[firstKey.foreignKey];
3922
+ if (!resultsByParentId.has(parentId)) {
3923
+ resultsByParentId.set(parentId, []);
3924
+ }
3925
+ resultsByParentId.get(parentId).push(result);
3926
+ }
3927
+ for (const key of groupKeys) {
3928
+ const keyResults = key.parentIds.map((parentId) => ({
3929
+ parentId,
3930
+ data: resultsByParentId.get(parentId) || []
3931
+ }));
3932
+ results.push(keyResults);
3933
+ }
3934
+ }
3935
+ return results;
3936
+ }
3937
+ buildBatchWhereClause(parentIds, isReversedRelation, foreignKeyName, additionalWhere) {
3938
+ const foreignKeyColumn = this.tableInfo.columns[foreignKeyName];
3939
+ if (!foreignKeyColumn) {
3940
+ console.error(`Foreign key column ${foreignKeyName} not found in table ${this.tableInfo.name}`);
3941
+ console.error(`Available columns:`, Object.keys(this.tableInfo.columns));
3942
+ return void 0;
3943
+ }
3944
+ const parentIdClause = (0, import_drizzle_orm17.inArray)(foreignKeyColumn, parentIds);
3945
+ if (!additionalWhere) {
3946
+ return parentIdClause;
3947
+ }
3948
+ const additionalClause = buildWhereClause2(this.tableInfo, additionalWhere);
3949
+ return additionalClause ? (0, import_drizzle_orm17.and)(parentIdClause, additionalClause) : parentIdClause;
3950
+ }
3951
+ async loadRelation(relationName, parentIds, foreignKey, options = {}, isReversedRelation = false) {
3952
+ const key = {
3953
+ relationName,
3954
+ parentIds,
3955
+ foreignKey,
3956
+ isReversedRelation,
3957
+ ...options
3958
+ };
3959
+ const loaderKey = this.createLoaderKey(key);
3960
+ const loader = this.getOrCreateLoader(loaderKey);
3961
+ const result = await loader.load(key);
3962
+ return result;
3963
+ }
3964
+ // Clear all loaders (call this at the end of each request)
3965
+ clearAll() {
3966
+ for (const loader of Array.from(this.loaders.values())) {
3967
+ loader.clearAll();
3968
+ }
3969
+ this.loaders.clear();
3970
+ }
3971
+ };
3972
+ function getRelationLoader(context, tableName, queryBase, tableInfo, relations) {
3973
+ if (!context.relationLoaders.has(tableName)) {
3974
+ context.relationLoaders.set(
3975
+ tableName,
3976
+ new RelationDataLoader(queryBase, tableInfo, relations)
3977
+ );
3978
+ }
3979
+ return context.relationLoaders.get(tableName);
3980
+ }
3981
+
3982
+ // src/build-schema-sdl-with-dl/generator/queries/dataloader-resolvers.ts
3983
+ var createDataLoaderFindManyResolver = (queryBase, tableInfo, tables, relations) => {
3984
+ return async (parent, args, context, info) => {
3985
+ try {
3986
+ const { where, orderBy, limit, offset } = args;
3987
+ const parsedInfo = (0, import_graphql_parse_resolve_info5.parseResolveInfo)(info, {
3988
+ deep: true
3989
+ });
3990
+ const allFields = {};
3991
+ if (parsedInfo.fieldsByTypeName) {
3992
+ for (const fields of Object.values(parsedInfo.fieldsByTypeName)) {
3993
+ Object.assign(allFields, fields);
3994
+ }
3995
+ }
3996
+ const allColumns = {};
3997
+ for (const columnName of Object.keys(tableInfo.columns)) {
3998
+ allColumns[columnName] = true;
3999
+ }
4000
+ const mainResults = await queryBase.findMany({
4001
+ columns: allColumns,
4002
+ offset,
4003
+ limit,
4004
+ orderBy: buildOrderByClause2(tableInfo, orderBy),
4005
+ where: buildWhereClause2(tableInfo, where)
4006
+ // No 'with' clause - we'll load relations separately
4007
+ });
4008
+ if (mainResults.length === 0) {
4009
+ return mainResults;
4010
+ }
4011
+ const enhancedResults = await loadRelationsWithDataLoader(
4012
+ mainResults,
4013
+ tableInfo,
4014
+ tables,
4015
+ relations,
4016
+ allFields,
4017
+ context
4018
+ );
4019
+ return enhancedResults;
4020
+ } catch (e) {
4021
+ if (typeof e === "object" && e !== null && "message" in e) {
4022
+ throw new import_graphql12.GraphQLError(String(e.message));
4023
+ }
4024
+ throw e;
4025
+ }
4026
+ };
4027
+ };
4028
+ var createDataLoaderFindFirstResolver = (queryBase, tableInfo, tables, relations) => {
4029
+ return async (parent, args, context, info) => {
4030
+ try {
4031
+ const { where, orderBy } = args;
4032
+ const parsedInfo = (0, import_graphql_parse_resolve_info5.parseResolveInfo)(info, {
4033
+ deep: true
4034
+ });
4035
+ const allFields = {};
4036
+ if (parsedInfo.fieldsByTypeName) {
4037
+ for (const fields of Object.values(parsedInfo.fieldsByTypeName)) {
4038
+ Object.assign(allFields, fields);
4039
+ }
4040
+ }
4041
+ const allColumns = {};
4042
+ for (const columnName of Object.keys(tableInfo.columns)) {
4043
+ allColumns[columnName] = true;
4044
+ }
4045
+ const mainResult = await queryBase.findFirst({
4046
+ columns: allColumns,
4047
+ orderBy: buildOrderByClause2(tableInfo, orderBy),
4048
+ where: buildWhereClause2(tableInfo, where)
4049
+ // No 'with' clause
4050
+ });
4051
+ if (!mainResult) {
4052
+ return null;
4053
+ }
4054
+ const [enhancedResult] = await loadRelationsWithDataLoader(
4055
+ [mainResult],
4056
+ tableInfo,
4057
+ tables,
4058
+ relations,
4059
+ allFields,
4060
+ context
4061
+ );
4062
+ return enhancedResult || null;
4063
+ } catch (e) {
4064
+ if (typeof e === "object" && e !== null && "message" in e) {
4065
+ throw new import_graphql12.GraphQLError(String(e.message));
4066
+ }
4067
+ throw e;
4068
+ }
4069
+ };
4070
+ };
4071
+ async function loadRelationsWithDataLoader(mainResults, tableInfo, tables, relations, fields, context) {
4072
+ const tableRelations = relations[tableInfo.name];
4073
+ if (!tableRelations) {
4074
+ return mainResults;
4075
+ }
4076
+ const primaryKeyColumn = Object.values(tableInfo.columns).find((col) => col.primary);
4077
+ if (!primaryKeyColumn) {
4078
+ throw new Error(`No primary key found for table ${tableInfo.name}`);
4079
+ }
4080
+ const parentIds = mainResults.map((result) => result[primaryKeyColumn.name]);
4081
+ const relationPromises = [];
4082
+ for (const [relName, { targetTableName, relation }] of Object.entries(tableRelations)) {
4083
+ const relationField = fields[relName];
4084
+ if (!relationField)
4085
+ continue;
4086
+ const targetTable = tables[targetTableName];
4087
+ if (!targetTable)
4088
+ continue;
4089
+ const relationFields = {};
4090
+ if (relationField.fieldsByTypeName) {
4091
+ for (const typeFields of Object.values(relationField.fieldsByTypeName)) {
4092
+ Object.assign(relationFields, typeFields);
4093
+ }
4094
+ }
4095
+ const allTargetColumns = {};
4096
+ for (const columnName of Object.keys(targetTable.columns)) {
4097
+ allTargetColumns[columnName] = true;
4098
+ }
4099
+ const relationArgs = relationField.args;
4100
+ const relationOptions = {
4101
+ columns: allTargetColumns,
4102
+ where: relationArgs?.where,
4103
+ orderBy: relationArgs?.orderBy,
4104
+ limit: relationArgs?.limit,
4105
+ offset: relationArgs?.offset
4106
+ };
4107
+ let foreignKeyName;
4108
+ let isReversedRelation = false;
4109
+ const relationConfig = relation.config;
4110
+ console.log(`Processing relation ${relName} for table ${tableInfo.name} -> ${targetTableName}`);
4111
+ if (relationConfig?.fields && relationConfig.fields.length > 0) {
4112
+ if ((0, import_drizzle_orm18.is)(relation, import_drizzle_orm18.One)) {
4113
+ const fieldColumn = relationConfig.fields[0];
4114
+ const referenceColumn = relationConfig.references[0];
4115
+ const referenceKeyName = Object.keys(targetTable.columns).find(
4116
+ (key) => targetTable.columns[key] === referenceColumn
4117
+ ) || referenceColumn.name;
4118
+ foreignKeyName = referenceKeyName;
4119
+ isReversedRelation = false;
4120
+ console.log(`One-to-one relation: foreignKey=${foreignKeyName}, isReversed=${isReversedRelation}`);
4121
+ } else {
4122
+ const fieldColumn = relationConfig.fields[0];
4123
+ const referenceColumn = relationConfig.references[0];
4124
+ foreignKeyName = Object.keys(targetTable.columns).find(
4125
+ (key) => targetTable.columns[key] === referenceColumn
4126
+ ) || referenceColumn.name;
4127
+ isReversedRelation = false;
4128
+ console.log(`Many-to-one relation: foreignKey=${foreignKeyName}, isReversed=${isReversedRelation}`);
4129
+ }
4130
+ } else if (relationConfig?.references && relationConfig.references.length > 0) {
4131
+ foreignKeyName = relationConfig.references[0].name;
4132
+ isReversedRelation = true;
4133
+ console.log(`References-only relation: foreignKey=${foreignKeyName}, isReversed=${isReversedRelation}`);
4134
+ } else {
4135
+ if ((0, import_drizzle_orm18.is)(relation, import_drizzle_orm18.One)) {
4136
+ let possibleForeignKeys = Object.entries(targetTable.columns).filter(([name, col]) => {
4137
+ const lowerName = name.toLowerCase();
4138
+ const tableName = tableInfo.name.toLowerCase();
4139
+ return lowerName.endsWith("id") && (lowerName.includes(tableName) || lowerName === `${tableName}id` || lowerName === `${tableName}_id`);
4140
+ });
4141
+ if (possibleForeignKeys.length > 0) {
4142
+ foreignKeyName = possibleForeignKeys[0][0];
4143
+ isReversedRelation = true;
4144
+ } else {
4145
+ possibleForeignKeys = Object.entries(tableInfo.columns).filter(([name, col]) => {
4146
+ const lowerName = name.toLowerCase();
4147
+ const targetName = targetTableName.toLowerCase();
4148
+ return lowerName.endsWith("id") && (lowerName.includes(targetName) || lowerName === `${targetName}id` || lowerName === `${targetName}_id`);
4149
+ });
4150
+ if (possibleForeignKeys.length > 0) {
4151
+ foreignKeyName = possibleForeignKeys[0][0];
4152
+ isReversedRelation = false;
4153
+ } else {
4154
+ console.warn(`Could not determine foreign key for one-to-one relation ${relName}`);
4155
+ console.warn(`Available columns in current table ${tableInfo.name}:`, Object.keys(tableInfo.columns));
4156
+ console.warn(`Available columns in target table ${targetTableName}:`, Object.keys(targetTable.columns));
4157
+ continue;
4158
+ }
4159
+ }
4160
+ } else {
4161
+ let possibleForeignKeys = Object.entries(targetTable.columns).filter(([name, col]) => {
4162
+ const lowerName = name.toLowerCase();
4163
+ const tableName = tableInfo.name.toLowerCase();
4164
+ return lowerName.endsWith("id") && (lowerName.includes(tableName) || lowerName === `${tableName}id` || lowerName === `${tableName}_id` || // Special case for author -> user relationship
4165
+ tableName === "user" && lowerName === "authorid" || tableName === "user" && lowerName === "author_id");
4166
+ });
4167
+ if (possibleForeignKeys.length > 0) {
4168
+ foreignKeyName = possibleForeignKeys[0][0];
4169
+ isReversedRelation = true;
4170
+ } else {
4171
+ console.warn(`Could not determine foreign key for one-to-many relation ${relName}. Looking for foreign key in target table ${targetTableName} that references ${tableInfo.name}`);
4172
+ console.warn(`Available columns in ${targetTableName}:`, Object.keys(targetTable.columns));
4173
+ continue;
4174
+ }
4175
+ }
4176
+ }
4177
+ let actualParentIds = parentIds;
4178
+ if (relationConfig?.fields && relationConfig.fields.length > 0) {
4179
+ const fieldColumn = relationConfig.fields[0];
4180
+ const fieldKeyName = Object.keys(tableInfo.columns).find(
4181
+ (key) => tableInfo.columns[key] === fieldColumn
4182
+ ) || fieldColumn.name;
4183
+ if (tableInfo.columns[fieldKeyName]) {
4184
+ actualParentIds = mainResults.map((result) => result[fieldKeyName]).filter((id) => id != null);
4185
+ console.log(`Extracted foreign key values for many-to-one relation:`, actualParentIds);
4186
+ }
4187
+ }
4188
+ const targetQueryBase = context.db?.query?.[targetTableName];
4189
+ if (!targetQueryBase) {
4190
+ console.warn(`No query base found for target table ${targetTableName}`);
4191
+ continue;
4192
+ }
4193
+ const relationLoader = getRelationLoader(
4194
+ context,
4195
+ targetTableName,
4196
+ targetQueryBase,
4197
+ targetTable,
4198
+ relations[targetTableName] || {}
4199
+ );
4200
+ console.log(`Created relation loader for ${targetTableName}, calling loadRelation with parentIds:`, actualParentIds);
4201
+ const relationPromise = relationLoader.loadRelation(
4202
+ relName,
4203
+ actualParentIds,
4204
+ foreignKeyName,
4205
+ relationOptions,
4206
+ isReversedRelation
4207
+ ).then(async (relationResults) => {
4208
+ console.log(`Relation ${relName} loaded, got ${relationResults.length} results:`, relationResults);
4209
+ const relationMap = /* @__PURE__ */ new Map();
4210
+ for (const result of relationResults) {
4211
+ relationMap.set(result.parentId, result.data);
4212
+ }
4213
+ const hasNestedRelations = Object.keys(relationFields).some(
4214
+ (fieldName) => !targetTable.columns[fieldName]
4215
+ );
4216
+ if (hasNestedRelations && relationResults.some((r) => r.data.length > 0)) {
4217
+ const allRelationData = relationResults.flatMap((r) => r.data);
4218
+ const enhancedRelationData = await loadRelationsWithDataLoader(
4219
+ allRelationData,
4220
+ targetTable,
4221
+ tables,
4222
+ relations,
4223
+ relationFields,
4224
+ context
4225
+ );
4226
+ let dataIndex = 0;
4227
+ for (const result of relationResults) {
4228
+ const enhancedData = enhancedRelationData.slice(dataIndex, dataIndex + result.data.length);
4229
+ relationMap.set(result.parentId, enhancedData);
4230
+ dataIndex += result.data.length;
4231
+ }
4232
+ }
4233
+ for (const mainResult of mainResults) {
4234
+ const parentId = mainResult[primaryKeyColumn.name];
4235
+ if (relationConfig?.fields && relationConfig.fields.length > 0) {
4236
+ const fieldColumn = relationConfig.fields[0];
4237
+ const fieldKeyName = Object.keys(tableInfo.columns).find(
4238
+ (key) => tableInfo.columns[key] === fieldColumn
4239
+ ) || fieldColumn.name;
4240
+ if (tableInfo.columns[fieldKeyName]) {
4241
+ const foreignKeyValue = mainResult[fieldKeyName];
4242
+ const relationData2 = relationMap.get(foreignKeyValue) || [];
4243
+ mainResult[relName] = relationData2[0] || null;
4244
+ continue;
4245
+ }
4246
+ }
4247
+ const relationData = relationMap.get(parentId) || [];
4248
+ if ((0, import_drizzle_orm18.is)(relation, import_drizzle_orm18.One)) {
4249
+ mainResult[relName] = relationData[0] || null;
4250
+ } else {
4251
+ mainResult[relName] = relationData;
4252
+ }
4253
+ }
4254
+ });
4255
+ relationPromises.push(relationPromise);
4256
+ }
4257
+ await Promise.all(relationPromises);
4258
+ return mainResults;
4259
+ }
4260
+
4261
+ // src/build-schema-sdl-with-dl/generator/queries/index.ts
4262
+ var generateQueries2 = (db, tables, relations) => {
4263
+ const queries = {};
4264
+ for (const [tableName, tableInfo] of Object.entries(tables)) {
4265
+ const queryBase = db.query[tableName];
4266
+ if (!queryBase) {
4267
+ throw new Error(
4268
+ `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`
4269
+ );
4270
+ }
4271
+ queries[`${tableName}FindMany`] = createDataLoaderFindManyResolver(
4272
+ queryBase,
4273
+ tableInfo,
4274
+ tables,
4275
+ relations
4276
+ );
4277
+ queries[`${tableName}FindFirst`] = createDataLoaderFindFirstResolver(
4278
+ queryBase,
4279
+ tableInfo,
4280
+ tables,
4281
+ relations
4282
+ );
4283
+ }
4284
+ return queries;
4285
+ };
4286
+
4287
+ // src/build-schema-sdl-with-dl/generator/mutations/resolvers.ts
4288
+ var import_graphql13 = require("graphql");
4289
+ var createInsertManyResolver2 = (db, queryBase, tableInfo, tables, relations, primaryKeyColumn) => {
4290
+ const queryResolver = createDataLoaderFindManyResolver(queryBase, tableInfo, tables, relations);
4291
+ return async (parent, args, context, info) => {
4292
+ try {
4293
+ const { values } = args;
4294
+ if (!values || values.length === 0) {
4295
+ throw new import_graphql13.GraphQLError("No values provided for insert");
4296
+ }
4297
+ const remappedValues = remapFromGraphQLArrayInput(
4298
+ values,
4299
+ tableInfo.table
4300
+ );
4301
+ const insertedRows = await db.insert(tableInfo.table).values(remappedValues).returning({
4302
+ [primaryKeyColumn.name]: primaryKeyColumn
4303
+ });
4304
+ const insertedIds = insertedRows.map(
4305
+ (row) => row[primaryKeyColumn.name]
4306
+ );
4307
+ const result = await queryResolver(
4308
+ parent,
4309
+ {
4310
+ where: {
4311
+ [primaryKeyColumn.name]: { inArray: insertedIds }
4312
+ }
4313
+ },
4314
+ context,
4315
+ info
4316
+ );
4317
+ return result;
4318
+ } catch (e) {
4319
+ if (typeof e === "object" && e !== null && "message" in e) {
4320
+ throw new import_graphql13.GraphQLError(String(e.message));
4321
+ }
4322
+ throw e;
4323
+ }
4324
+ };
4325
+ };
4326
+ var createUpdateManyResolver2 = (db, queryBase, tableInfo, tables, relations, primaryKeyColumn) => {
4327
+ const queryResolver = createDataLoaderFindManyResolver(queryBase, tableInfo, tables, relations);
4328
+ return async (parent, args, context, info) => {
4329
+ try {
4330
+ const { where, set } = args;
4331
+ if (!set || Object.keys(set).length === 0) {
4332
+ throw new import_graphql13.GraphQLError("No values provided for update");
4333
+ }
4334
+ const remappedSet = remapFromGraphQLSingleInput(set, tableInfo.table);
4335
+ const whereClause = buildWhereClause2(tableInfo, where);
4336
+ let query = db.update(tableInfo.table).set(remappedSet);
4337
+ if (whereClause) {
4338
+ query = query.where(whereClause);
4339
+ }
4340
+ const updatedRows = await query.returning({
4341
+ [primaryKeyColumn.name]: primaryKeyColumn
4342
+ });
4343
+ const updatedIds = updatedRows.map(
4344
+ (row) => row[primaryKeyColumn.name]
4345
+ );
4346
+ const result = await queryResolver(
4347
+ parent,
4348
+ {
4349
+ where: {
4350
+ [primaryKeyColumn.name]: { inArray: updatedIds }
4351
+ }
4352
+ },
4353
+ context,
4354
+ info
4355
+ );
4356
+ return result;
4357
+ } catch (e) {
4358
+ if (typeof e === "object" && e !== null && "message" in e) {
4359
+ throw new import_graphql13.GraphQLError(String(e.message));
4360
+ }
4361
+ throw e;
4362
+ }
4363
+ };
4364
+ };
4365
+ var createDeleteManyResolver2 = (db, queryBase, tableInfo, tables, relations, primaryKeyColumn) => {
4366
+ const queryResolver = createDataLoaderFindManyResolver(queryBase, tableInfo, tables, relations);
4367
+ return async (parent, args, context, info) => {
4368
+ try {
4369
+ const { where } = args;
4370
+ const whereClause = buildWhereClause2(tableInfo, where);
4371
+ let deleteQuery = db.delete(tableInfo.table);
4372
+ if (whereClause) {
4373
+ deleteQuery = deleteQuery.where(whereClause);
4374
+ }
4375
+ const deletedRows = await deleteQuery.returning({
4376
+ [primaryKeyColumn.name]: primaryKeyColumn
4377
+ });
4378
+ const deletedItems = deletedRows.map((row) => ({
4379
+ id: row[primaryKeyColumn.name]
4380
+ }));
4381
+ return {
4382
+ deletedItems,
4383
+ [tableInfo.name + "FindMany"]: queryResolver
4384
+ };
4385
+ } catch (e) {
4386
+ if (typeof e === "object" && e !== null && "message" in e) {
4387
+ throw new import_graphql13.GraphQLError(String(e.message));
4388
+ }
4389
+ throw e;
4390
+ }
4391
+ };
4392
+ };
4393
+
4394
+ // src/build-schema-sdl-with-dl/generator/mutations/index.ts
4395
+ var generateMutations2 = (db, tables, relations) => {
4396
+ const mutations = {};
4397
+ const deleteResultResolvers = {};
4398
+ for (const [tableName, tableInfo] of Object.entries(tables)) {
4399
+ const capitalizedName = capitalize(tableName);
4400
+ const queryBase = db.query[tableName];
4401
+ if (!queryBase) {
4402
+ throw new Error(
4403
+ `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`
4404
+ );
4405
+ }
4406
+ const primaryKeyColumn = Object.values(tableInfo.columns).find(
4407
+ (col) => col.primary || col.name === "id"
4408
+ );
4409
+ if (!primaryKeyColumn) {
4410
+ throw new Error(
4411
+ `Drizzle-GraphQL Error: Table ${tableName} does not have a primary key column`
4412
+ );
4413
+ }
4414
+ mutations[`${tableName}InsertMany`] = createInsertManyResolver2(
4415
+ db,
4416
+ queryBase,
4417
+ tableInfo,
4418
+ tables,
4419
+ relations,
4420
+ primaryKeyColumn
4421
+ );
4422
+ mutations[`${tableName}UpdateMany`] = createUpdateManyResolver2(
4423
+ db,
4424
+ queryBase,
4425
+ tableInfo,
4426
+ tables,
4427
+ relations,
4428
+ primaryKeyColumn
4429
+ );
4430
+ mutations[`${tableName}DeleteMany`] = createDeleteManyResolver2(
4431
+ db,
4432
+ queryBase,
4433
+ tableInfo,
4434
+ tables,
4435
+ relations,
4436
+ primaryKeyColumn
4437
+ );
4438
+ deleteResultResolvers[`${capitalizedName}DeleteResult`] = {
4439
+ [`${tableName}FindMany`]: (parent, args, context, info) => {
4440
+ const resolverFn = parent[`${tableName}FindMany`];
4441
+ if (typeof resolverFn === "function") {
4442
+ return resolverFn(parent, args, context, info);
4443
+ }
4444
+ return [];
4445
+ }
4446
+ };
4447
+ }
4448
+ return { mutations, deleteResultResolvers };
4449
+ };
4450
+
4451
+ // src/build-schema-sdl-with-dl/generator/utils/context.ts
4452
+ function createDataLoaderContext() {
4453
+ return {
4454
+ relationLoaders: /* @__PURE__ */ new Map()
4455
+ };
4456
+ }
4457
+ function cleanupDataLoaderContext(context) {
4458
+ for (const loader of Array.from(context.relationLoaders.values())) {
4459
+ loader.clearAll();
4460
+ }
4461
+ context.relationLoaders.clear();
4462
+ }
4463
+
4464
+ // src/build-schema-sdl-with-dl/index.ts
4465
+ var buildSchemaSDL2 = (db) => {
4466
+ const schema = db._.fullSchema;
4467
+ if (!schema) {
4468
+ throw new Error(
4469
+ "Drizzle-GraphQL Error: Schema not found in drizzle instance. Make sure you're using drizzle-orm v0.30.9 or above and schema is passed to drizzle constructor!"
4470
+ );
4471
+ }
4472
+ if (!(0, import_drizzle_orm19.is)(db, import_sqlite_core7.BaseSQLiteDatabase)) {
4473
+ throw new Error(
4474
+ "Drizzle-GraphQL Error: buildSchemaSDL currently only supports SQLite databases"
4475
+ );
4476
+ }
4477
+ const { tables, relations } = generateTypes2(db, schema);
4478
+ const typeDefsArray = [];
4479
+ typeDefsArray.push(generateTypeDefs2(tables, relations));
4480
+ typeDefsArray.push(generateQueryTypeDefs2(tables));
4481
+ typeDefsArray.push(generateMutationTypeDefs2(tables));
4482
+ const typeDefs = typeDefsArray.join("\n\n");
4483
+ const queries = generateQueries2(db, tables, relations);
4484
+ const { mutations, deleteResultResolvers } = generateMutations2(
4485
+ db,
4486
+ tables,
4487
+ relations
4488
+ );
4489
+ return {
4490
+ typeDefs,
4491
+ resolvers: {
4492
+ Query: queries,
4493
+ Mutation: mutations,
4494
+ ...deleteResultResolvers
4495
+ }
4496
+ };
4497
+ };
4498
+
3269
4499
  // src/export-tool/ExportStore.ts
3270
4500
  var ExportStore = class {
3271
4501
  store = /* @__PURE__ */ new Map();
@@ -3388,10 +4618,10 @@ function createExportMiddleware() {
3388
4618
  }
3389
4619
 
3390
4620
  // src/export-tool/makeScalarAcceptExports.ts
3391
- var import_graphql11 = require("graphql");
4621
+ var import_graphql14 = require("graphql");
3392
4622
  function makeScalarAcceptExports(originalScalar) {
3393
4623
  const config = originalScalar.toConfig();
3394
- return new import_graphql11.GraphQLScalarType({
4624
+ return new import_graphql14.GraphQLScalarType({
3395
4625
  ...config,
3396
4626
  name: config.name,
3397
4627
  // Keep original name to override it in schema
@@ -3407,7 +4637,7 @@ function makeScalarAcceptExports(originalScalar) {
3407
4637
  return value;
3408
4638
  },
3409
4639
  parseLiteral(ast, variables) {
3410
- if (ast.kind === import_graphql11.Kind.STRING) {
4640
+ if (ast.kind === import_graphql14.Kind.STRING) {
3411
4641
  if (ast.value.startsWith("$_") || ast.value === "") {
3412
4642
  return ast.value;
3413
4643
  }
@@ -3421,13 +4651,13 @@ function makeScalarAcceptExports(originalScalar) {
3421
4651
  }
3422
4652
 
3423
4653
  // src/helpers.ts
3424
- var import_drizzle_orm13 = require("drizzle-orm");
4654
+ var import_drizzle_orm20 = require("drizzle-orm");
3425
4655
  function setCustomGraphQL(table, columnConfig) {
3426
4656
  for (const [columnName, config] of Object.entries(columnConfig)) {
3427
4657
  const column = table[columnName];
3428
4658
  if (!column) {
3429
4659
  console.warn(
3430
- `Warning: Column "${columnName}" not found in table "${(0, import_drizzle_orm13.getTableName)(
4660
+ `Warning: Column "${columnName}" not found in table "${(0, import_drizzle_orm20.getTableName)(
3431
4661
  table
3432
4662
  )}"`
3433
4663
  );
@@ -3451,6 +4681,9 @@ function setCustomGraphQLTypes(table, columnTypes) {
3451
4681
  0 && (module.exports = {
3452
4682
  buildSchema,
3453
4683
  buildSchemaSDL,
4684
+ buildSchemaSDLWithDataLoader,
4685
+ cleanupDataLoaderContext,
4686
+ createDataLoaderContext,
3454
4687
  createExportMiddleware,
3455
4688
  makeScalarAcceptExports,
3456
4689
  setCustomGraphQL,