drizzle-graphql-plus 0.8.14 → 0.8.16

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.js CHANGED
@@ -1,4 +1,4 @@
1
- // src/index.ts
1
+ // src/buildSchema.ts
2
2
  import { is as is6 } from "drizzle-orm";
3
3
  import { MySqlDatabase as MySqlDatabase2 } from "drizzle-orm/mysql-core";
4
4
  import { PgDatabase as PgDatabase2 } from "drizzle-orm/pg-core";
@@ -320,9 +320,6 @@ var extractSelectedColumnsFromTree = (tree, table) => {
320
320
  fieldData.fieldsByTypeName
321
321
  )) {
322
322
  for (const [subFieldName, subFieldData] of Object.entries(typeFields)) {
323
- console.log(
324
- ` Checking subField: ${subFieldName}, name: ${subFieldData.name}`
325
- );
326
323
  if (tableColumns[subFieldData.name]) {
327
324
  selectedColumns.push([subFieldData.name, true]);
328
325
  } else {
@@ -2199,7 +2196,7 @@ var generateSchemaData3 = (db, schema, relationsDepthLimit) => {
2199
2196
  return { queries, mutations, inputs, interfaces, types: outputs };
2200
2197
  };
2201
2198
 
2202
- // src/index.ts
2199
+ // src/buildSchema.ts
2203
2200
  var buildSchema = (db, config) => {
2204
2201
  const schema = db._.fullSchema;
2205
2202
  if (!schema) {
@@ -2246,7 +2243,777 @@ var buildSchema = (db, config) => {
2246
2243
  const outputSchema = new GraphQLSchema(graphQLSchemaConfig);
2247
2244
  return { schema: outputSchema, entities: generatorOutput };
2248
2245
  };
2246
+
2247
+ // src/buildSchemaSDL/index.ts
2248
+ import { is as is8 } from "drizzle-orm";
2249
+ import { BaseSQLiteDatabase as BaseSQLiteDatabase3 } from "drizzle-orm/sqlite-core";
2250
+
2251
+ // src/buildSchemaSDL/generator/schema.ts
2252
+ import {
2253
+ getTableColumns as getTableColumns3,
2254
+ getTableName,
2255
+ is as is7,
2256
+ Relations as Relations4,
2257
+ createTableRelationsHelpers as createTableRelationsHelpers4,
2258
+ One as One2
2259
+ } from "drizzle-orm";
2260
+ import { MySqlInt as MySqlInt2, MySqlSerial as MySqlSerial2 } from "drizzle-orm/mysql-core";
2261
+ import { PgInteger as PgInteger2, PgSerial as PgSerial2 } from "drizzle-orm/pg-core";
2262
+ import { SQLiteInteger as SQLiteInteger2 } from "drizzle-orm/sqlite-core";
2263
+ var allowedNameChars2 = /^[a-zA-Z0-9_]+$/;
2264
+ var customScalars = /* @__PURE__ */ new Set();
2265
+ var enumDefinitions = /* @__PURE__ */ new Map();
2266
+ var columnToSDL = (column, columnName, tableName, forceNullable = false) => {
2267
+ let baseType;
2268
+ if (column.customGraphqlType) {
2269
+ baseType = column.customGraphqlType;
2270
+ } else {
2271
+ switch (column.dataType) {
2272
+ case "boolean":
2273
+ baseType = "Boolean";
2274
+ break;
2275
+ case "json":
2276
+ if (column.columnType === "PgGeometryObject") {
2277
+ baseType = "PgGeometryObject";
2278
+ customScalars.add("PgGeometryObject");
2279
+ } else {
2280
+ baseType = "JSON";
2281
+ customScalars.add("JSON");
2282
+ }
2283
+ break;
2284
+ case "date":
2285
+ baseType = "Date";
2286
+ customScalars.add("Date");
2287
+ break;
2288
+ case "string":
2289
+ if (column.enumValues?.length) {
2290
+ const enumName = `${capitalize(tableName)}${capitalize(
2291
+ columnName
2292
+ )}Enum`;
2293
+ baseType = enumName;
2294
+ if (!enumDefinitions.has(enumName)) {
2295
+ enumDefinitions.set(enumName, {
2296
+ name: enumName,
2297
+ values: column.enumValues.map(
2298
+ (e, index) => allowedNameChars2.test(e) ? e : `Option${index}`
2299
+ )
2300
+ });
2301
+ }
2302
+ } else {
2303
+ baseType = "String";
2304
+ }
2305
+ break;
2306
+ case "bigint":
2307
+ baseType = "BigInt";
2308
+ customScalars.add("BigInt");
2309
+ break;
2310
+ case "number":
2311
+ if (is7(column, PgInteger2) || is7(column, PgSerial2) || is7(column, MySqlInt2) || is7(column, MySqlSerial2) || is7(column, SQLiteInteger2)) {
2312
+ baseType = "Int";
2313
+ } else {
2314
+ baseType = "Float";
2315
+ }
2316
+ break;
2317
+ case "buffer":
2318
+ baseType = "[Int!]";
2319
+ break;
2320
+ case "array":
2321
+ if (column.columnType === "PgVector") {
2322
+ baseType = "[Float!]";
2323
+ } else if (column.columnType === "PgGeometry") {
2324
+ baseType = "[Float!]";
2325
+ } else {
2326
+ const scalarName = `${capitalize(tableName)}${capitalize(
2327
+ columnName
2328
+ )}Array`;
2329
+ baseType = scalarName;
2330
+ customScalars.add(scalarName);
2331
+ }
2332
+ break;
2333
+ case "custom":
2334
+ default:
2335
+ if (column.columnType) {
2336
+ baseType = column.columnType;
2337
+ customScalars.add(column.columnType);
2338
+ } else {
2339
+ const customScalarName = `${capitalize(tableName)}${capitalize(
2340
+ columnName
2341
+ )}`;
2342
+ baseType = customScalarName;
2343
+ customScalars.add(customScalarName);
2344
+ }
2345
+ break;
2346
+ }
2347
+ }
2348
+ if (!forceNullable && column.notNull && !column.hasDefault && !column.defaultFn) {
2349
+ return `${baseType}!`;
2350
+ }
2351
+ return baseType;
2352
+ };
2353
+ var generateTypes = (db, schema) => {
2354
+ const tables = {};
2355
+ const schemaEntries = Object.entries(schema);
2356
+ const tableEntries = [];
2357
+ for (const [key, value] of schemaEntries) {
2358
+ if (value && typeof value === "object" && "getSQL" in value) {
2359
+ const table = value;
2360
+ const tableName = getTableName(table);
2361
+ const columns = getTableColumns3(table);
2362
+ tables[tableName] = {
2363
+ name: tableName,
2364
+ table,
2365
+ columns
2366
+ };
2367
+ tableEntries.push([tableName, table]);
2368
+ }
2369
+ }
2370
+ const rawRelations = schemaEntries.filter(([key, value]) => is7(value, Relations4)).map(([key, value]) => [
2371
+ tableEntries.find(
2372
+ ([tableName, tableValue]) => tableValue === value.table
2373
+ )[0],
2374
+ value
2375
+ ]).map(([tableName, relValue]) => [
2376
+ tableName,
2377
+ relValue.config(createTableRelationsHelpers4(tables[tableName].table))
2378
+ ]);
2379
+ const namedRelations = Object.fromEntries(
2380
+ rawRelations.map(([relName, config]) => {
2381
+ const namedConfig = Object.fromEntries(
2382
+ Object.entries(config).map(([innerRelName, innerRelValue]) => [
2383
+ innerRelName,
2384
+ {
2385
+ relation: innerRelValue,
2386
+ targetTableName: tableEntries.find(
2387
+ ([tableName, tableValue]) => tableValue === innerRelValue.referencedTable
2388
+ )[0]
2389
+ }
2390
+ ])
2391
+ );
2392
+ return [relName, namedConfig];
2393
+ })
2394
+ );
2395
+ return { tables, relations: namedRelations };
2396
+ };
2397
+ var generateTypeDefs = (tables, relations) => {
2398
+ const typeDefs = [];
2399
+ customScalars.clear();
2400
+ enumDefinitions.clear();
2401
+ for (const [tableName, tableInfo] of Object.entries(tables)) {
2402
+ const typeName = capitalize(tableName);
2403
+ const fields = [];
2404
+ for (const [columnName, column] of Object.entries(tableInfo.columns)) {
2405
+ const typeStr = columnToSDL(
2406
+ column,
2407
+ columnName,
2408
+ tableName,
2409
+ false
2410
+ );
2411
+ const description = column.customGraphqlDescription;
2412
+ if (description) {
2413
+ fields.push(` """${description}"""`);
2414
+ }
2415
+ fields.push(` ${columnName}: ${typeStr}`);
2416
+ }
2417
+ const tableRelations = relations[tableName];
2418
+ if (tableRelations) {
2419
+ for (const [relationName, relationInfo] of Object.entries(
2420
+ tableRelations
2421
+ )) {
2422
+ const isOne = is7(relationInfo.relation, One2);
2423
+ const targetTableName = relationInfo.targetTableName;
2424
+ const targetTypeName = capitalize(targetTableName);
2425
+ if (isOne) {
2426
+ fields.push(
2427
+ ` ${relationName}(where: ${targetTypeName}Filters): ${targetTypeName}`
2428
+ );
2429
+ } else {
2430
+ fields.push(
2431
+ ` ${relationName}(where: ${targetTypeName}Filters, orderBy: ${targetTypeName}OrderBy, limit: Int, offset: Int): [${targetTypeName}!]!`
2432
+ );
2433
+ }
2434
+ }
2435
+ }
2436
+ typeDefs.push(`type ${typeName} {
2437
+ ${fields.join("\n")}
2438
+ }`);
2439
+ const insertFields = [];
2440
+ for (const [columnName, column] of Object.entries(tableInfo.columns)) {
2441
+ const typeStr = columnToSDL(
2442
+ column,
2443
+ columnName,
2444
+ tableName,
2445
+ false
2446
+ );
2447
+ const nullableType = typeStr.endsWith("!") ? typeStr.slice(0, -1) : typeStr;
2448
+ insertFields.push(` ${columnName}: ${nullableType}`);
2449
+ }
2450
+ if (insertFields.length > 0) {
2451
+ typeDefs.push(
2452
+ `input ${typeName}InsertInput {
2453
+ ${insertFields.join("\n")}
2454
+ }`
2455
+ );
2456
+ }
2457
+ const updateFields = [];
2458
+ for (const [columnName, column] of Object.entries(tableInfo.columns)) {
2459
+ const typeStr = columnToSDL(
2460
+ column,
2461
+ columnName,
2462
+ tableName,
2463
+ true
2464
+ );
2465
+ updateFields.push(` ${columnName}: ${typeStr}`);
2466
+ }
2467
+ typeDefs.push(
2468
+ `input ${typeName}UpdateInput {
2469
+ ${updateFields.join("\n")}
2470
+ }`
2471
+ );
2472
+ for (const [columnName, column] of Object.entries(tableInfo.columns)) {
2473
+ const typeStr = columnToSDL(
2474
+ column,
2475
+ columnName,
2476
+ tableName,
2477
+ true
2478
+ );
2479
+ const filterName = `${typeName}${capitalize(columnName)}Filters`;
2480
+ const filterFields = [];
2481
+ filterFields.push(` eq: ${typeStr}`);
2482
+ filterFields.push(` ne: ${typeStr}`);
2483
+ filterFields.push(` lt: ${typeStr}`);
2484
+ filterFields.push(` lte: ${typeStr}`);
2485
+ filterFields.push(` gt: ${typeStr}`);
2486
+ filterFields.push(` gte: ${typeStr}`);
2487
+ filterFields.push(` like: String`);
2488
+ filterFields.push(` notLike: String`);
2489
+ filterFields.push(` ilike: String`);
2490
+ filterFields.push(` notIlike: String`);
2491
+ filterFields.push(` inArray: [${typeStr}!]`);
2492
+ filterFields.push(` notInArray: [${typeStr}!]`);
2493
+ filterFields.push(` isNull: Boolean`);
2494
+ filterFields.push(` isNotNull: Boolean`);
2495
+ const orFilterName = `${typeName}${capitalize(columnName)}FiltersOr`;
2496
+ typeDefs.push(`input ${orFilterName} {
2497
+ ${filterFields.join("\n")}
2498
+ }`);
2499
+ filterFields.push(` OR: [${orFilterName}!]`);
2500
+ typeDefs.push(`input ${filterName} {
2501
+ ${filterFields.join("\n")}
2502
+ }`);
2503
+ }
2504
+ const whereFields = [];
2505
+ for (const columnName of Object.keys(tableInfo.columns)) {
2506
+ const filterName = `${typeName}${capitalize(columnName)}Filters`;
2507
+ whereFields.push(` ${columnName}: ${filterName}`);
2508
+ }
2509
+ whereFields.push(` OR: [${typeName}FiltersOr!]`);
2510
+ const filtersOrFields = [];
2511
+ for (const columnName of Object.keys(tableInfo.columns)) {
2512
+ const filterName = `${typeName}${capitalize(columnName)}Filters`;
2513
+ filtersOrFields.push(` ${columnName}: ${filterName}`);
2514
+ }
2515
+ typeDefs.push(
2516
+ `input ${typeName}FiltersOr {
2517
+ ${filtersOrFields.join("\n")}
2518
+ }`
2519
+ );
2520
+ typeDefs.push(`input ${typeName}Filters {
2521
+ ${whereFields.join("\n")}
2522
+ }`);
2523
+ const orderByFields = [];
2524
+ for (const columnName of Object.keys(tableInfo.columns)) {
2525
+ orderByFields.push(` ${columnName}: InnerOrder`);
2526
+ }
2527
+ typeDefs.push(`input ${typeName}OrderBy {
2528
+ ${orderByFields.join("\n")}
2529
+ }`);
2530
+ }
2531
+ const allDefs = [];
2532
+ if (customScalars.size > 0) {
2533
+ for (const scalarName of Array.from(customScalars).sort()) {
2534
+ allDefs.push(`scalar ${scalarName}`);
2535
+ }
2536
+ }
2537
+ if (enumDefinitions.size > 0) {
2538
+ for (const enumDef of enumDefinitions.values()) {
2539
+ const valueStrings = enumDef.values.map((v) => ` ${v}`);
2540
+ allDefs.push(`enum ${enumDef.name} {
2541
+ ${valueStrings.join("\n")}
2542
+ }`);
2543
+ }
2544
+ }
2545
+ allDefs.push(`enum OrderByDirection {
2546
+ asc
2547
+ desc
2548
+ }`);
2549
+ allDefs.push(`input InnerOrder {
2550
+ direction: OrderByDirection!
2551
+ priority: Int!
2552
+ }`);
2553
+ allDefs.push(...typeDefs);
2554
+ return allDefs.join("\n\n");
2555
+ };
2556
+ var generateQueryTypeDefs = (tables) => {
2557
+ const queryFields = [];
2558
+ for (const tableName of Object.keys(tables)) {
2559
+ const typeName = capitalize(tableName);
2560
+ queryFields.push(
2561
+ ` ${tableName}(where: ${typeName}Filters, orderBy: ${typeName}OrderBy, limit: Int, offset: Int): [${typeName}!]!`
2562
+ );
2563
+ }
2564
+ return `type Query {
2565
+ ${queryFields.join("\n")}
2566
+ }`;
2567
+ };
2568
+ var generateMutationTypeDefs = (tables) => {
2569
+ const mutationFields = [];
2570
+ for (const tableName of Object.keys(tables)) {
2571
+ const typeName = capitalize(tableName);
2572
+ mutationFields.push(
2573
+ ` insert${typeName}(values: [${typeName}InsertInput!]!): [${typeName}!]!`
2574
+ );
2575
+ mutationFields.push(
2576
+ ` update${typeName}(where: ${typeName}Filters, set: ${typeName}UpdateInput!): [${typeName}!]!`
2577
+ );
2578
+ mutationFields.push(
2579
+ ` delete${typeName}(where: ${typeName}Filters): [${typeName}!]!`
2580
+ );
2581
+ }
2582
+ return `type Mutation {
2583
+ ${mutationFields.join("\n")}
2584
+ }`;
2585
+ };
2586
+
2587
+ // src/buildSchemaSDL/generator/queries.ts
2588
+ import {
2589
+ eq as eq2,
2590
+ gt as gt2,
2591
+ gte as gte2,
2592
+ lt as lt2,
2593
+ lte as lte2,
2594
+ ne as ne2,
2595
+ inArray as inArray2,
2596
+ notInArray as notInArray2,
2597
+ like as like2,
2598
+ notLike as notLike2,
2599
+ ilike as ilike2,
2600
+ notIlike as notIlike2,
2601
+ isNull as isNull2,
2602
+ isNotNull as isNotNull2,
2603
+ and as and2,
2604
+ or as or2,
2605
+ asc as asc2,
2606
+ desc as desc2
2607
+ } from "drizzle-orm";
2608
+ import { GraphQLError as GraphQLError6 } from "graphql";
2609
+ import { parseResolveInfo as parseResolveInfo4 } from "graphql-parse-resolve-info";
2610
+ var extractFiltersColumn2 = (column, columnName, operators) => {
2611
+ const entries = Object.entries(operators);
2612
+ if (!entries.length)
2613
+ return void 0;
2614
+ if (operators.OR && operators.OR.length > 0) {
2615
+ if (entries.length > 1) {
2616
+ throw new GraphQLError6(
2617
+ `WHERE ${columnName}: Cannot specify both fields and 'OR' in column operators!`
2618
+ );
2619
+ }
2620
+ const variants2 = [];
2621
+ for (const variant of operators.OR) {
2622
+ const extracted = extractFiltersColumn2(column, columnName, variant);
2623
+ if (extracted)
2624
+ variants2.push(extracted);
2625
+ }
2626
+ return variants2.length ? variants2.length > 1 ? or2(...variants2) : variants2[0] : void 0;
2627
+ }
2628
+ const variants = [];
2629
+ for (const [operatorName, operatorValue] of entries) {
2630
+ if (operatorValue === null || operatorValue === false)
2631
+ continue;
2632
+ switch (operatorName) {
2633
+ case "eq":
2634
+ case "ne":
2635
+ case "gt":
2636
+ case "gte":
2637
+ case "lt":
2638
+ case "lte": {
2639
+ const singleValue = remapFromGraphQLCore(
2640
+ operatorValue,
2641
+ column,
2642
+ columnName
2643
+ );
2644
+ const opMap = { eq: eq2, ne: ne2, gt: gt2, gte: gte2, lt: lt2, lte: lte2 };
2645
+ variants.push(opMap[operatorName](column, singleValue));
2646
+ break;
2647
+ }
2648
+ case "like":
2649
+ case "notLike":
2650
+ case "ilike":
2651
+ case "notIlike": {
2652
+ const opMap = { like: like2, notLike: notLike2, ilike: ilike2, notIlike: notIlike2 };
2653
+ variants.push(opMap[operatorName](column, operatorValue));
2654
+ break;
2655
+ }
2656
+ case "inArray":
2657
+ case "notInArray": {
2658
+ if (!operatorValue.length) {
2659
+ throw new GraphQLError6(
2660
+ `WHERE ${columnName}: Unable to use operator ${operatorName} with an empty array!`
2661
+ );
2662
+ }
2663
+ const arrayValue = operatorValue.map(
2664
+ (val) => remapFromGraphQLCore(val, column, columnName)
2665
+ );
2666
+ const opMap = { inArray: inArray2, notInArray: notInArray2 };
2667
+ variants.push(opMap[operatorName](column, arrayValue));
2668
+ break;
2669
+ }
2670
+ case "isNull":
2671
+ case "isNotNull": {
2672
+ const opMap = { isNull: isNull2, isNotNull: isNotNull2 };
2673
+ variants.push(opMap[operatorName](column));
2674
+ break;
2675
+ }
2676
+ }
2677
+ }
2678
+ return variants.length ? variants.length > 1 ? and2(...variants) : variants[0] : void 0;
2679
+ };
2680
+ var buildWhereClause = (tableInfo, where) => {
2681
+ if (!where || Object.keys(where).length === 0) {
2682
+ return void 0;
2683
+ }
2684
+ if (where.OR && where.OR.length > 0) {
2685
+ if (Object.keys(where).length > 1) {
2686
+ throw new GraphQLError6(
2687
+ `WHERE ${tableInfo.name}: Cannot specify both fields and 'OR' in table filters!`
2688
+ );
2689
+ }
2690
+ const variants = [];
2691
+ for (const variant of where.OR) {
2692
+ const extracted = buildWhereClause(tableInfo, variant);
2693
+ if (extracted)
2694
+ variants.push(extracted);
2695
+ }
2696
+ return variants.length ? variants.length > 1 ? or2(...variants) : variants[0] : void 0;
2697
+ }
2698
+ const conditions = [];
2699
+ for (const [columnName, operators] of Object.entries(where)) {
2700
+ if (columnName === "OR")
2701
+ continue;
2702
+ if (!operators || Object.keys(operators).length === 0)
2703
+ continue;
2704
+ const column = tableInfo.columns[columnName];
2705
+ if (!column)
2706
+ continue;
2707
+ const extracted = extractFiltersColumn2(
2708
+ column,
2709
+ columnName,
2710
+ operators
2711
+ );
2712
+ if (extracted)
2713
+ conditions.push(extracted);
2714
+ }
2715
+ if (conditions.length === 0)
2716
+ return void 0;
2717
+ if (conditions.length === 1)
2718
+ return conditions[0];
2719
+ return and2(...conditions);
2720
+ };
2721
+ var buildOrderByClause = (tableInfo, orderBy) => {
2722
+ if (!orderBy || Object.keys(orderBy).length === 0) {
2723
+ return void 0;
2724
+ }
2725
+ const orderEntries = Object.entries(orderBy).map(([columnName, field]) => ({
2726
+ columnName,
2727
+ ...field
2728
+ }));
2729
+ orderEntries.sort((a, b) => a.priority - b.priority);
2730
+ const orderClauses = [];
2731
+ for (const entry of orderEntries) {
2732
+ const column = tableInfo.columns[entry.columnName];
2733
+ if (column) {
2734
+ orderClauses.push(
2735
+ entry.direction === "desc" ? desc2(column) : asc2(column)
2736
+ );
2737
+ }
2738
+ }
2739
+ return orderClauses.length > 0 ? orderClauses : void 0;
2740
+ };
2741
+ var extractSelectedColumns = (fields, tableInfo) => {
2742
+ const columns = {};
2743
+ for (const fieldName of Object.keys(fields)) {
2744
+ if (tableInfo.columns[fieldName]) {
2745
+ columns[fieldName] = true;
2746
+ }
2747
+ }
2748
+ return Object.keys(columns).length > 0 ? columns : {};
2749
+ };
2750
+ var extractRelationsParams2 = (relationMap, tables, tableName, fields) => {
2751
+ const relations = relationMap[tableName];
2752
+ if (!relations)
2753
+ return void 0;
2754
+ const args = {};
2755
+ for (const [relName, { targetTableName, relation }] of Object.entries(
2756
+ relations
2757
+ )) {
2758
+ const relationField = fields[relName];
2759
+ if (!relationField)
2760
+ continue;
2761
+ const allFields = {};
2762
+ if (relationField.fieldsByTypeName) {
2763
+ for (const typeFields of Object.values(relationField.fieldsByTypeName)) {
2764
+ Object.assign(allFields, typeFields);
2765
+ }
2766
+ }
2767
+ const targetTable = tables[targetTableName];
2768
+ if (!targetTable)
2769
+ continue;
2770
+ const thisRecord = {
2771
+ columns: extractSelectedColumns(allFields, targetTable)
2772
+ };
2773
+ const relationArgs = relationField.args;
2774
+ if (relationArgs) {
2775
+ if (relationArgs["where"]) {
2776
+ thisRecord.where = buildWhereClause(
2777
+ targetTable,
2778
+ relationArgs["where"]
2779
+ );
2780
+ }
2781
+ if (relationArgs["orderBy"]) {
2782
+ thisRecord.orderBy = buildOrderByClause(
2783
+ targetTable,
2784
+ relationArgs["orderBy"]
2785
+ );
2786
+ }
2787
+ if (relationArgs["limit"] !== void 0) {
2788
+ thisRecord.limit = relationArgs["limit"];
2789
+ }
2790
+ if (relationArgs["offset"] !== void 0) {
2791
+ thisRecord.offset = relationArgs["offset"];
2792
+ }
2793
+ }
2794
+ const nestedWith = extractRelationsParams2(
2795
+ relationMap,
2796
+ tables,
2797
+ targetTableName,
2798
+ allFields
2799
+ );
2800
+ if (nestedWith) {
2801
+ thisRecord.with = nestedWith;
2802
+ }
2803
+ args[relName] = thisRecord;
2804
+ }
2805
+ return Object.keys(args).length > 0 ? args : void 0;
2806
+ };
2807
+ var generateQueries = (db, tables, relations) => {
2808
+ const queries = {};
2809
+ for (const [tableName, tableInfo] of Object.entries(tables)) {
2810
+ const queryBase = db.query[tableName];
2811
+ if (!queryBase) {
2812
+ throw new Error(
2813
+ `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`
2814
+ );
2815
+ }
2816
+ queries[tableName] = async (parent, args, context, info) => {
2817
+ try {
2818
+ const { where, orderBy, limit, offset } = args;
2819
+ const parsedInfo = parseResolveInfo4(info, {
2820
+ deep: true
2821
+ });
2822
+ const allFields = {};
2823
+ if (parsedInfo.fieldsByTypeName) {
2824
+ for (const fields of Object.values(parsedInfo.fieldsByTypeName)) {
2825
+ Object.assign(allFields, fields);
2826
+ }
2827
+ }
2828
+ const result = await queryBase.findMany({
2829
+ columns: extractSelectedColumns(allFields, tableInfo),
2830
+ offset,
2831
+ limit,
2832
+ orderBy: buildOrderByClause(tableInfo, orderBy),
2833
+ where: buildWhereClause(tableInfo, where),
2834
+ with: extractRelationsParams2(relations, tables, tableName, allFields)
2835
+ });
2836
+ return result;
2837
+ } catch (e) {
2838
+ if (typeof e === "object" && e !== null && "message" in e) {
2839
+ throw new GraphQLError6(String(e.message));
2840
+ }
2841
+ throw e;
2842
+ }
2843
+ };
2844
+ }
2845
+ return queries;
2846
+ };
2847
+
2848
+ // src/buildSchemaSDL/generator/mutations.ts
2849
+ import { eq as eq3, and as and3, or as or3 } from "drizzle-orm";
2850
+ import { GraphQLError as GraphQLError7 } from "graphql";
2851
+ var buildWhereClause2 = (tableInfo, where) => {
2852
+ if (!where || Object.keys(where).length === 0) {
2853
+ return void 0;
2854
+ }
2855
+ if (where.OR && where.OR.length > 0) {
2856
+ if (Object.keys(where).length > 1) {
2857
+ throw new GraphQLError7(
2858
+ `WHERE ${tableInfo.name}: Cannot specify both fields and 'OR' in table filters!`
2859
+ );
2860
+ }
2861
+ const variants = [];
2862
+ for (const variant of where.OR) {
2863
+ const extracted = buildWhereClause2(tableInfo, variant);
2864
+ if (extracted)
2865
+ variants.push(extracted);
2866
+ }
2867
+ return variants.length ? variants.length > 1 ? or3(...variants) : variants[0] : void 0;
2868
+ }
2869
+ const conditions = [];
2870
+ for (const [key, value] of Object.entries(where)) {
2871
+ if (key === "OR")
2872
+ continue;
2873
+ if (value === null || value === void 0)
2874
+ continue;
2875
+ const column = tableInfo.columns[key];
2876
+ if (column) {
2877
+ const filters = value;
2878
+ if (typeof filters === "object" && filters.eq !== void 0) {
2879
+ conditions.push(eq3(column, filters.eq));
2880
+ } else if (typeof filters !== "object" || !Array.isArray(filters)) {
2881
+ conditions.push(eq3(column, filters));
2882
+ }
2883
+ }
2884
+ }
2885
+ if (conditions.length === 0)
2886
+ return void 0;
2887
+ if (conditions.length === 1)
2888
+ return conditions[0];
2889
+ return and3(...conditions);
2890
+ };
2891
+ var generateMutations = (db, tables) => {
2892
+ const mutations = {};
2893
+ for (const [tableName, tableInfo] of Object.entries(tables)) {
2894
+ const capitalizedName = capitalize(tableName);
2895
+ mutations[`insert${capitalizedName}`] = async (parent, args, context, info) => {
2896
+ try {
2897
+ const { values } = args;
2898
+ if (!values || values.length === 0) {
2899
+ throw new GraphQLError7("No values provided for insert");
2900
+ }
2901
+ const remappedValues = remapFromGraphQLArrayInput(
2902
+ values,
2903
+ tableInfo.table
2904
+ );
2905
+ const result = await db.insert(tableInfo.table).values(remappedValues).returning();
2906
+ return result;
2907
+ } catch (e) {
2908
+ if (typeof e === "object" && e !== null && "message" in e) {
2909
+ throw new GraphQLError7(String(e.message));
2910
+ }
2911
+ throw e;
2912
+ }
2913
+ };
2914
+ mutations[`update${capitalizedName}`] = async (parent, args, context, info) => {
2915
+ try {
2916
+ const { where, set } = args;
2917
+ if (!set || Object.keys(set).length === 0) {
2918
+ throw new GraphQLError7("No values provided for update");
2919
+ }
2920
+ const remappedSet = remapFromGraphQLSingleInput(set, tableInfo.table);
2921
+ const whereClause = buildWhereClause2(tableInfo, where);
2922
+ let query = db.update(tableInfo.table).set(remappedSet);
2923
+ if (whereClause) {
2924
+ query = query.where(whereClause);
2925
+ }
2926
+ const result = await query.returning();
2927
+ return result;
2928
+ } catch (e) {
2929
+ if (typeof e === "object" && e !== null && "message" in e) {
2930
+ throw new GraphQLError7(String(e.message));
2931
+ }
2932
+ throw e;
2933
+ }
2934
+ };
2935
+ mutations[`delete${capitalizedName}`] = async (parent, args, context, info) => {
2936
+ try {
2937
+ const { where } = args;
2938
+ const whereClause = buildWhereClause2(tableInfo, where);
2939
+ let deleteQuery = db.delete(tableInfo.table);
2940
+ if (whereClause) {
2941
+ deleteQuery = deleteQuery.where(whereClause);
2942
+ }
2943
+ const result = await deleteQuery.returning();
2944
+ return result;
2945
+ } catch (e) {
2946
+ if (typeof e === "object" && e !== null && "message" in e) {
2947
+ throw new GraphQLError7(String(e.message));
2948
+ }
2949
+ throw e;
2950
+ }
2951
+ };
2952
+ }
2953
+ return mutations;
2954
+ };
2955
+
2956
+ // src/buildSchemaSDL/index.ts
2957
+ var buildSchemaSDL = (db, config) => {
2958
+ const schema = db._.fullSchema;
2959
+ if (!schema) {
2960
+ throw new Error(
2961
+ "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!"
2962
+ );
2963
+ }
2964
+ if (!is8(db, BaseSQLiteDatabase3)) {
2965
+ throw new Error(
2966
+ "Drizzle-GraphQL Error: buildSchemaSDL currently only supports SQLite databases"
2967
+ );
2968
+ }
2969
+ const { tables, relations } = generateTypes(db, schema);
2970
+ const typeDefsArray = [];
2971
+ typeDefsArray.push(generateTypeDefs(tables, relations));
2972
+ typeDefsArray.push(generateQueryTypeDefs(tables));
2973
+ typeDefsArray.push(generateMutationTypeDefs(tables));
2974
+ const typeDefs = typeDefsArray.join("\n\n");
2975
+ const queries = generateQueries(db, tables, relations);
2976
+ const mutations = generateMutations(db, tables);
2977
+ return {
2978
+ typeDefs,
2979
+ resolvers: {
2980
+ Query: queries,
2981
+ Mutation: mutations
2982
+ }
2983
+ };
2984
+ };
2985
+
2986
+ // src/helpers.ts
2987
+ import { getTableName as getTableName2 } from "drizzle-orm";
2988
+ function setCustomGraphQL(table, columnConfig) {
2989
+ for (const [columnName, config] of Object.entries(columnConfig)) {
2990
+ const column = table[columnName];
2991
+ if (!column) {
2992
+ console.warn(
2993
+ `Warning: Column "${columnName}" not found in table "${getTableName2(
2994
+ table
2995
+ )}"`
2996
+ );
2997
+ continue;
2998
+ }
2999
+ if (typeof config === "string") {
3000
+ column.customGraphqlType = config;
3001
+ } else if (config && typeof config === "object") {
3002
+ const fieldConfig = config;
3003
+ column.customGraphqlType = fieldConfig.type;
3004
+ if (fieldConfig.description) {
3005
+ column.customGraphqlDescription = fieldConfig.description;
3006
+ }
3007
+ }
3008
+ }
3009
+ }
3010
+ function setCustomGraphQLTypes(table, columnTypes) {
3011
+ setCustomGraphQL(table, columnTypes);
3012
+ }
2249
3013
  export {
2250
- buildSchema
3014
+ buildSchema,
3015
+ buildSchemaSDL,
3016
+ setCustomGraphQL,
3017
+ setCustomGraphQLTypes
2251
3018
  };
2252
3019
  //# sourceMappingURL=index.js.map