@vantreeseba/drizzle-graphql 7.5.0 → 7.7.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.cjs CHANGED
@@ -1144,7 +1144,7 @@ var batchedPaginatedRelationQuery = async (db, targetTable, foreignCol, whereCon
1144
1144
  }
1145
1145
  return rows;
1146
1146
  };
1147
- var createRelationResolverFactory = (db, tables, nullOrdering, filterCtx, limits) => ({ tableName, relationName, relEntry, isOne }) => {
1147
+ var createRelationResolverFactory = (db, tables, nullOrdering, filterCtx, limits, policies) => ({ tableName, relationName, relEntry, isOne }) => {
1148
1148
  const parentTable = tables[tableName];
1149
1149
  const targetTableName = relEntry.targetTableName;
1150
1150
  const targetTable = tables[targetTableName];
@@ -1166,7 +1166,14 @@ var createRelationResolverFactory = (db, tables, nullOrdering, filterCtx, limits
1166
1166
  if (localValue == null) {
1167
1167
  return isOne ? null : [];
1168
1168
  }
1169
- const { where: whereArg, orderBy: orderByArg, limit: requestedLimit, offset, after } = args ?? {};
1169
+ const {
1170
+ where: whereArg,
1171
+ orderBy: orderByArg,
1172
+ limit: requestedLimit,
1173
+ offset,
1174
+ after,
1175
+ deleted
1176
+ } = args ?? {};
1170
1177
  const limit = applyLimitPolicy(requestedLimit, limitPolicy, `${tableName}.${relationName}`);
1171
1178
  const distinct = (args ?? {}).distinct?.length ? (args ?? {}).distinct : void 0;
1172
1179
  const cursorSelected = !isOne && !!info && selectsCursorField(info, targetTable);
@@ -1197,6 +1204,7 @@ var createRelationResolverFactory = (db, tables, nullOrdering, filterCtx, limits
1197
1204
  orderBy: orderByArg ?? null,
1198
1205
  limit: limit ?? null,
1199
1206
  offset: offset ?? null,
1207
+ deleted: deleted ?? null,
1200
1208
  after: after ?? null,
1201
1209
  distinct: distinct ?? null,
1202
1210
  cursor: cursorEntries ? 1 : 0
@@ -1205,10 +1213,17 @@ var createRelationResolverFactory = (db, tables, nullOrdering, filterCtx, limits
1205
1213
  const loader = getOrCreateLoader(context, loaderKey, async (parentIds) => {
1206
1214
  const executor = resolveExecutor(db, context);
1207
1215
  const uniqueIds = [...new Set(parentIds)];
1208
- let whereCondition = (0, import_drizzle_orm4.and)(
1209
- (0, import_drizzle_orm4.inArray)(foreignCol, uniqueIds),
1210
- whereArg ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName)) : void 0,
1211
- cursorValues ? buildCursorCondition(targetTable, cursorEntries, cursorValues, nullOrdering) : void 0
1216
+ const scope = resolveScope(policies, context, filterCtx);
1217
+ let whereCondition = withScope(
1218
+ scope,
1219
+ targetTableName,
1220
+ targetTable,
1221
+ (0, import_drizzle_orm4.and)(
1222
+ (0, import_drizzle_orm4.inArray)(foreignCol, uniqueIds),
1223
+ whereArg ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName)) : void 0,
1224
+ cursorValues ? buildCursorCondition(targetTable, cursorEntries, cursorValues, nullOrdering) : void 0
1225
+ ),
1226
+ deleted
1212
1227
  );
1213
1228
  if (distinct) {
1214
1229
  const keys = await selectDistinctKeys({
@@ -2013,7 +2028,8 @@ var generateSelectFields = (tables, tableName, relationMap, fromTableName, fromR
2013
2028
  {
2014
2029
  type: isRequired ? new import_graphql5.GraphQLNonNull(relType) : relType,
2015
2030
  args: {
2016
- where: { type: relSelectData.filters }
2031
+ where: { type: relSelectData.filters },
2032
+ ...deletedArg(cacheCtx.softDeleteOf, targetTableName)
2017
2033
  },
2018
2034
  resolve,
2019
2035
  ...relationDocs,
@@ -2032,6 +2048,7 @@ var generateSelectFields = (tables, tableName, relationMap, fromTableName, fromR
2032
2048
  orderBy: { type: relSelectData.order },
2033
2049
  offset: { type: import_graphql5.GraphQLInt },
2034
2050
  limit: { type: import_graphql5.GraphQLInt },
2051
+ ...deletedArg(cacheCtx.softDeleteOf, targetTableName),
2035
2052
  after: {
2036
2053
  type: import_graphql5.GraphQLString,
2037
2054
  description: "Keyset pagination: only return related rows strictly after this cursor (a row's `cursor` field from a previous page of this relation, under the same orderBy)."
@@ -2059,7 +2076,8 @@ var generateSelectFields = (tables, tableName, relationMap, fromTableName, fromR
2059
2076
  {
2060
2077
  type: new import_graphql5.GraphQLNonNull(relationAggregate.type),
2061
2078
  args: {
2062
- where: { type: relSelectData.filters }
2079
+ where: { type: relSelectData.filters },
2080
+ ...deletedArg(cacheCtx.softDeleteOf, targetTableName)
2063
2081
  },
2064
2082
  resolve: relationAggregate.resolve,
2065
2083
  extensions: {
@@ -2114,9 +2132,14 @@ var generateTableTypes = (tableName, tables, relationMap, withReturning, relatio
2114
2132
  const table = tables[tableName];
2115
2133
  const columns = visibleColumns(table);
2116
2134
  const columnEntries = Object.entries(columns);
2135
+ const contextColumns = cacheCtx.contextValuesOf?.(tableName);
2136
+ const markerColumn = cacheCtx.softDeleteOf?.(tableName)?.columnName;
2137
+ const writableEntries = contextColumns || markerColumn ? columnEntries.filter(
2138
+ ([columnName]) => !(contextColumns && columnName in contextColumns) && columnName !== markerColumn
2139
+ ) : columnEntries;
2117
2140
  const relaxedColumns = nestedWrites?.relaxedColumns(tableName);
2118
2141
  const insertFields = Object.fromEntries(
2119
- columnEntries.map(([columnName, column]) => {
2142
+ writableEntries.map(([columnName, column]) => {
2120
2143
  const converted = drizzleColumnToGraphQLType(
2121
2144
  column,
2122
2145
  columnName,
@@ -2132,7 +2155,7 @@ var generateTableTypes = (tableName, tables, relationMap, withReturning, relatio
2132
2155
  })
2133
2156
  );
2134
2157
  const updateFields = Object.fromEntries(
2135
- columnEntries.map(([columnName, column]) => {
2158
+ writableEntries.map(([columnName, column]) => {
2136
2159
  const converted = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);
2137
2160
  const operations = cacheCtx.featureOf(tableName).fieldUpdateOperations ? fieldUpdateInputType(column, columnName, tableName) : void 0;
2138
2161
  const field = operations ? { ...converted, type: operations } : converted;
@@ -2655,7 +2678,132 @@ var extractFilters = (table, tableName, filters, relationCtx) => {
2655
2678
  }
2656
2679
  return variants.length ? variants.length > 1 ? (0, import_drizzle_orm4.and)(...variants) : variants[0] : void 0;
2657
2680
  };
2658
- var extractRelationsParamsInner = (relationMap, tables, tableName, typeName, originField, typeNameMapper, _isInitial = false, filterCtx, limits) => {
2681
+ var deletedFilterEnum = new import_graphql5.GraphQLEnumType({
2682
+ name: "DeletedFilter",
2683
+ description: "Which rows a read over a soft-deleting table returns.",
2684
+ values: {
2685
+ EXCLUDE: { value: "EXCLUDE", description: "Only rows that are not marked deleted. The default." },
2686
+ INCLUDE: { value: "INCLUDE", description: "Marked and unmarked rows alike." },
2687
+ ONLY: { value: "ONLY", description: "Only rows that are marked deleted \u2014 a trash view." }
2688
+ }
2689
+ });
2690
+ var resolveSoftDeleteInfo = (table, tableName, declaration) => {
2691
+ const config = typeof declaration === "string" ? { column: declaration } : declaration;
2692
+ const columnName = config?.column;
2693
+ if (typeof columnName !== "string" || !columnName) {
2694
+ throw new Error(
2695
+ `Drizzle-GraphQL Error: config.softDelete.${tableName} must be a column name or an object with a 'column' property.`
2696
+ );
2697
+ }
2698
+ const column = (0, import_drizzle_orm4.getColumns)(table)[columnName];
2699
+ if (!column) {
2700
+ throw new Error(
2701
+ `Drizzle-GraphQL Error: config.softDelete names '${tableName}.${columnName}', which is not a column of that table.`
2702
+ );
2703
+ }
2704
+ const nullable = !column.notNull;
2705
+ const { type: baseType, constraint } = (0, import_drizzle_orm4.extractExtendedColumnType)(column);
2706
+ const hasDeleted = "deletedValue" in config && config.deletedValue !== void 0;
2707
+ const writeDeleted = hasDeleted ? typeof config.deletedValue === "function" ? config.deletedValue : () => config.deletedValue : constraint === "date" && baseType === "object" ? () => /* @__PURE__ */ new Date() : baseType === "string" ? () => (/* @__PURE__ */ new Date()).toISOString() : baseType === "number" ? () => Date.now() : baseType === "bigint" ? () => BigInt(Date.now()) : () => true;
2708
+ let marker;
2709
+ if (!nullable) {
2710
+ if (hasDeleted && typeof config.deletedValue !== "function") {
2711
+ marker = config.deletedValue;
2712
+ } else if (!hasDeleted && baseType === "boolean") {
2713
+ marker = true;
2714
+ } else {
2715
+ throw new Error(
2716
+ `Drizzle-GraphQL Error: config.softDelete.${tableName} marks a NOT NULL column ('${columnName}'), so 'deletedValue' must be a constant that means deleted \u2014 not a function, and not omitted for a non-boolean column.`
2717
+ );
2718
+ }
2719
+ }
2720
+ const hasRestored = "restoredValue" in config;
2721
+ const writeRestored = hasRestored ? config.restoredValue : nullable ? null : baseType === "boolean" ? false : void 0;
2722
+ if (!nullable && writeRestored === void 0) {
2723
+ throw new Error(
2724
+ `Drizzle-GraphQL Error: config.softDelete.${tableName} marks a NOT NULL column ('${columnName}'), so 'restoredValue' must say what restoring writes back.`
2725
+ );
2726
+ }
2727
+ return { columnName, column, nullable, writeDeleted, writeRestored, marker };
2728
+ };
2729
+ var softDeletePredicate = (info, table, mode) => {
2730
+ if (mode === "INCLUDE") {
2731
+ return void 0;
2732
+ }
2733
+ const column = table?.[info.columnName] ?? info.column;
2734
+ if (info.nullable) {
2735
+ return mode === "ONLY" ? (0, import_drizzle_orm4.isNotNull)(column) : (0, import_drizzle_orm4.isNull)(column);
2736
+ }
2737
+ return mode === "ONLY" ? (0, import_drizzle_orm4.eq)(column, info.marker) : (0, import_drizzle_orm4.ne)(column, info.marker);
2738
+ };
2739
+ var resolveScope = (policies, context, filterCtx) => {
2740
+ const scopes = policies?.scope;
2741
+ const softDelete = policies?.softDelete;
2742
+ if (!scopes && !softDelete) {
2743
+ return void 0;
2744
+ }
2745
+ return {
2746
+ has: (tableName, mode) => !!scopes?.(tableName) || !!softDelete?.(tableName) && (mode ?? "EXCLUDE") !== "INCLUDE",
2747
+ on: (tableName, table, mode) => {
2748
+ const marked = softDelete?.(tableName);
2749
+ const deleted = marked ? softDeletePredicate(marked, table, mode ?? "EXCLUDE") : void 0;
2750
+ const hook = scopes?.(tableName);
2751
+ if (!hook) {
2752
+ return deleted;
2753
+ }
2754
+ const predicate = hook(context, table);
2755
+ if (predicate === void 0 || predicate === null) {
2756
+ return deleted;
2757
+ }
2758
+ if ((0, import_drizzle_orm4.is)(predicate, import_drizzle_orm4.SQL)) {
2759
+ return (0, import_drizzle_orm4.and)(deleted, predicate);
2760
+ }
2761
+ if (typeof predicate !== "object") {
2762
+ throw new import_graphql5.GraphQLError(
2763
+ `Drizzle-GraphQL Error: the scope for '${tableName}' returned a ${typeof predicate}. A scope returns a filter object, a Drizzle SQL expression, or undefined.`
2764
+ );
2765
+ }
2766
+ return (0, import_drizzle_orm4.and)(deleted, extractFilters(table, tableName, predicate, relationFilterCtx(filterCtx, tableName)));
2767
+ }
2768
+ };
2769
+ };
2770
+ var withScope = (scope, tableName, table, condition, mode) => {
2771
+ const predicate = scope?.on(tableName, table, mode);
2772
+ return predicate ? (0, import_drizzle_orm4.and)(condition, predicate) : condition;
2773
+ };
2774
+ var bindPolicies = (policies, filterCtx) => policies?.scope || policies?.contextValues || policies?.softDelete ? {
2775
+ scope: policies.scope || policies.softDelete ? (context) => resolveScope(policies, context, filterCtx) : void 0,
2776
+ contextValues: policies.contextValues,
2777
+ softDelete: policies.softDelete
2778
+ } : void 0;
2779
+ var applyContextValues = (values, hooks, context) => {
2780
+ if (!hooks) {
2781
+ return values;
2782
+ }
2783
+ for (const [columnName, hook] of Object.entries(hooks)) {
2784
+ values[columnName] = hook(context);
2785
+ }
2786
+ return values;
2787
+ };
2788
+ var applyContextValuesAll = (rows, hooks, context) => {
2789
+ if (!hooks) {
2790
+ return rows;
2791
+ }
2792
+ for (const row of rows) {
2793
+ applyContextValues(row, hooks, context);
2794
+ }
2795
+ return rows;
2796
+ };
2797
+ var stripContextValues = (values, hooks) => {
2798
+ if (!hooks) {
2799
+ return values;
2800
+ }
2801
+ for (const columnName of Object.keys(hooks)) {
2802
+ delete values[columnName];
2803
+ }
2804
+ return values;
2805
+ };
2806
+ var extractRelationsParamsInner = (relationMap, tables, tableName, typeName, originField, typeNameMapper, _isInitial = false, filterCtx, limits, scope) => {
2659
2807
  const relationsForTable = relationMap[tableName];
2660
2808
  if (!relationsForTable) {
2661
2809
  return void 0;
@@ -2701,8 +2849,15 @@ var extractRelationsParamsInner = (relationMap, tables, tableName, typeName, ori
2701
2849
  const offset = relationArgs?.offset ?? void 0;
2702
2850
  const limit = (0, import_drizzle_orm4.is)(relEntry.relation, import_drizzle_orm4.One) ? relationArgs?.limit ?? void 0 : applyLimitPolicy(relationArgs?.limit, limits?.(targetTableName), `${tableName}.${relName}`);
2703
2851
  const relWhere = relationArgs?.where;
2704
- thisRecord.where = relWhere ? {
2705
- RAW: (aliasedTable2) => extractFilters(aliasedTable2, relName, relWhere, relationFilterCtx(filterCtx, targetTableName))
2852
+ const relDeleted = relationArgs?.deleted;
2853
+ thisRecord.where = relWhere || scope?.has(targetTableName, relDeleted) ? {
2854
+ RAW: (aliasedTable2) => withScope(
2855
+ scope,
2856
+ targetTableName,
2857
+ aliasedTable2,
2858
+ relWhere ? extractFilters(aliasedTable2, relName, relWhere, relationFilterCtx(filterCtx, targetTableName)) : void 0,
2859
+ relDeleted
2860
+ )
2706
2861
  } : void 0;
2707
2862
  const hasPagination = offset != null || limit != null;
2708
2863
  const pkNames = targetPkNames ?? [];
@@ -2718,14 +2873,15 @@ var extractRelationsParamsInner = (relationMap, tables, tableName, typeName, ori
2718
2873
  typeNameMapper,
2719
2874
  false,
2720
2875
  filterCtx,
2721
- limits
2876
+ limits,
2877
+ scope
2722
2878
  ) : void 0;
2723
2879
  thisRecord.with = relWith;
2724
2880
  args[relName] = thisRecord;
2725
2881
  }
2726
2882
  return args;
2727
2883
  };
2728
- var extractRelationsParams = (relationMap, tables, tableName, info, typeName, typeNameMapper, filterCtx, limits) => {
2884
+ var extractRelationsParams = (relationMap, tables, tableName, info, typeName, typeNameMapper, filterCtx, limits, scope) => {
2729
2885
  if (!info) {
2730
2886
  return void 0;
2731
2887
  }
@@ -2738,7 +2894,8 @@ var extractRelationsParams = (relationMap, tables, tableName, info, typeName, ty
2738
2894
  typeNameMapper,
2739
2895
  true,
2740
2896
  filterCtx,
2741
- limits
2897
+ limits,
2898
+ scope
2742
2899
  );
2743
2900
  };
2744
2901
  var pruneNonEagerRelations = (relationMap, shouldEagerLoad) => {
@@ -3148,7 +3305,8 @@ var prepareMutationRelationColumns = (params) => {
3148
3305
  typeName,
3149
3306
  typeNameMapper,
3150
3307
  void 0,
3151
- params.limits
3308
+ params.limits,
3309
+ params.scope
3152
3310
  ) : void 0;
3153
3311
  const hasRelations = !!(withParams && Object.keys(withParams).length);
3154
3312
  const baseColumns = extractSelectedColumnsFromTreeSQLFormat(parsedInfo.fieldsByTypeName[typeName], table, {
@@ -3224,9 +3382,11 @@ var computeResolverFieldNames = (tableName, typeNameMapper, prefixes, suffixes)
3224
3382
  const updateFieldName = `${prefixes.update}${mapped ? capitalize(mapped.singular) : capitalize(tableName)}`;
3225
3383
  const updateManyFieldName = `${prefixes.update}${mapped ? capitalize(mapped.plural) : capitalize(tableName)}Many`;
3226
3384
  const deleteFieldName = `${prefixes.delete}${mapped ? capitalize(mapped.singular) : capitalize(tableName)}`;
3385
+ const restoreFieldName = `${prefixes.restore ?? "restore"}${mapped ? capitalize(mapped.singular) : capitalize(tableName)}`;
3227
3386
  const writeSingleSuffix = suffixes.single === "" ? "Single" : suffixes.single;
3228
3387
  const updateSingleFieldName = `${updateFieldName}${writeSingleSuffix}`;
3229
3388
  const deleteSingleFieldName = `${deleteFieldName}${writeSingleSuffix}`;
3389
+ const restoreSingleFieldName = `${restoreFieldName}${writeSingleSuffix}`;
3230
3390
  const pluralNoun = mapped ? capitalize(mapped.plural) : capitalize(tableName);
3231
3391
  const updateCountFieldName = `${prefixes.update}${pluralNoun}Count`;
3232
3392
  const deleteCountFieldName = `${prefixes.delete}${pluralNoun}Count`;
@@ -3246,6 +3406,8 @@ var computeResolverFieldNames = (tableName, typeNameMapper, prefixes, suffixes)
3246
3406
  updateCountFieldName,
3247
3407
  deleteFieldName,
3248
3408
  deleteSingleFieldName,
3409
+ restoreFieldName,
3410
+ restoreSingleFieldName,
3249
3411
  deleteCountFieldName
3250
3412
  };
3251
3413
  };
@@ -3350,7 +3512,13 @@ var generateWriteCount = ({
3350
3512
  args: queryArgs
3351
3513
  };
3352
3514
  };
3353
- var selectArrayArgs = (orderArgs, filterArgs, distinctEnum) => ({
3515
+ var deletedArg = (softDelete, tableName) => softDelete?.(tableName) ? {
3516
+ deleted: {
3517
+ type: deletedFilterEnum,
3518
+ description: "Whether rows marked deleted are returned. Defaults to EXCLUDE."
3519
+ }
3520
+ } : {};
3521
+ var selectArrayArgs = (orderArgs, filterArgs, distinctEnum, softDelete, tableName) => ({
3354
3522
  offset: { type: import_graphql5.GraphQLInt },
3355
3523
  limit: { type: import_graphql5.GraphQLInt },
3356
3524
  orderBy: { type: orderArgs },
@@ -3359,12 +3527,14 @@ var selectArrayArgs = (orderArgs, filterArgs, distinctEnum) => ({
3359
3527
  type: import_graphql5.GraphQLString,
3360
3528
  description: "Keyset pagination: only return rows strictly after this cursor (a row's `cursor` field from a previous page, under the same orderBy)."
3361
3529
  },
3362
- ...distinctEnum ? { distinct: { type: new import_graphql5.GraphQLList(new import_graphql5.GraphQLNonNull(distinctEnum)) } } : {}
3530
+ ...distinctEnum ? { distinct: { type: new import_graphql5.GraphQLList(new import_graphql5.GraphQLNonNull(distinctEnum)) } } : {},
3531
+ ...deletedArg(softDelete, tableName)
3363
3532
  });
3364
- var selectSingleArgs = (orderArgs, filterArgs) => ({
3533
+ var selectSingleArgs = (orderArgs, filterArgs, softDelete, tableName) => ({
3365
3534
  offset: { type: import_graphql5.GraphQLInt },
3366
3535
  orderBy: { type: orderArgs },
3367
- where: { type: filterArgs }
3536
+ where: { type: filterArgs },
3537
+ ...deletedArg(softDelete, tableName)
3368
3538
  });
3369
3539
  var runRelationalSelect = async (opts) => {
3370
3540
  const {
@@ -3382,7 +3552,9 @@ var runRelationalSelect = async (opts) => {
3382
3552
  single,
3383
3553
  filterCtx,
3384
3554
  pkNames,
3385
- after
3555
+ after,
3556
+ scope,
3557
+ deleted
3386
3558
  } = opts;
3387
3559
  const distinct = opts.distinct?.length ? opts.distinct : void 0;
3388
3560
  const cursorSelected = !single && isCursorFieldSelected(parsedInfo.fieldsByTypeName[typeName], table);
@@ -3414,7 +3586,13 @@ var runRelationalSelect = async (opts) => {
3414
3586
  tableName,
3415
3587
  distinct,
3416
3588
  pkNames: pkNames ?? [],
3417
- where: where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0,
3589
+ where: withScope(
3590
+ scope,
3591
+ tableName,
3592
+ table,
3593
+ where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0,
3594
+ deleted
3595
+ ),
3418
3596
  orderBy,
3419
3597
  limit: single ? 1 : opts.limit,
3420
3598
  offset
@@ -3441,15 +3619,24 @@ var runRelationalSelect = async (opts) => {
3441
3619
  // exactly the ordering the cursor encodes and the keyset predicate compares against.
3442
3620
  (aliasedTable2) => cursorOrderExprs(aliasedTable2, cursorEntries)
3443
3621
  ) : orderBy ? (aliasedTable2) => extractOrderBy(aliasedTable2, orderBy, relationFilterCtx(filterCtx, tableName), where) : needsDefaultOrder && pkNames?.length ? (aliasedTable2) => primaryKeyOrderExprs(aliasedTable2, pkNames) : void 0,
3444
- where: distinctKeys ? { RAW: (aliasedTable2) => primaryKeyRestriction(aliasedTable2, pkNames, distinctKeys) } : where || cursorValues ? {
3445
- RAW: (aliasedTable2) => (0, import_drizzle_orm4.and)(
3446
- where ? extractFilters(aliasedTable2, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0,
3447
- cursorValues ? buildCursorCondition(
3448
- aliasedTable2,
3449
- cursorEntries,
3450
- cursorValues,
3451
- opts.nullOrdering ?? "nulls-smallest"
3452
- ) : void 0
3622
+ where: distinctKeys ? (
3623
+ // The distinct pass already ran inside the scope, so the keys it picked are in it.
3624
+ { RAW: (aliasedTable2) => primaryKeyRestriction(aliasedTable2, pkNames, distinctKeys) }
3625
+ ) : where || cursorValues || scope?.has(tableName, deleted) ? {
3626
+ RAW: (aliasedTable2) => withScope(
3627
+ scope,
3628
+ tableName,
3629
+ aliasedTable2,
3630
+ (0, import_drizzle_orm4.and)(
3631
+ where ? extractFilters(aliasedTable2, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0,
3632
+ cursorValues ? buildCursorCondition(
3633
+ aliasedTable2,
3634
+ cursorEntries,
3635
+ cursorValues,
3636
+ opts.nullOrdering ?? "nulls-smallest"
3637
+ ) : void 0
3638
+ ),
3639
+ deleted
3453
3640
  )
3454
3641
  } : void 0,
3455
3642
  with: relationMap[tableName] ? extractRelationsParams(
@@ -3460,7 +3647,8 @@ var runRelationalSelect = async (opts) => {
3460
3647
  typeName,
3461
3648
  typeNameMapper,
3462
3649
  filterCtx,
3463
- opts.limits
3650
+ opts.limits,
3651
+ scope
3464
3652
  ) : void 0
3465
3653
  };
3466
3654
  if (single) {
@@ -3765,10 +3953,11 @@ var assembleAggregateRow = (row, request, target) => {
3765
3953
  }
3766
3954
  return result;
3767
3955
  };
3768
- var generateAggregate = (db, tableName, table, typeName, fieldName, filterArgs, filterCtx) => {
3956
+ var generateAggregate = (db, tableName, table, typeName, fieldName, filterArgs, filterCtx, policies) => {
3769
3957
  const target = aggregateTarget(table, tableName, typeName);
3770
3958
  const queryArgs = {
3771
- where: { type: filterArgs }
3959
+ where: { type: filterArgs },
3960
+ ...deletedArg(policies?.softDelete, tableName)
3772
3961
  };
3773
3962
  return {
3774
3963
  name: fieldName,
@@ -3779,8 +3968,15 @@ var generateAggregate = (db, tableName, table, typeName, fieldName, filterArgs,
3779
3968
  return {};
3780
3969
  }
3781
3970
  let query = resolveExecutor(db, context).select(request.selection).from(table);
3782
- if (args.where) {
3783
- query = query.where(extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName)));
3971
+ const where = withScope(
3972
+ resolveScope(policies, context, filterCtx),
3973
+ tableName,
3974
+ table,
3975
+ args.where ? extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName)) : void 0,
3976
+ args.deleted
3977
+ );
3978
+ if (where) {
3979
+ query = query.where(where);
3784
3980
  }
3785
3981
  const rows = await query;
3786
3982
  return assembleAggregateRow(rows[0] ?? {}, request, target);
@@ -3792,7 +3988,7 @@ var generateAggregate = (db, tableName, table, typeName, fieldName, filterArgs,
3792
3988
  };
3793
3989
  };
3794
3990
  var GROUP_KEY = "__dgql_group_key";
3795
- var createRelationAggregateFactory = (db, tables, cacheCtx, typeNameMapper, filterCtx) => {
3991
+ var createRelationAggregateFactory = (db, tables, cacheCtx, typeNameMapper, filterCtx, policies) => {
3796
3992
  return ({ tableName, relationName, relEntry }) => {
3797
3993
  const parentTable = tables[tableName];
3798
3994
  const targetTableName = relEntry.targetTableName;
@@ -3819,17 +4015,25 @@ var createRelationAggregateFactory = (db, tables, cacheCtx, typeNameMapper, filt
3819
4015
  return assembleAggregateRow({}, request, target);
3820
4016
  }
3821
4017
  const whereArg = args?.where;
4018
+ const deleted = args?.deleted;
3822
4019
  const argsKey = JSON.stringify({
3823
4020
  where: whereArg ?? null,
4021
+ deleted: deleted ?? null,
3824
4022
  selection: Object.keys(request.selection).sort()
3825
4023
  });
3826
4024
  const loaderKey = `${tableName}::${relationName}::aggregate::${argsKey}`;
3827
4025
  const loader = getOrCreateLoader(context, loaderKey, async (parentIds) => {
3828
4026
  const executor = resolveExecutor(db, context);
3829
4027
  const uniqueIds = [...new Set(parentIds)];
3830
- const whereCondition = (0, import_drizzle_orm5.and)(
3831
- (0, import_drizzle_orm5.inArray)(foreignCol, uniqueIds),
3832
- whereArg ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName)) : void 0
4028
+ const whereCondition = withScope(
4029
+ resolveScope(policies, context, filterCtx),
4030
+ targetTableName,
4031
+ targetTable,
4032
+ (0, import_drizzle_orm5.and)(
4033
+ (0, import_drizzle_orm5.inArray)(foreignCol, uniqueIds),
4034
+ whereArg ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName)) : void 0
4035
+ ),
4036
+ deleted
3833
4037
  );
3834
4038
  const rows = await executor.select({ [GROUP_KEY]: foreignCol, ...request.selection }).from(targetTable).where(whereCondition).groupBy(foreignCol);
3835
4039
  const byKey = new Map(rows.map((row) => [row[GROUP_KEY], row]));
@@ -3962,7 +4166,7 @@ var buildHavingCondition = (having, columns) => {
3962
4166
  }
3963
4167
  return conditions.length ? (0, import_drizzle_orm5.and)(...conditions) : void 0;
3964
4168
  };
3965
- var generateGroupBy = (db, tableName, table, typeName, fieldName, filterArgs, groupByEnum, havingInput, filterCtx) => {
4169
+ var generateGroupBy = (db, tableName, table, typeName, fieldName, filterArgs, groupByEnum, havingInput, filterCtx, policies) => {
3966
4170
  const target = aggregateTarget(table, tableName, typeName);
3967
4171
  const groupable = groupableColumns(table, tableName);
3968
4172
  const columns = (0, import_drizzle_orm5.getColumns)(table);
@@ -3973,7 +4177,8 @@ var generateGroupBy = (db, tableName, table, typeName, fieldName, filterArgs, gr
3973
4177
  description: "Columns to group by. One result row per distinct combination of their values."
3974
4178
  },
3975
4179
  where: { type: filterArgs, description: "Filters the rows before they are grouped." },
3976
- having: { type: havingInput, description: "Filters the groups after they are aggregated." }
4180
+ having: { type: havingInput, description: "Filters the groups after they are aggregated." },
4181
+ ...deletedArg(policies?.softDelete, tableName)
3977
4182
  };
3978
4183
  return {
3979
4184
  name: fieldName,
@@ -3996,8 +4201,15 @@ var generateGroupBy = (db, tableName, table, typeName, fieldName, filterArgs, gr
3996
4201
  ...request.selection
3997
4202
  };
3998
4203
  let query = resolveExecutor(db, context).select(selection).from(table);
3999
- if (args.where) {
4000
- query = query.where(extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName)));
4204
+ const where = withScope(
4205
+ resolveScope(policies, context, filterCtx),
4206
+ tableName,
4207
+ table,
4208
+ args.where ? extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName)) : void 0,
4209
+ args.deleted
4210
+ );
4211
+ if (where) {
4212
+ query = query.where(where);
4001
4213
  }
4002
4214
  query = query.groupBy(...keyColumns.map(([, column]) => column));
4003
4215
  const havingCondition = buildHavingCondition(args.having, columns);
@@ -4023,7 +4235,7 @@ var generateGroupBy = (db, tableName, table, typeName, fieldName, filterArgs, gr
4023
4235
  };
4024
4236
 
4025
4237
  // src/util/builders/mysql.ts
4026
- var generateSelectArray = (db, tableName, tables, relationMap, orderArgs, filterArgs, fieldName, typeName, typeNameMapper, filterCtx, distinctEnabled = true, limits) => {
4238
+ var generateSelectArray = (db, tableName, tables, relationMap, orderArgs, filterArgs, fieldName, typeName, typeNameMapper, filterCtx, distinctEnabled = true, limits, policies) => {
4027
4239
  const queryBase = db.query[tableName];
4028
4240
  if (!queryBase) {
4029
4241
  throw new Error(
@@ -4036,7 +4248,9 @@ var generateSelectArray = (db, tableName, tables, relationMap, orderArgs, filter
4036
4248
  const queryArgs = selectArrayArgs(
4037
4249
  orderArgs,
4038
4250
  filterArgs,
4039
- distinctEnabled ? generateDistinctEnum(table, typeName) : void 0
4251
+ distinctEnabled ? generateDistinctEnum(table, typeName) : void 0,
4252
+ policies?.softDelete,
4253
+ tableName
4040
4254
  );
4041
4255
  return {
4042
4256
  name: fieldName,
@@ -4058,6 +4272,7 @@ var generateSelectArray = (db, tableName, tables, relationMap, orderArgs, filter
4058
4272
  single: false,
4059
4273
  filterCtx,
4060
4274
  limits,
4275
+ scope: policies?.scope?.(context),
4061
4276
  pkNames,
4062
4277
  db: executor,
4063
4278
  // MySQL sorts NULLs as the smallest values (first in ASC).
@@ -4070,14 +4285,14 @@ var generateSelectArray = (db, tableName, tables, relationMap, orderArgs, filter
4070
4285
  args: queryArgs
4071
4286
  };
4072
4287
  };
4073
- var generateSelectSingle = (db, tableName, tables, relationMap, orderArgs, filterArgs, fieldName, typeName, typeNameMapper, filterCtx, limits) => {
4288
+ var generateSelectSingle = (db, tableName, tables, relationMap, orderArgs, filterArgs, fieldName, typeName, typeNameMapper, filterCtx, limits, policies) => {
4074
4289
  const queryBase = db.query[tableName];
4075
4290
  if (!queryBase) {
4076
4291
  throw new Error(
4077
4292
  `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`
4078
4293
  );
4079
4294
  }
4080
- const queryArgs = selectSingleArgs(orderArgs, filterArgs);
4295
+ const queryArgs = selectSingleArgs(orderArgs, filterArgs, policies?.softDelete, tableName);
4081
4296
  const table = tables[tableName];
4082
4297
  const pkNames = mysqlPrimaryKeyPropNames(table);
4083
4298
  return {
@@ -4099,6 +4314,7 @@ var generateSelectSingle = (db, tableName, tables, relationMap, orderArgs, filte
4099
4314
  single: true,
4100
4315
  filterCtx,
4101
4316
  limits,
4317
+ scope: policies?.scope?.(context),
4102
4318
  pkNames,
4103
4319
  db: executor
4104
4320
  });
@@ -4109,7 +4325,7 @@ var generateSelectSingle = (db, tableName, tables, relationMap, orderArgs, filte
4109
4325
  args: queryArgs
4110
4326
  };
4111
4327
  };
4112
- var generateInsertArray = (db, _tableName, table, baseType, fieldName, txCtx) => {
4328
+ var generateInsertArray = (db, tableName, table, baseType, fieldName, txCtx, policies) => {
4113
4329
  const queryArgs = {
4114
4330
  values: {
4115
4331
  type: new import_graphql7.GraphQLNonNull(new import_graphql7.GraphQLList(new import_graphql7.GraphQLNonNull(baseType)))
@@ -4120,7 +4336,11 @@ var generateInsertArray = (db, _tableName, table, baseType, fieldName, txCtx) =>
4120
4336
  resolver: async (_source, args, context, info) => {
4121
4337
  try {
4122
4338
  return await runMutation(db, context, info, txCtx, async (executor) => {
4123
- const input = remapFromGraphQLArrayInput(args.values, table);
4339
+ const input = applyContextValuesAll(
4340
+ remapFromGraphQLArrayInput(args.values, table),
4341
+ policies?.contextValues?.(tableName),
4342
+ context
4343
+ );
4124
4344
  if (!input.length) {
4125
4345
  throw new import_graphql7.GraphQLError("No values were provided!");
4126
4346
  }
@@ -4134,7 +4354,7 @@ var generateInsertArray = (db, _tableName, table, baseType, fieldName, txCtx) =>
4134
4354
  args: queryArgs
4135
4355
  };
4136
4356
  };
4137
- var generateInsertSingle = (db, _tableName, table, baseType, fieldName, txCtx) => {
4357
+ var generateInsertSingle = (db, tableName, table, baseType, fieldName, txCtx, policies) => {
4138
4358
  const queryArgs = {
4139
4359
  values: {
4140
4360
  type: new import_graphql7.GraphQLNonNull(baseType)
@@ -4145,7 +4365,11 @@ var generateInsertSingle = (db, _tableName, table, baseType, fieldName, txCtx) =
4145
4365
  resolver: async (_source, args, context, info) => {
4146
4366
  try {
4147
4367
  return await runMutation(db, context, info, txCtx, async (executor) => {
4148
- const input = remapFromGraphQLSingleInput(args.values, table);
4368
+ const input = applyContextValues(
4369
+ remapFromGraphQLSingleInput(args.values, table),
4370
+ policies?.contextValues?.(tableName),
4371
+ context
4372
+ );
4149
4373
  await executor.insert(table).values(input);
4150
4374
  return { isSuccess: true };
4151
4375
  });
@@ -4156,7 +4380,7 @@ var generateInsertSingle = (db, _tableName, table, baseType, fieldName, txCtx) =
4156
4380
  args: queryArgs
4157
4381
  };
4158
4382
  };
4159
- var generateUpsert = (db, table, baseType, onConflictType, fieldName, single, txCtx) => {
4383
+ var generateUpsert = (db, tableName, table, baseType, onConflictType, fieldName, single, txCtx, policies) => {
4160
4384
  const queryArgs = {
4161
4385
  values: {
4162
4386
  type: single ? new import_graphql7.GraphQLNonNull(baseType) : new import_graphql7.GraphQLNonNull(new import_graphql7.GraphQLList(new import_graphql7.GraphQLNonNull(baseType)))
@@ -4172,7 +4396,11 @@ var generateUpsert = (db, table, baseType, onConflictType, fieldName, single, tx
4172
4396
  resolver: async (_source, args, context, info) => {
4173
4397
  try {
4174
4398
  return await runMutation(db, context, info, txCtx, async (executor) => {
4175
- const input = single ? [remapFromGraphQLSingleInput(args.values, table)] : remapFromGraphQLArrayInput(args.values, table);
4399
+ const input = applyContextValuesAll(
4400
+ single ? [remapFromGraphQLSingleInput(args.values, table)] : remapFromGraphQLArrayInput(args.values, table),
4401
+ policies?.contextValues?.(tableName),
4402
+ context
4403
+ );
4176
4404
  if (!input.length) {
4177
4405
  throw new import_graphql7.GraphQLError("No values were provided!");
4178
4406
  }
@@ -4199,7 +4427,7 @@ var generateUpsert = (db, table, baseType, onConflictType, fieldName, single, tx
4199
4427
  args: queryArgs
4200
4428
  };
4201
4429
  };
4202
- var generateUpdate = (db, tableName, table, setArgs, filterArgs, fieldName, single, requireWhere, filterCtx, txCtx) => {
4430
+ var generateUpdate = (db, tableName, table, setArgs, filterArgs, fieldName, single, requireWhere, filterCtx, txCtx, policies) => {
4203
4431
  const queryArgs = {
4204
4432
  set: {
4205
4433
  type: new import_graphql7.GraphQLNonNull(setArgs)
@@ -4214,12 +4442,21 @@ var generateUpdate = (db, tableName, table, setArgs, filterArgs, fieldName, sing
4214
4442
  try {
4215
4443
  return await runMutation(db, context, info, txCtx, async (executor) => {
4216
4444
  const { where, set } = args;
4217
- const input = remapUpdateInput(set, table, tableName);
4445
+ const scope = policies?.scope?.(context);
4446
+ const input = stripContextValues(
4447
+ remapUpdateInput(set, table, tableName),
4448
+ policies?.contextValues?.(tableName)
4449
+ );
4218
4450
  if (!Object.keys(input).length) {
4219
4451
  throw new import_graphql7.GraphQLError("Unable to update with no values specified!");
4220
4452
  }
4221
4453
  const relationCtx = relationFilterCtx(filterCtx, tableName);
4222
- const filters = single || requireWhere ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx) : where ? extractFilters(table, tableName, where, relationCtx) : void 0;
4454
+ const filters = withScope(
4455
+ scope,
4456
+ tableName,
4457
+ table,
4458
+ single || requireWhere ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx) : where ? extractFilters(table, tableName, where, relationCtx) : void 0
4459
+ );
4223
4460
  if (single) {
4224
4461
  await assertSingleMatch(executor, table, filters, fieldName);
4225
4462
  }
@@ -4237,7 +4474,7 @@ var generateUpdate = (db, tableName, table, setArgs, filterArgs, fieldName, sing
4237
4474
  args: queryArgs
4238
4475
  };
4239
4476
  };
4240
- var generateUpdateMany = (db, tableName, table, updateManyInput, fieldName, filterCtx, txCtx) => {
4477
+ var generateUpdateMany = (db, tableName, table, updateManyInput, fieldName, filterCtx, txCtx, policies) => {
4241
4478
  const queryArgs = {
4242
4479
  updates: {
4243
4480
  type: new import_graphql7.GraphQLNonNull(new import_graphql7.GraphQLList(new import_graphql7.GraphQLNonNull(updateManyInput)))
@@ -4252,14 +4489,21 @@ var generateUpdateMany = (db, tableName, table, updateManyInput, fieldName, filt
4252
4489
  if (!updates.length) {
4253
4490
  throw new import_graphql7.GraphQLError("No updates were provided!");
4254
4491
  }
4492
+ const scope = policies?.scope?.(context);
4493
+ const contextColumns = policies?.contextValues?.(tableName);
4255
4494
  const entries = updates.map(({ where, set }) => {
4256
- const input = remapUpdateInput(set, table, tableName);
4495
+ const input = stripContextValues(remapUpdateInput(set, table, tableName), contextColumns);
4257
4496
  if (!Object.keys(input).length) {
4258
4497
  throw new import_graphql7.GraphQLError("Unable to update with no values specified!");
4259
4498
  }
4260
4499
  return {
4261
4500
  set: input,
4262
- filters: where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0
4501
+ filters: withScope(
4502
+ scope,
4503
+ tableName,
4504
+ table,
4505
+ where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0
4506
+ )
4263
4507
  };
4264
4508
  });
4265
4509
  await executor.transaction(async (tx) => {
@@ -4280,7 +4524,8 @@ var generateUpdateMany = (db, tableName, table, updateManyInput, fieldName, filt
4280
4524
  args: queryArgs
4281
4525
  };
4282
4526
  };
4283
- var generateDelete = (db, tableName, table, filterArgs, fieldName, single, requireWhere, filterCtx, txCtx) => {
4527
+ var generateDelete = (db, tableName, table, filterArgs, fieldName, single, requireWhere, filterCtx, txCtx, policies, restore = false) => {
4528
+ const softDelete = policies?.softDelete?.(tableName);
4284
4529
  const queryArgs = {
4285
4530
  where: {
4286
4531
  type: single || requireWhere ? new import_graphql7.GraphQLNonNull(filterArgs) : filterArgs
@@ -4292,12 +4537,19 @@ var generateDelete = (db, tableName, table, filterArgs, fieldName, single, requi
4292
4537
  try {
4293
4538
  return await runMutation(db, context, info, txCtx, async (executor) => {
4294
4539
  const { where } = args;
4540
+ const scope = policies?.scope?.(context);
4295
4541
  const relationCtx = relationFilterCtx(filterCtx, tableName);
4296
- const filters = single || requireWhere ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx) : where ? extractFilters(table, tableName, where, relationCtx) : void 0;
4542
+ const filters = withScope(
4543
+ scope,
4544
+ tableName,
4545
+ table,
4546
+ single || requireWhere ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx) : where ? extractFilters(table, tableName, where, relationCtx) : void 0,
4547
+ restore ? "ONLY" : void 0
4548
+ );
4297
4549
  if (single) {
4298
4550
  await assertSingleMatch(executor, table, filters, fieldName);
4299
4551
  }
4300
- let query = executor.delete(table);
4552
+ let query = softDelete ? executor.update(table).set({ [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted() }) : executor.delete(table);
4301
4553
  if (filters) {
4302
4554
  query = query.where(filters);
4303
4555
  }
@@ -4341,12 +4593,17 @@ var generateSchemaData = (db, schema, relations, options) => {
4341
4593
  attachTargetPrimaryKeys(namedRelations, tables, mysqlPrimaryKeyPropNames);
4342
4594
  const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);
4343
4595
  const filterCtx = { tables, relationMap: namedRelations };
4596
+ const tablePolicies = options.policies;
4597
+ const contextValuesOf = tablePolicies?.contextValues;
4598
+ const softDeleteOf = tablePolicies?.softDelete;
4599
+ const policies = bindPolicies(tablePolicies, filterCtx);
4344
4600
  const resolverFactory = createRelationResolverFactory(
4345
4601
  db,
4346
4602
  tables,
4347
4603
  "nulls-smallest",
4348
4604
  filterCtx,
4349
- limits
4605
+ limits,
4606
+ tablePolicies
4350
4607
  );
4351
4608
  const cacheCtx = {
4352
4609
  genericFilterCache: /* @__PURE__ */ new Map(),
@@ -4364,9 +4621,11 @@ var generateSchemaData = (db, schema, relations, options) => {
4364
4621
  limits,
4365
4622
  docs: options.docs ?? {},
4366
4623
  primaryKeyOf: (name) => tables[name] ? mysqlPrimaryKeyPropNames(tables[name]) : [],
4624
+ contextValuesOf,
4625
+ softDeleteOf,
4367
4626
  featureOf
4368
4627
  };
4369
- const relationAggregateFactory = anyTable("relationAggregates") ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx) : void 0;
4628
+ const relationAggregateFactory = anyTable("relationAggregates") ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx, tablePolicies) : void 0;
4370
4629
  const queries = {};
4371
4630
  const mutations = {};
4372
4631
  const mutationTxCtx = createMutationTxCtx(options.transactions);
@@ -4422,8 +4681,11 @@ var generateSchemaData = (db, schema, relations, options) => {
4422
4681
  updateCountFieldName,
4423
4682
  deleteFieldName,
4424
4683
  deleteSingleFieldName,
4684
+ restoreFieldName,
4685
+ restoreSingleFieldName,
4425
4686
  deleteCountFieldName
4426
4687
  } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);
4688
+ const softDeleteInfo = softDeleteOf?.(tableName);
4427
4689
  const selectArrGenerated = generateSelectArray(
4428
4690
  db,
4429
4691
  tableName,
@@ -4436,7 +4698,8 @@ var generateSchemaData = (db, schema, relations, options) => {
4436
4698
  typeNameMapper,
4437
4699
  filterCtx,
4438
4700
  tableFeatures.distinct,
4439
- limits
4701
+ limits,
4702
+ policies
4440
4703
  );
4441
4704
  const selectSingleGenerated = generateSelectSingle(
4442
4705
  db,
@@ -4449,7 +4712,8 @@ var generateSchemaData = (db, schema, relations, options) => {
4449
4712
  typeName,
4450
4713
  typeNameMapper,
4451
4714
  filterCtx,
4452
- limits
4715
+ limits,
4716
+ policies
4453
4717
  );
4454
4718
  const insertArrGenerated = tableFeatures.insert ? generateInsertArray(
4455
4719
  db,
@@ -4457,7 +4721,8 @@ var generateSchemaData = (db, schema, relations, options) => {
4457
4721
  schema[tableName],
4458
4722
  insertInput,
4459
4723
  createArrayFieldName,
4460
- mutationTxCtx
4724
+ mutationTxCtx,
4725
+ policies
4461
4726
  ) : void 0;
4462
4727
  const insertSingleGenerated = tableFeatures.insert ? generateInsertSingle(
4463
4728
  db,
@@ -4465,7 +4730,8 @@ var generateSchemaData = (db, schema, relations, options) => {
4465
4730
  schema[tableName],
4466
4731
  insertInput,
4467
4732
  createSingleFieldName,
4468
- mutationTxCtx
4733
+ mutationTxCtx,
4734
+ policies
4469
4735
  ) : void 0;
4470
4736
  const onConflictInput = tableFeatures.upsert ? generateOnConflictInput({
4471
4737
  table: schema[tableName],
@@ -4476,21 +4742,25 @@ var generateSchemaData = (db, schema, relations, options) => {
4476
4742
  }) : void 0;
4477
4743
  const upsertArrGenerated = onConflictInput ? generateUpsert(
4478
4744
  db,
4745
+ tableName,
4479
4746
  schema[tableName],
4480
4747
  insertInput,
4481
4748
  onConflictInput,
4482
4749
  upsertArrayFieldName,
4483
4750
  false,
4484
- mutationTxCtx
4751
+ mutationTxCtx,
4752
+ policies
4485
4753
  ) : void 0;
4486
4754
  const upsertSingleGenerated = onConflictInput ? generateUpsert(
4487
4755
  db,
4756
+ tableName,
4488
4757
  schema[tableName],
4489
4758
  insertInput,
4490
4759
  onConflictInput,
4491
4760
  upsertSingleFieldName,
4492
4761
  true,
4493
- mutationTxCtx
4762
+ mutationTxCtx,
4763
+ policies
4494
4764
  ) : void 0;
4495
4765
  const updateGenerated = tableFeatures.update ? generateUpdate(
4496
4766
  db,
@@ -4502,7 +4772,8 @@ var generateSchemaData = (db, schema, relations, options) => {
4502
4772
  false,
4503
4773
  tableFeatures.requireWhere,
4504
4774
  filterCtx,
4505
- mutationTxCtx
4775
+ mutationTxCtx,
4776
+ policies
4506
4777
  ) : void 0;
4507
4778
  const updateSingleGenerated = tableFeatures.update ? generateUpdate(
4508
4779
  db,
@@ -4514,7 +4785,8 @@ var generateSchemaData = (db, schema, relations, options) => {
4514
4785
  true,
4515
4786
  tableFeatures.requireWhere,
4516
4787
  filterCtx,
4517
- mutationTxCtx
4788
+ mutationTxCtx,
4789
+ policies
4518
4790
  ) : void 0;
4519
4791
  const updateManyInput = tableFeatures.update && tableFeatures.updateMany ? generateUpdateManyInput({ typeName, updatePrefix: prefixes.update, updateInput, tableFilters }) : void 0;
4520
4792
  const updateManyGenerated = updateManyInput ? generateUpdateMany(
@@ -4524,7 +4796,8 @@ var generateSchemaData = (db, schema, relations, options) => {
4524
4796
  updateManyInput,
4525
4797
  updateManyFieldName,
4526
4798
  filterCtx,
4527
- mutationTxCtx
4799
+ mutationTxCtx,
4800
+ policies
4528
4801
  ) : void 0;
4529
4802
  const deleteGenerated = tableFeatures.delete ? generateDelete(
4530
4803
  db,
@@ -4535,7 +4808,8 @@ var generateSchemaData = (db, schema, relations, options) => {
4535
4808
  false,
4536
4809
  tableFeatures.requireWhere,
4537
4810
  filterCtx,
4538
- mutationTxCtx
4811
+ mutationTxCtx,
4812
+ policies
4539
4813
  ) : void 0;
4540
4814
  const deleteSingleGenerated = tableFeatures.delete ? generateDelete(
4541
4815
  db,
@@ -4546,7 +4820,34 @@ var generateSchemaData = (db, schema, relations, options) => {
4546
4820
  true,
4547
4821
  tableFeatures.requireWhere,
4548
4822
  filterCtx,
4549
- mutationTxCtx
4823
+ mutationTxCtx,
4824
+ policies
4825
+ ) : void 0;
4826
+ const restoreGenerated = softDeleteInfo ? generateDelete(
4827
+ db,
4828
+ tableName,
4829
+ schema[tableName],
4830
+ tableFilters,
4831
+ restoreFieldName,
4832
+ false,
4833
+ tableFeatures.requireWhere,
4834
+ filterCtx,
4835
+ mutationTxCtx,
4836
+ policies,
4837
+ true
4838
+ ) : void 0;
4839
+ const restoreSingleGenerated = softDeleteInfo ? generateDelete(
4840
+ db,
4841
+ tableName,
4842
+ schema[tableName],
4843
+ tableFilters,
4844
+ restoreSingleFieldName,
4845
+ true,
4846
+ tableFeatures.requireWhere,
4847
+ filterCtx,
4848
+ mutationTxCtx,
4849
+ policies,
4850
+ true
4550
4851
  ) : void 0;
4551
4852
  const updateCountGenerated = tableFeatures.update && tableFeatures.countMutations ? generateWriteCount({
4552
4853
  db,
@@ -4579,7 +4880,8 @@ var generateSchemaData = (db, schema, relations, options) => {
4579
4880
  typeName,
4580
4881
  aggregateFieldName,
4581
4882
  tableFilters,
4582
- filterCtx
4883
+ filterCtx,
4884
+ tablePolicies
4583
4885
  ) : void 0;
4584
4886
  const groupByType = tableFeatures.aggregates && tableFeatures.groupBy ? generateGroupByType(schema[tableName], tableName, typeName, cacheCtx) : void 0;
4585
4887
  const groupByEnum = groupByType ? generateGroupByEnum(schema[tableName], tableName, typeName) : void 0;
@@ -4593,7 +4895,8 @@ var generateSchemaData = (db, schema, relations, options) => {
4593
4895
  tableFilters,
4594
4896
  groupByEnum,
4595
4897
  havingInput,
4596
- filterCtx
4898
+ filterCtx,
4899
+ tablePolicies
4597
4900
  ) : void 0;
4598
4901
  queries[selectArrGenerated.name] = {
4599
4902
  type: selectArrOutput,
@@ -4643,7 +4946,9 @@ var generateSchemaData = (db, schema, relations, options) => {
4643
4946
  [updateManyGenerated, { operation: "updateMany", single: false, targetArg: "updates" }],
4644
4947
  [updateSingleGenerated, { operation: "update", single: true, targetArg: "where" }],
4645
4948
  [deleteGenerated, { operation: "delete", single: false, targetArg: "where" }],
4646
- [deleteSingleGenerated, { operation: "delete", single: true, targetArg: "where" }]
4949
+ [deleteSingleGenerated, { operation: "delete", single: true, targetArg: "where" }],
4950
+ [restoreGenerated, { operation: "restore", single: false, targetArg: "where" }],
4951
+ [restoreSingleGenerated, { operation: "restore", single: true, targetArg: "where" }]
4647
4952
  ];
4648
4953
  for (const [generated, meta] of generatedMutations) {
4649
4954
  if (generated) {
@@ -4821,8 +5126,9 @@ var createNestedWriteTypes = (params) => {
4821
5126
  return cached;
4822
5127
  }
4823
5128
  const omitted = plan.fkSide === "child" ? plan.foreignColPropName : void 0;
5129
+ const contextColumns = cacheCtx.contextValuesOf?.(plan.targetTableName);
4824
5130
  const fields = Object.fromEntries(
4825
- Object.entries(visibleColumns(plan.targetTable)).filter(([columnName]) => columnName !== omitted).map(([columnName, column]) => [
5131
+ Object.entries(visibleColumns(plan.targetTable)).filter(([columnName]) => columnName !== omitted && !contextColumns?.[columnName]).map(([columnName, column]) => [
4826
5132
  columnName,
4827
5133
  drizzleColumnToGraphQLType(column, columnName, plan.targetTableName, false, true, true)
4828
5134
  ])
@@ -4921,8 +5227,8 @@ var createNestedWriteTypes = (params) => {
4921
5227
  var mergedOps = (entries) => Object.assign({}, ...entries.map((entry) => entry.ops));
4922
5228
  var asArray = (value) => Array.isArray(value) ? value : value === void 0 ? [] : [value];
4923
5229
  var createNestedWriteRuntime = (params) => {
4924
- const { plans, filterCtx } = params;
4925
- const conditionOf = (plan, filter, operation) => {
5230
+ const { plans, filterCtx, policies, contextValues } = params;
5231
+ const conditionOf = (plan, filter, operation, scope) => {
4926
5232
  const condition = extractFilters(
4927
5233
  plan.targetTable,
4928
5234
  plan.targetTableName,
@@ -4934,7 +5240,7 @@ var createNestedWriteRuntime = (params) => {
4934
5240
  `Drizzle-GraphQL Error: '${operation}' on '${plan.relationName}' needs a filter that selects rows \u2014 it was given one that matches everything.`
4935
5241
  );
4936
5242
  }
4937
- return condition;
5243
+ return withScope(scope, plan.targetTableName, plan.targetTable, condition);
4938
5244
  };
4939
5245
  const assertSingleOperation = (plan, op) => {
4940
5246
  const supplied = ["create", "connect", "disconnect"].filter((key) => op[key] !== void 0 && op[key] !== null);
@@ -4944,7 +5250,7 @@ var createNestedWriteRuntime = (params) => {
4944
5250
  );
4945
5251
  }
4946
5252
  };
4947
- const detachAll = async (executor, plan, key) => executor.update(plan.targetTable).set({ [plan.foreignColPropName]: null }).where((0, import_drizzle_orm7.eq)(plan.foreignCol, key));
5253
+ const detachAll = async (executor, plan, key, scope) => executor.update(plan.targetTable).set({ [plan.foreignColPropName]: null }).where(withScope(scope, plan.targetTableName, plan.targetTable, (0, import_drizzle_orm7.eq)(plan.foreignCol, key)));
4948
5254
  return {
4949
5255
  enabled: (tableName) => !!plans[tableName],
4950
5256
  split: (tableName, values) => {
@@ -4978,12 +5284,13 @@ var createNestedWriteRuntime = (params) => {
4978
5284
  }
4979
5285
  return columns;
4980
5286
  },
4981
- applyParentSide: async (executor, tableName, ops) => {
5287
+ applyParentSide: async (executor, tableName, ops, context) => {
4982
5288
  const tablePlans = plans[tableName];
4983
5289
  const patch = {};
4984
5290
  if (!tablePlans) {
4985
5291
  return patch;
4986
5292
  }
5293
+ const scope = resolveScope(policies, context, filterCtx);
4987
5294
  for (const [relationName, op] of Object.entries(ops)) {
4988
5295
  const plan = tablePlans[relationName];
4989
5296
  if (!plan || plan.fkSide !== "parent") {
@@ -4991,7 +5298,11 @@ var createNestedWriteRuntime = (params) => {
4991
5298
  }
4992
5299
  assertSingleOperation(plan, op);
4993
5300
  if (op["create"] !== void 0) {
4994
- const values = remapFromGraphQLSingleInput({ ...op["create"] }, plan.targetTable);
5301
+ const values = applyContextValues(
5302
+ remapFromGraphQLSingleInput({ ...op["create"] }, plan.targetTable),
5303
+ contextValues?.(plan.targetTableName),
5304
+ context
5305
+ );
4995
5306
  const inserted = await executor.insert(plan.targetTable).values(values).returning();
4996
5307
  const created = inserted[0];
4997
5308
  if (!created) {
@@ -5001,7 +5312,7 @@ var createNestedWriteRuntime = (params) => {
5001
5312
  }
5002
5313
  patch[plan.localColPropName] = created[plan.foreignColPropName];
5003
5314
  } else if (op["connect"] !== void 0) {
5004
- const rows = await executor.select().from(plan.targetTable).where(conditionOf(plan, op["connect"], "connect"));
5315
+ const rows = await executor.select().from(plan.targetTable).where(conditionOf(plan, op["connect"], "connect", scope));
5005
5316
  if (rows.length !== 1) {
5006
5317
  throw new import_graphql8.GraphQLError(
5007
5318
  `Drizzle-GraphQL Error: 'connect' on '${relationName}' matched ${rows.length} rows \u2014 it attaches a single row, so its filter must match exactly one.`
@@ -5014,11 +5325,12 @@ var createNestedWriteRuntime = (params) => {
5014
5325
  }
5015
5326
  return patch;
5016
5327
  },
5017
- applyChildSide: async (executor, tableName, ops, parentRows) => {
5328
+ applyChildSide: async (executor, tableName, ops, parentRows, context) => {
5018
5329
  const tablePlans = plans[tableName];
5019
5330
  if (!tablePlans) {
5020
5331
  return;
5021
5332
  }
5333
+ const scope = resolveScope(policies, context, filterCtx);
5022
5334
  for (const [relationName, op] of Object.entries(ops)) {
5023
5335
  const plan = tablePlans[relationName];
5024
5336
  if (!plan || plan.fkSide !== "child") {
@@ -5035,34 +5347,38 @@ var createNestedWriteRuntime = (params) => {
5035
5347
  );
5036
5348
  }
5037
5349
  if (op["set"] !== void 0) {
5038
- await detachAll(executor, plan, key);
5350
+ await detachAll(executor, plan, key, scope);
5039
5351
  for (const filter of asArray(op["set"])) {
5040
- await executor.update(plan.targetTable).set({ [plan.foreignColPropName]: key }).where(conditionOf(plan, filter, "set"));
5352
+ await executor.update(plan.targetTable).set({ [plan.foreignColPropName]: key }).where(conditionOf(plan, filter, "set", scope));
5041
5353
  }
5042
5354
  }
5043
5355
  if (op["disconnect"] !== void 0) {
5044
5356
  if (plan.isOne) {
5045
5357
  if (op["disconnect"] === true) {
5046
- await detachAll(executor, plan, key);
5358
+ await detachAll(executor, plan, key, scope);
5047
5359
  }
5048
5360
  } else {
5049
5361
  for (const filter of asArray(op["disconnect"])) {
5050
- await executor.update(plan.targetTable).set({ [plan.foreignColPropName]: null }).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(plan.foreignCol, key), conditionOf(plan, filter, "disconnect")));
5362
+ await executor.update(plan.targetTable).set({ [plan.foreignColPropName]: null }).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(plan.foreignCol, key), conditionOf(plan, filter, "disconnect", scope)));
5051
5363
  }
5052
5364
  }
5053
5365
  }
5054
5366
  const attaches = op["connect"] !== void 0 || op["create"] !== void 0;
5055
5367
  if (plan.isOne && attaches && plan.canDetach && op["set"] === void 0) {
5056
- await detachAll(executor, plan, key);
5368
+ await detachAll(executor, plan, key, scope);
5057
5369
  }
5058
5370
  if (op["connect"] !== void 0) {
5059
5371
  for (const filter of asArray(op["connect"])) {
5060
- await executor.update(plan.targetTable).set({ [plan.foreignColPropName]: key }).where(conditionOf(plan, filter, "connect"));
5372
+ await executor.update(plan.targetTable).set({ [plan.foreignColPropName]: key }).where(conditionOf(plan, filter, "connect", scope));
5061
5373
  }
5062
5374
  }
5063
5375
  if (op["create"] !== void 0) {
5064
5376
  const rows = asArray(op["create"]).map((row) => ({
5065
- ...remapFromGraphQLSingleInput({ ...row }, plan.targetTable),
5377
+ ...applyContextValues(
5378
+ remapFromGraphQLSingleInput({ ...row }, plan.targetTable),
5379
+ contextValues?.(plan.targetTableName),
5380
+ context
5381
+ ),
5066
5382
  [plan.foreignColPropName]: key
5067
5383
  }));
5068
5384
  if (rows.length) {
@@ -5075,30 +5391,30 @@ var createNestedWriteRuntime = (params) => {
5075
5391
  };
5076
5392
  };
5077
5393
  var writeWithNestedOps = async (params) => {
5078
- const { executor, runtime, tableName, entries, remapValues, write } = params;
5394
+ const { executor, runtime, tableName, entries, remapValues, write, context } = params;
5079
5395
  return executor.transaction(async (tx) => {
5080
5396
  const rows = [];
5081
5397
  for (const entry of entries) {
5082
- const patch = await runtime.applyParentSide(tx, tableName, entry.ops);
5398
+ const patch = await runtime.applyParentSide(tx, tableName, entry.ops, context);
5083
5399
  const written = await write(tx, { ...remapValues(entry.columns), ...patch });
5084
- await runtime.applyChildSide(tx, tableName, entry.ops, written);
5400
+ await runtime.applyChildSide(tx, tableName, entry.ops, written, context);
5085
5401
  rows.push(...written);
5086
5402
  }
5087
5403
  return rows;
5088
5404
  });
5089
5405
  };
5090
5406
  var updateWithNestedOps = async (params) => {
5091
- const { executor, runtime, tableName, columns, ops, remapValues, write } = params;
5407
+ const { executor, runtime, tableName, columns, ops, remapValues, write, context } = params;
5092
5408
  return executor.transaction(async (tx) => {
5093
- const patch = await runtime.applyParentSide(tx, tableName, ops);
5409
+ const patch = await runtime.applyParentSide(tx, tableName, ops, context);
5094
5410
  const rows = await write(tx, { ...remapValues(columns), ...patch });
5095
- await runtime.applyChildSide(tx, tableName, ops, rows);
5411
+ await runtime.applyChildSide(tx, tableName, ops, rows, context);
5096
5412
  return rows;
5097
5413
  });
5098
5414
  };
5099
5415
 
5100
5416
  // src/util/builders/pg.ts
5101
- var generateSelectArray2 = (db, tableName, tables, relationMap, orderArgs, filterArgs, fieldName, typeName, typeNameMapper, filterCtx, distinctEnabled = true, limits) => {
5417
+ var generateSelectArray2 = (db, tableName, tables, relationMap, orderArgs, filterArgs, fieldName, typeName, typeNameMapper, filterCtx, distinctEnabled = true, limits, policies) => {
5102
5418
  const queryBase = db.query[tableName];
5103
5419
  const table = tables[tableName];
5104
5420
  const limitPolicy = limits?.(tableName);
@@ -5106,7 +5422,9 @@ var generateSelectArray2 = (db, tableName, tables, relationMap, orderArgs, filte
5106
5422
  const queryArgs = selectArrayArgs(
5107
5423
  orderArgs,
5108
5424
  filterArgs,
5109
- distinctEnabled ? generateDistinctEnum(table, typeName) : void 0
5425
+ distinctEnabled ? generateDistinctEnum(table, typeName) : void 0,
5426
+ policies?.softDelete,
5427
+ tableName
5110
5428
  );
5111
5429
  return {
5112
5430
  name: fieldName,
@@ -5114,6 +5432,7 @@ var generateSelectArray2 = (db, tableName, tables, relationMap, orderArgs, filte
5114
5432
  try {
5115
5433
  const parsedInfo = (0, import_graphql_parse_resolve_info3.parseResolveInfo)(info, { deep: true });
5116
5434
  const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);
5435
+ const scope = policies?.scope?.(context);
5117
5436
  const limit = applyLimitPolicy(args.limit, limitPolicy, fieldName);
5118
5437
  if (requestQueryBase) {
5119
5438
  return await runRelationalSelect({
@@ -5132,11 +5451,12 @@ var generateSelectArray2 = (db, tableName, tables, relationMap, orderArgs, filte
5132
5451
  limits,
5133
5452
  pkNames,
5134
5453
  db: executor,
5454
+ scope,
5135
5455
  // PostgreSQL sorts NULLs as the largest values (last in ASC).
5136
5456
  nullOrdering: "nulls-largest"
5137
5457
  });
5138
5458
  }
5139
- const { offset, orderBy, where, distinct, after } = args;
5459
+ const { offset, orderBy, where, distinct, after, deleted } = args;
5140
5460
  const selectedColumnsSql = extractSelectedColumnsFromTreeSQLFormat(
5141
5461
  parsedInfo.fieldsByTypeName[typeName],
5142
5462
  table,
@@ -5170,7 +5490,13 @@ var generateSelectArray2 = (db, tableName, tables, relationMap, orderArgs, filte
5170
5490
  }
5171
5491
  }
5172
5492
  const cursorCondition = after != null && cursorEntries ? buildCursorCondition(table, cursorEntries, decodeCursor(after, cursorEntries), "nulls-largest") : void 0;
5173
- const baseWhereSql = where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0;
5493
+ const baseWhereSql = withScope(
5494
+ scope,
5495
+ tableName,
5496
+ table,
5497
+ where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0,
5498
+ deleted
5499
+ );
5174
5500
  const whereSql = cursorCondition ? (0, import_drizzle_orm8.and)(baseWhereSql, cursorCondition) : baseWhereSql;
5175
5501
  let distinctKeys;
5176
5502
  if (distinct?.length) {
@@ -5225,9 +5551,9 @@ var generateSelectArray2 = (db, tableName, tables, relationMap, orderArgs, filte
5225
5551
  args: queryArgs
5226
5552
  };
5227
5553
  };
5228
- var generateSelectSingle2 = (db, tableName, tables, relationMap, orderArgs, filterArgs, fieldName, typeName, typeNameMapper, filterCtx, limits) => {
5554
+ var generateSelectSingle2 = (db, tableName, tables, relationMap, orderArgs, filterArgs, fieldName, typeName, typeNameMapper, filterCtx, limits, policies) => {
5229
5555
  const queryBase = db.query[tableName];
5230
- const queryArgs = selectSingleArgs(orderArgs, filterArgs);
5556
+ const queryArgs = selectSingleArgs(orderArgs, filterArgs, policies?.softDelete, tableName);
5231
5557
  const table = tables[tableName];
5232
5558
  const pkNames = pgPrimaryKeyPropNames(table);
5233
5559
  return {
@@ -5236,6 +5562,7 @@ var generateSelectSingle2 = (db, tableName, tables, relationMap, orderArgs, filt
5236
5562
  try {
5237
5563
  const parsedInfo = (0, import_graphql_parse_resolve_info3.parseResolveInfo)(info, { deep: true });
5238
5564
  const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);
5565
+ const scope = policies?.scope?.(context);
5239
5566
  if (requestQueryBase) {
5240
5567
  return await runRelationalSelect({
5241
5568
  queryBase: requestQueryBase,
@@ -5251,18 +5578,26 @@ var generateSelectSingle2 = (db, tableName, tables, relationMap, orderArgs, filt
5251
5578
  filterCtx,
5252
5579
  limits,
5253
5580
  pkNames,
5254
- db: executor
5581
+ db: executor,
5582
+ scope
5255
5583
  });
5256
5584
  }
5257
- const { offset, orderBy, where } = args;
5585
+ const { offset, orderBy, where, deleted } = args;
5258
5586
  const selectedColumnsSql = extractSelectedColumnsFromTreeSQLFormat(
5259
5587
  parsedInfo.fieldsByTypeName[typeName],
5260
5588
  table,
5261
5589
  { tableName, relationMap, tables }
5262
5590
  );
5263
5591
  let q = executor.select(selectedColumnsSql).from(table);
5264
- if (where) {
5265
- q = q.where(extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)));
5592
+ const whereSql = withScope(
5593
+ scope,
5594
+ tableName,
5595
+ table,
5596
+ where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0,
5597
+ deleted
5598
+ );
5599
+ if (whereSql) {
5600
+ q = q.where(whereSql);
5266
5601
  }
5267
5602
  if (orderBy) {
5268
5603
  q = q.orderBy(...extractOrderBy(table, orderBy, relationFilterCtx(filterCtx, tableName), where));
@@ -5283,7 +5618,7 @@ var generateSelectSingle2 = (db, tableName, tables, relationMap, orderArgs, filt
5283
5618
  };
5284
5619
  };
5285
5620
  var pgPrimaryKeyPropNames = (table) => getPrimaryKeyPropNamesFromConfig(table, import_pg_core2.getTableConfig);
5286
- var generateInsertArray2 = (db, tableName, table, tables, relationMap, baseType, fieldName, typeName, typeNameMapper, conflictDoNothing = false, txCtx, nested, limits) => {
5621
+ var generateInsertArray2 = (db, tableName, table, tables, relationMap, baseType, fieldName, typeName, typeNameMapper, conflictDoNothing = false, txCtx, nested, limits, policies) => {
5287
5622
  const queryArgs = {
5288
5623
  values: {
5289
5624
  type: new import_graphql9.GraphQLNonNull(new import_graphql9.GraphQLList(new import_graphql9.GraphQLNonNull(baseType)))
@@ -5300,7 +5635,13 @@ var generateInsertArray2 = (db, tableName, table, tables, relationMap, baseType,
5300
5635
  }
5301
5636
  const entries = nested?.enabled(tableName) ? args.values.map((values) => nested.split(tableName, values)) : void 0;
5302
5637
  const nestedEntries = entries?.some((entry) => nested.hasOps(entry.ops)) ? entries : void 0;
5303
- const input = nestedEntries ? [] : remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : args.values, table);
5638
+ const contextColumns = policies?.contextValues?.(tableName);
5639
+ const scope = policies?.scope?.(context);
5640
+ const input = nestedEntries ? [] : applyContextValuesAll(
5641
+ remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : args.values, table),
5642
+ contextColumns,
5643
+ context
5644
+ );
5304
5645
  const parsedInfo = (0, import_graphql_parse_resolve_info3.parseResolveInfo)(info, {
5305
5646
  deep: true
5306
5647
  });
@@ -5313,7 +5654,8 @@ var generateInsertArray2 = (db, tableName, table, tables, relationMap, baseType,
5313
5654
  table,
5314
5655
  pkNames,
5315
5656
  parsedInfo,
5316
- limits
5657
+ limits,
5658
+ scope
5317
5659
  });
5318
5660
  const returning = nestedEntries ? nested.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table) : columns;
5319
5661
  const runInsert = async (target, values) => {
@@ -5328,8 +5670,9 @@ var generateInsertArray2 = (db, tableName, table, tables, relationMap, baseType,
5328
5670
  runtime: nested,
5329
5671
  tableName,
5330
5672
  entries: nestedEntries,
5331
- remapValues: (values) => remapFromGraphQLSingleInput(values, table),
5332
- write: (tx, values) => runInsert(tx, [values])
5673
+ remapValues: (values) => applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),
5674
+ write: (tx, values) => runInsert(tx, [values]),
5675
+ context
5333
5676
  }) : await runInsert(executor, input);
5334
5677
  const enriched = hasRelations ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams) : result;
5335
5678
  return remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);
@@ -5341,7 +5684,7 @@ var generateInsertArray2 = (db, tableName, table, tables, relationMap, baseType,
5341
5684
  args: queryArgs
5342
5685
  };
5343
5686
  };
5344
- var generateInsertSingle2 = (db, tableName, table, tables, relationMap, baseType, fieldName, typeName, typeNameMapper, conflictDoNothing = false, txCtx, nested, limits) => {
5687
+ var generateInsertSingle2 = (db, tableName, table, tables, relationMap, baseType, fieldName, typeName, typeNameMapper, conflictDoNothing = false, txCtx, nested, limits, policies) => {
5345
5688
  const queryArgs = {
5346
5689
  values: {
5347
5690
  type: new import_graphql9.GraphQLNonNull(baseType)
@@ -5355,7 +5698,13 @@ var generateInsertSingle2 = (db, tableName, table, tables, relationMap, baseType
5355
5698
  return await runMutation(db, context, info, txCtx, async (executor) => {
5356
5699
  const entry = nested?.enabled(tableName) ? nested.split(tableName, args.values) : void 0;
5357
5700
  const nestedEntry = entry && nested.hasOps(entry.ops) ? entry : void 0;
5358
- const input = nestedEntry ? {} : remapFromGraphQLSingleInput(entry ? entry.columns : args.values, table);
5701
+ const contextColumns = policies?.contextValues?.(tableName);
5702
+ const scope = policies?.scope?.(context);
5703
+ const input = nestedEntry ? {} : applyContextValues(
5704
+ remapFromGraphQLSingleInput(entry ? entry.columns : args.values, table),
5705
+ contextColumns,
5706
+ context
5707
+ );
5359
5708
  const parsedInfo = (0, import_graphql_parse_resolve_info3.parseResolveInfo)(info, {
5360
5709
  deep: true
5361
5710
  });
@@ -5368,7 +5717,8 @@ var generateInsertSingle2 = (db, tableName, table, tables, relationMap, baseType
5368
5717
  table,
5369
5718
  pkNames,
5370
5719
  parsedInfo,
5371
- limits
5720
+ limits,
5721
+ scope
5372
5722
  });
5373
5723
  const returning = nestedEntry ? nested.withJoinColumns(tableName, nestedEntry.ops, { ...columns }, table) : columns;
5374
5724
  const runInsert = async (target, values) => {
@@ -5383,8 +5733,9 @@ var generateInsertSingle2 = (db, tableName, table, tables, relationMap, baseType
5383
5733
  runtime: nested,
5384
5734
  tableName,
5385
5735
  entries: [nestedEntry],
5386
- remapValues: (values) => remapFromGraphQLSingleInput(values, table),
5387
- write: runInsert
5736
+ remapValues: (values) => applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),
5737
+ write: runInsert,
5738
+ context
5388
5739
  }) : await runInsert(executor, input);
5389
5740
  if (!result[0]) {
5390
5741
  if (!conflictDoNothing) {
@@ -5402,7 +5753,7 @@ var generateInsertSingle2 = (db, tableName, table, tables, relationMap, baseType
5402
5753
  args: queryArgs
5403
5754
  };
5404
5755
  };
5405
- var generateUpsert2 = (db, tableName, table, tables, relationMap, baseType, onConflictType, uniqueSets, fieldName, typeName, single, typeNameMapper, filterCtx, txCtx, nested, limits) => {
5756
+ var generateUpsert2 = (db, tableName, table, tables, relationMap, baseType, onConflictType, uniqueSets, fieldName, typeName, single, typeNameMapper, filterCtx, txCtx, nested, limits, policies) => {
5406
5757
  const queryArgs = {
5407
5758
  values: {
5408
5759
  type: single ? new import_graphql9.GraphQLNonNull(baseType) : new import_graphql9.GraphQLNonNull(new import_graphql9.GraphQLList(new import_graphql9.GraphQLNonNull(baseType)))
@@ -5424,7 +5775,13 @@ var generateUpsert2 = (db, tableName, table, tables, relationMap, baseType, onCo
5424
5775
  }
5425
5776
  const entries = nested?.enabled(tableName) ? supplied.map((values) => nested.split(tableName, values)) : void 0;
5426
5777
  const nestedEntries = entries?.some((entry) => nested.hasOps(entry.ops)) ? entries : void 0;
5427
- const input = nestedEntries ? [] : remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table);
5778
+ const contextColumns = policies?.contextValues?.(tableName);
5779
+ const scope = policies?.scope?.(context);
5780
+ const input = nestedEntries ? [] : applyContextValuesAll(
5781
+ remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table),
5782
+ contextColumns,
5783
+ context
5784
+ );
5428
5785
  const parsedInfo = (0, import_graphql_parse_resolve_info3.parseResolveInfo)(info, { deep: true });
5429
5786
  const { columns, hasRelations, withParams } = prepareMutationRelationColumns({
5430
5787
  relationMap,
@@ -5435,7 +5792,8 @@ var generateUpsert2 = (db, tableName, table, tables, relationMap, baseType, onCo
5435
5792
  table,
5436
5793
  pkNames,
5437
5794
  parsedInfo,
5438
- limits
5795
+ limits,
5796
+ scope
5439
5797
  });
5440
5798
  const returning = nestedEntries ? nested.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table) : columns;
5441
5799
  const runUpsert = async (target, values) => {
@@ -5450,7 +5808,8 @@ var generateUpsert2 = (db, tableName, table, tables, relationMap, baseType, onCo
5450
5808
  buildWhere: (where) => extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))
5451
5809
  });
5452
5810
  let query = target.insert(table).values(values).returning(returning);
5453
- query = plan.action === "NOTHING" ? query.onConflictDoNothing(plan.target ? { target: plan.target } : void 0) : query.onConflictDoUpdate({ target: plan.target, set: plan.set, setWhere: plan.setWhere });
5811
+ const setWhere = withScope(scope, tableName, table, plan.setWhere);
5812
+ query = plan.action === "NOTHING" ? query.onConflictDoNothing(plan.target ? { target: plan.target } : void 0) : query.onConflictDoUpdate({ target: plan.target, set: plan.set, setWhere });
5454
5813
  return await query;
5455
5814
  };
5456
5815
  const result = nestedEntries ? await writeWithNestedOps({
@@ -5458,8 +5817,9 @@ var generateUpsert2 = (db, tableName, table, tables, relationMap, baseType, onCo
5458
5817
  runtime: nested,
5459
5818
  tableName,
5460
5819
  entries: nestedEntries,
5461
- remapValues: (values) => remapFromGraphQLSingleInput(values, table),
5462
- write: (tx, values) => runUpsert(tx, [values])
5820
+ remapValues: (values) => applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),
5821
+ write: (tx, values) => runUpsert(tx, [values]),
5822
+ context
5463
5823
  }) : await runUpsert(executor, input);
5464
5824
  if (single && !result[0]) {
5465
5825
  return void 0;
@@ -5474,7 +5834,7 @@ var generateUpsert2 = (db, tableName, table, tables, relationMap, baseType, onCo
5474
5834
  args: queryArgs
5475
5835
  };
5476
5836
  };
5477
- var generateUpdate2 = (db, tableName, table, tables, relationMap, setArgs, filterArgs, fieldName, typeName, single, requireWhere, typeNameMapper, filterCtx, txCtx, nested, limits) => {
5837
+ var generateUpdate2 = (db, tableName, table, tables, relationMap, setArgs, filterArgs, fieldName, typeName, single, requireWhere, typeNameMapper, filterCtx, txCtx, nested, limits, policies) => {
5478
5838
  const queryArgs = {
5479
5839
  set: {
5480
5840
  type: new import_graphql9.GraphQLNonNull(setArgs)
@@ -5490,6 +5850,7 @@ var generateUpdate2 = (db, tableName, table, tables, relationMap, setArgs, filte
5490
5850
  try {
5491
5851
  return await runMutation(db, context, info, txCtx, async (executor) => {
5492
5852
  const { where, set } = args;
5853
+ const scope = policies?.scope?.(context);
5493
5854
  const parsedInfo = (0, import_graphql_parse_resolve_info3.parseResolveInfo)(info, {
5494
5855
  deep: true
5495
5856
  });
@@ -5502,16 +5863,25 @@ var generateUpdate2 = (db, tableName, table, tables, relationMap, setArgs, filte
5502
5863
  table,
5503
5864
  pkNames,
5504
5865
  parsedInfo,
5505
- limits
5866
+ limits,
5867
+ scope
5506
5868
  });
5507
5869
  const entry = nested?.enabled(tableName) ? nested.split(tableName, set) : void 0;
5508
5870
  const nestedOps = entry && nested.hasOps(entry.ops) ? entry.ops : void 0;
5509
- const input = remapUpdateInput(entry ? entry.columns : set, table, tableName);
5871
+ const input = stripContextValues(
5872
+ remapUpdateInput(entry ? entry.columns : set, table, tableName),
5873
+ policies?.contextValues?.(tableName)
5874
+ );
5510
5875
  if (!Object.keys(input).length && !nestedOps) {
5511
5876
  throw new import_graphql9.GraphQLError("Unable to update with no values specified!");
5512
5877
  }
5513
5878
  const relationCtx = relationFilterCtx(filterCtx, tableName);
5514
- const filters = single || requireWhere ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx) : where ? extractFilters(table, tableName, where, relationCtx) : void 0;
5879
+ const filters = withScope(
5880
+ scope,
5881
+ tableName,
5882
+ table,
5883
+ single || requireWhere ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx) : where ? extractFilters(table, tableName, where, relationCtx) : void 0
5884
+ );
5515
5885
  if (single) {
5516
5886
  await assertSingleMatch(executor, table, filters, fieldName);
5517
5887
  }
@@ -5531,7 +5901,8 @@ var generateUpdate2 = (db, tableName, table, tables, relationMap, setArgs, filte
5531
5901
  columns: input,
5532
5902
  ops: nestedOps,
5533
5903
  remapValues: (values) => values,
5534
- write: runUpdate
5904
+ write: runUpdate,
5905
+ context
5535
5906
  }) : await runUpdate(executor, input);
5536
5907
  if (single && result.length > 1) {
5537
5908
  throw new import_graphql9.GraphQLError(`${fieldName}: 'where' matched more than one row!`);
@@ -5549,7 +5920,7 @@ var generateUpdate2 = (db, tableName, table, tables, relationMap, setArgs, filte
5549
5920
  args: queryArgs
5550
5921
  };
5551
5922
  };
5552
- var generateUpdateMany2 = (db, tableName, table, tables, relationMap, updateManyInput, fieldName, typeName, typeNameMapper, filterCtx, txCtx, nested, limits) => {
5923
+ var generateUpdateMany2 = (db, tableName, table, tables, relationMap, updateManyInput, fieldName, typeName, typeNameMapper, filterCtx, txCtx, nested, limits, policies) => {
5553
5924
  const queryArgs = {
5554
5925
  updates: {
5555
5926
  type: new import_graphql9.GraphQLNonNull(new import_graphql9.GraphQLList(new import_graphql9.GraphQLNonNull(updateManyInput)))
@@ -5565,6 +5936,8 @@ var generateUpdateMany2 = (db, tableName, table, tables, relationMap, updateMany
5565
5936
  if (!updates.length) {
5566
5937
  throw new import_graphql9.GraphQLError("No updates were provided!");
5567
5938
  }
5939
+ const scope = policies?.scope?.(context);
5940
+ const contextColumns = policies?.contextValues?.(tableName);
5568
5941
  const parsedInfo = (0, import_graphql_parse_resolve_info3.parseResolveInfo)(info, {
5569
5942
  deep: true
5570
5943
  });
@@ -5577,19 +5950,28 @@ var generateUpdateMany2 = (db, tableName, table, tables, relationMap, updateMany
5577
5950
  table,
5578
5951
  pkNames,
5579
5952
  parsedInfo,
5580
- limits
5953
+ limits,
5954
+ scope
5581
5955
  });
5582
5956
  const entries = updates.map(({ where, set }) => {
5583
5957
  const split = nested?.enabled(tableName) ? nested.split(tableName, set) : void 0;
5584
5958
  const ops = split && nested.hasOps(split.ops) ? split.ops : void 0;
5585
- const input = remapUpdateInput(split ? split.columns : set, table, tableName);
5959
+ const input = stripContextValues(
5960
+ remapUpdateInput(split ? split.columns : set, table, tableName),
5961
+ contextColumns
5962
+ );
5586
5963
  if (!Object.keys(input).length && !ops) {
5587
5964
  throw new import_graphql9.GraphQLError("Unable to update with no values specified!");
5588
5965
  }
5589
5966
  return {
5590
5967
  set: input,
5591
5968
  ops,
5592
- filters: where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0
5969
+ filters: withScope(
5970
+ scope,
5971
+ tableName,
5972
+ table,
5973
+ where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0
5974
+ )
5593
5975
  };
5594
5976
  });
5595
5977
  const returning = entries.some((entry) => entry.ops) ? nested.withJoinColumns(
@@ -5603,7 +5985,7 @@ var generateUpdateMany2 = (db, tableName, table, tables, relationMap, updateMany
5603
5985
  const perEntry = await executor.transaction(async (tx) => {
5604
5986
  const results = [];
5605
5987
  for (const entry of entries) {
5606
- const values = entry.ops ? { ...entry.set, ...await nested.applyParentSide(tx, tableName, entry.ops) } : entry.set;
5988
+ const values = entry.ops ? { ...entry.set, ...await nested.applyParentSide(tx, tableName, entry.ops, context) } : entry.set;
5607
5989
  const writes = Object.keys(values).length > 0;
5608
5990
  let query = writes ? tx.update(table).set(values) : tx.select(returning).from(table);
5609
5991
  if (entry.filters) {
@@ -5611,7 +5993,7 @@ var generateUpdateMany2 = (db, tableName, table, tables, relationMap, updateMany
5611
5993
  }
5612
5994
  const rows = await (writes ? query.returning(returning) : query);
5613
5995
  if (entry.ops) {
5614
- await nested.applyChildSide(tx, tableName, entry.ops, rows);
5996
+ await nested.applyChildSide(tx, tableName, entry.ops, rows, context);
5615
5997
  }
5616
5998
  results.push(rows);
5617
5999
  }
@@ -5640,7 +6022,8 @@ var generateUpdateMany2 = (db, tableName, table, tables, relationMap, updateMany
5640
6022
  args: queryArgs
5641
6023
  };
5642
6024
  };
5643
- var generateDelete2 = (db, tableName, table, filterArgs, fieldName, typeName, single, requireWhere, filterCtx, selectionCtx, txCtx) => {
6025
+ var generateDelete2 = (db, tableName, table, filterArgs, fieldName, typeName, single, requireWhere, filterCtx, selectionCtx, txCtx, policies, restore = false) => {
6026
+ const softDelete = policies?.softDelete?.(tableName);
5644
6027
  const queryArgs = {
5645
6028
  where: {
5646
6029
  type: single || requireWhere ? new import_graphql9.GraphQLNonNull(filterArgs) : filterArgs
@@ -5652,6 +6035,7 @@ var generateDelete2 = (db, tableName, table, filterArgs, fieldName, typeName, si
5652
6035
  try {
5653
6036
  return await runMutation(db, context, info, txCtx, async (executor) => {
5654
6037
  const { where } = args;
6038
+ const scope = policies?.scope?.(context);
5655
6039
  const parsedInfo = (0, import_graphql_parse_resolve_info3.parseResolveInfo)(info, {
5656
6040
  deep: true
5657
6041
  });
@@ -5661,11 +6045,17 @@ var generateDelete2 = (db, tableName, table, filterArgs, fieldName, typeName, si
5661
6045
  selectionCtx
5662
6046
  );
5663
6047
  const relationCtx = relationFilterCtx(filterCtx, tableName);
5664
- const filters = single || requireWhere ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx) : where ? extractFilters(table, tableName, where, relationCtx) : void 0;
6048
+ const filters = withScope(
6049
+ scope,
6050
+ tableName,
6051
+ table,
6052
+ single || requireWhere ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx) : where ? extractFilters(table, tableName, where, relationCtx) : void 0,
6053
+ restore ? "ONLY" : void 0
6054
+ );
5665
6055
  if (single) {
5666
6056
  await assertSingleMatch(executor, table, filters, fieldName);
5667
6057
  }
5668
- let query = executor.delete(table);
6058
+ let query = softDelete ? executor.update(table).set({ [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted() }) : executor.delete(table);
5669
6059
  if (filters) {
5670
6060
  query = query.where(filters);
5671
6061
  }
@@ -5719,12 +6109,17 @@ function generateSchemaData2(db, schema, relations, options) {
5719
6109
  attachTargetPrimaryKeys(namedRelations, tables, pgPrimaryKeyPropNames);
5720
6110
  const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);
5721
6111
  const filterCtx = { tables, relationMap: namedRelations };
6112
+ const tablePolicies = options.policies;
6113
+ const contextValuesOf = tablePolicies?.contextValues;
6114
+ const softDeleteOf = tablePolicies?.softDelete;
6115
+ const policies = bindPolicies(tablePolicies, filterCtx);
5722
6116
  const resolverFactory = createRelationResolverFactory(
5723
6117
  db,
5724
6118
  tables,
5725
6119
  "nulls-largest",
5726
6120
  filterCtx,
5727
- limits
6121
+ limits,
6122
+ tablePolicies
5728
6123
  );
5729
6124
  const cacheCtx = {
5730
6125
  genericFilterCache: /* @__PURE__ */ new Map(),
@@ -5742,6 +6137,8 @@ function generateSchemaData2(db, schema, relations, options) {
5742
6137
  limits,
5743
6138
  docs: options.docs ?? {},
5744
6139
  primaryKeyOf: (name) => tables[name] ? pgPrimaryKeyPropNames(tables[name]) : [],
6140
+ contextValuesOf,
6141
+ softDeleteOf,
5745
6142
  featureOf
5746
6143
  };
5747
6144
  const nestedPlans = features.nestedWrites ? buildNestedWritePlans(
@@ -5752,8 +6149,13 @@ function generateSchemaData2(db, schema, relations, options) {
5752
6149
  extractRelationJoinColumns
5753
6150
  ) : void 0;
5754
6151
  const nestedTypes = nestedPlans ? createNestedWriteTypes({ plans: nestedPlans, cacheCtx, typeNameMapper, insertPrefix: prefixes.insert }) : void 0;
5755
- const nestedRuntime = nestedPlans ? createNestedWriteRuntime({ plans: nestedPlans, filterCtx }) : void 0;
5756
- const relationAggregateFactory = anyTable("relationAggregates") ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx) : void 0;
6152
+ const nestedRuntime = nestedPlans ? createNestedWriteRuntime({
6153
+ plans: nestedPlans,
6154
+ filterCtx,
6155
+ policies: tablePolicies,
6156
+ contextValues: contextValuesOf
6157
+ }) : void 0;
6158
+ const relationAggregateFactory = anyTable("relationAggregates") ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx, tablePolicies) : void 0;
5757
6159
  const queries = {};
5758
6160
  const mutations = {};
5759
6161
  const mutationTxCtx = createMutationTxCtx(options.transactions);
@@ -5799,8 +6201,11 @@ function generateSchemaData2(db, schema, relations, options) {
5799
6201
  updateCountFieldName,
5800
6202
  deleteFieldName,
5801
6203
  deleteSingleFieldName,
6204
+ restoreFieldName,
6205
+ restoreSingleFieldName,
5802
6206
  deleteCountFieldName
5803
6207
  } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);
6208
+ const softDeleteInfo = softDeleteOf?.(tableName);
5804
6209
  const selectArrGenerated = generateSelectArray2(
5805
6210
  db,
5806
6211
  tableName,
@@ -5813,7 +6218,8 @@ function generateSchemaData2(db, schema, relations, options) {
5813
6218
  typeNameMapper,
5814
6219
  filterCtx,
5815
6220
  tableFeatures.distinct,
5816
- limits
6221
+ limits,
6222
+ policies
5817
6223
  );
5818
6224
  const selectSingleGenerated = generateSelectSingle2(
5819
6225
  db,
@@ -5826,7 +6232,8 @@ function generateSchemaData2(db, schema, relations, options) {
5826
6232
  typeName,
5827
6233
  typeNameMapper,
5828
6234
  filterCtx,
5829
- limits
6235
+ limits,
6236
+ policies
5830
6237
  );
5831
6238
  const insertArrGenerated = tableFeatures.insert ? generateInsertArray2(
5832
6239
  db,
@@ -5841,7 +6248,8 @@ function generateSchemaData2(db, schema, relations, options) {
5841
6248
  conflictDoNothing,
5842
6249
  mutationTxCtx,
5843
6250
  nestedRuntime,
5844
- limits
6251
+ limits,
6252
+ policies
5845
6253
  ) : void 0;
5846
6254
  const insertSingleGenerated = tableFeatures.insert ? generateInsertSingle2(
5847
6255
  db,
@@ -5856,7 +6264,8 @@ function generateSchemaData2(db, schema, relations, options) {
5856
6264
  conflictDoNothing,
5857
6265
  mutationTxCtx,
5858
6266
  nestedRuntime,
5859
- limits
6267
+ limits,
6268
+ policies
5860
6269
  ) : void 0;
5861
6270
  const uniqueSets = tableFeatures.upsert ? getUniqueColumnSets(schema[tableName], import_pg_core2.getTableConfig) : [];
5862
6271
  const onConflictInput = tableFeatures.upsert ? generateOnConflictInput({
@@ -5882,7 +6291,8 @@ function generateSchemaData2(db, schema, relations, options) {
5882
6291
  filterCtx,
5883
6292
  mutationTxCtx,
5884
6293
  nestedRuntime,
5885
- limits
6294
+ limits,
6295
+ policies
5886
6296
  ) : void 0;
5887
6297
  const upsertSingleGenerated = onConflictInput ? generateUpsert2(
5888
6298
  db,
@@ -5900,7 +6310,8 @@ function generateSchemaData2(db, schema, relations, options) {
5900
6310
  filterCtx,
5901
6311
  mutationTxCtx,
5902
6312
  nestedRuntime,
5903
- limits
6313
+ limits,
6314
+ policies
5904
6315
  ) : void 0;
5905
6316
  const updateGenerated = tableFeatures.update ? generateUpdate2(
5906
6317
  db,
@@ -5918,7 +6329,8 @@ function generateSchemaData2(db, schema, relations, options) {
5918
6329
  filterCtx,
5919
6330
  mutationTxCtx,
5920
6331
  nestedRuntime,
5921
- limits
6332
+ limits,
6333
+ policies
5922
6334
  ) : void 0;
5923
6335
  const updateSingleGenerated = tableFeatures.update ? generateUpdate2(
5924
6336
  db,
@@ -5936,7 +6348,8 @@ function generateSchemaData2(db, schema, relations, options) {
5936
6348
  filterCtx,
5937
6349
  mutationTxCtx,
5938
6350
  nestedRuntime,
5939
- limits
6351
+ limits,
6352
+ policies
5940
6353
  ) : void 0;
5941
6354
  const updateManyInput = tableFeatures.update && tableFeatures.updateMany ? generateUpdateManyInput({ typeName, updatePrefix: prefixes.update, updateInput, tableFilters }) : void 0;
5942
6355
  const updateManyGenerated = updateManyInput ? generateUpdateMany2(
@@ -5952,7 +6365,8 @@ function generateSchemaData2(db, schema, relations, options) {
5952
6365
  filterCtx,
5953
6366
  mutationTxCtx,
5954
6367
  nestedRuntime,
5955
- limits
6368
+ limits,
6369
+ policies
5956
6370
  ) : void 0;
5957
6371
  const deleteGenerated = tableFeatures.delete ? generateDelete2(
5958
6372
  db,
@@ -5965,7 +6379,8 @@ function generateSchemaData2(db, schema, relations, options) {
5965
6379
  tableFeatures.requireWhere,
5966
6380
  filterCtx,
5967
6381
  { tableName, relationMap: namedRelations, tables },
5968
- mutationTxCtx
6382
+ mutationTxCtx,
6383
+ policies
5969
6384
  ) : void 0;
5970
6385
  const deleteSingleGenerated = tableFeatures.delete ? generateDelete2(
5971
6386
  db,
@@ -5978,7 +6393,38 @@ function generateSchemaData2(db, schema, relations, options) {
5978
6393
  tableFeatures.requireWhere,
5979
6394
  filterCtx,
5980
6395
  { tableName, relationMap: namedRelations, tables },
5981
- mutationTxCtx
6396
+ mutationTxCtx,
6397
+ policies
6398
+ ) : void 0;
6399
+ const restoreGenerated = softDeleteInfo ? generateDelete2(
6400
+ db,
6401
+ tableName,
6402
+ schema[tableName],
6403
+ tableFilters,
6404
+ restoreFieldName,
6405
+ typeName,
6406
+ false,
6407
+ tableFeatures.requireWhere,
6408
+ filterCtx,
6409
+ { tableName, relationMap: namedRelations, tables },
6410
+ mutationTxCtx,
6411
+ policies,
6412
+ true
6413
+ ) : void 0;
6414
+ const restoreSingleGenerated = softDeleteInfo ? generateDelete2(
6415
+ db,
6416
+ tableName,
6417
+ schema[tableName],
6418
+ tableFilters,
6419
+ restoreSingleFieldName,
6420
+ typeName,
6421
+ true,
6422
+ tableFeatures.requireWhere,
6423
+ filterCtx,
6424
+ { tableName, relationMap: namedRelations, tables },
6425
+ mutationTxCtx,
6426
+ policies,
6427
+ true
5982
6428
  ) : void 0;
5983
6429
  const updateCountGenerated = tableFeatures.update && tableFeatures.countMutations ? generateWriteCount({
5984
6430
  db,
@@ -6012,7 +6458,8 @@ function generateSchemaData2(db, schema, relations, options) {
6012
6458
  typeName,
6013
6459
  aggregateFieldName,
6014
6460
  tableFilters,
6015
- filterCtx
6461
+ filterCtx,
6462
+ tablePolicies
6016
6463
  ) : void 0;
6017
6464
  const groupByType = tableFeatures.aggregates && tableFeatures.groupBy ? generateGroupByType(schema[tableName], tableName, typeName, cacheCtx) : void 0;
6018
6465
  const groupByEnum = groupByType ? generateGroupByEnum(schema[tableName], tableName, typeName) : void 0;
@@ -6026,7 +6473,8 @@ function generateSchemaData2(db, schema, relations, options) {
6026
6473
  tableFilters,
6027
6474
  groupByEnum,
6028
6475
  havingInput,
6029
- filterCtx
6476
+ filterCtx,
6477
+ tablePolicies
6030
6478
  ) : void 0;
6031
6479
  queries[selectArrGenerated.name] = {
6032
6480
  type: selectArrOutput,
@@ -6163,6 +6611,26 @@ function generateSchemaData2(db, schema, relations, options) {
6163
6611
  }
6164
6612
  };
6165
6613
  }
6614
+ if (restoreGenerated) {
6615
+ mutations[restoreGenerated.name] = {
6616
+ type: arrTableItemOutput,
6617
+ args: restoreGenerated.args,
6618
+ resolve: restoreGenerated.resolver,
6619
+ extensions: {
6620
+ drizzle: drizzleMeta({ kind: "mutation", operation: "restore", single: false, targetArg: "where" })
6621
+ }
6622
+ };
6623
+ }
6624
+ if (restoreSingleGenerated) {
6625
+ mutations[restoreSingleGenerated.name] = {
6626
+ type: singleTableItemOutput,
6627
+ args: restoreSingleGenerated.args,
6628
+ resolve: restoreSingleGenerated.resolver,
6629
+ extensions: {
6630
+ drizzle: drizzleMeta({ kind: "mutation", operation: "restore", single: true, targetArg: "where" })
6631
+ }
6632
+ };
6633
+ }
6166
6634
  if (updateCountGenerated) {
6167
6635
  mutations[updateCountGenerated.name] = {
6168
6636
  type: new import_graphql9.GraphQLNonNull(import_graphql9.GraphQLInt),
@@ -6228,7 +6696,7 @@ var import_drizzle_orm9 = require("drizzle-orm");
6228
6696
  var import_sqlite_core2 = require("drizzle-orm/sqlite-core");
6229
6697
  var import_graphql10 = require("graphql");
6230
6698
  var import_graphql_parse_resolve_info4 = require("graphql-parse-resolve-info");
6231
- var generateSelectArray3 = (db, tableName, tables, relationMap, orderArgs, filterArgs, fieldName, typeName, typeNameMapper, filterCtx, distinctEnabled = true, limits) => {
6699
+ var generateSelectArray3 = (db, tableName, tables, relationMap, orderArgs, filterArgs, fieldName, typeName, typeNameMapper, filterCtx, distinctEnabled = true, limits, policies) => {
6232
6700
  const queryBase = db.query[tableName];
6233
6701
  if (!queryBase) {
6234
6702
  throw new Error(
@@ -6241,7 +6709,9 @@ var generateSelectArray3 = (db, tableName, tables, relationMap, orderArgs, filte
6241
6709
  const queryArgs = selectArrayArgs(
6242
6710
  orderArgs,
6243
6711
  filterArgs,
6244
- distinctEnabled ? generateDistinctEnum(table, typeName) : void 0
6712
+ distinctEnabled ? generateDistinctEnum(table, typeName) : void 0,
6713
+ policies?.softDelete,
6714
+ tableName
6245
6715
  );
6246
6716
  return {
6247
6717
  name: fieldName,
@@ -6265,6 +6735,7 @@ var generateSelectArray3 = (db, tableName, tables, relationMap, orderArgs, filte
6265
6735
  limits,
6266
6736
  pkNames,
6267
6737
  db: executor,
6738
+ scope: policies?.scope?.(context),
6268
6739
  // SQLite sorts NULLs as the smallest values (first in ASC).
6269
6740
  nullOrdering: "nulls-smallest"
6270
6741
  });
@@ -6275,14 +6746,14 @@ var generateSelectArray3 = (db, tableName, tables, relationMap, orderArgs, filte
6275
6746
  args: queryArgs
6276
6747
  };
6277
6748
  };
6278
- var generateSelectSingle3 = (db, tableName, tables, relationMap, orderArgs, filterArgs, fieldName, typeName, typeNameMapper, filterCtx, limits) => {
6749
+ var generateSelectSingle3 = (db, tableName, tables, relationMap, orderArgs, filterArgs, fieldName, typeName, typeNameMapper, filterCtx, limits, policies) => {
6279
6750
  const queryBase = db.query[tableName];
6280
6751
  if (!queryBase) {
6281
6752
  throw new Error(
6282
6753
  `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`
6283
6754
  );
6284
6755
  }
6285
- const queryArgs = selectSingleArgs(orderArgs, filterArgs);
6756
+ const queryArgs = selectSingleArgs(orderArgs, filterArgs, policies?.softDelete, tableName);
6286
6757
  const table = tables[tableName];
6287
6758
  const pkNames = sqlitePrimaryKeyPropNames(table);
6288
6759
  return {
@@ -6305,7 +6776,8 @@ var generateSelectSingle3 = (db, tableName, tables, relationMap, orderArgs, filt
6305
6776
  filterCtx,
6306
6777
  limits,
6307
6778
  pkNames,
6308
- db: executor
6779
+ db: executor,
6780
+ scope: policies?.scope?.(context)
6309
6781
  });
6310
6782
  } catch (e) {
6311
6783
  throw toGraphQLError(e);
@@ -6315,7 +6787,7 @@ var generateSelectSingle3 = (db, tableName, tables, relationMap, orderArgs, filt
6315
6787
  };
6316
6788
  };
6317
6789
  var sqlitePrimaryKeyPropNames = (table) => getPrimaryKeyPropNamesFromConfig(table, import_sqlite_core2.getTableConfig);
6318
- var generateInsertArray3 = (db, tableName, table, tables, relationMap, baseType, fieldName, typeName, typeNameMapper, conflictDoNothing = false, txCtx, nested, limits) => {
6790
+ var generateInsertArray3 = (db, tableName, table, tables, relationMap, baseType, fieldName, typeName, typeNameMapper, conflictDoNothing = false, txCtx, nested, limits, policies) => {
6319
6791
  const queryArgs = {
6320
6792
  values: {
6321
6793
  type: new import_graphql10.GraphQLNonNull(new import_graphql10.GraphQLList(new import_graphql10.GraphQLNonNull(baseType)))
@@ -6332,7 +6804,13 @@ var generateInsertArray3 = (db, tableName, table, tables, relationMap, baseType,
6332
6804
  }
6333
6805
  const entries = nested?.enabled(tableName) ? args.values.map((values) => nested.split(tableName, values)) : void 0;
6334
6806
  const nestedEntries = entries?.some((entry) => nested.hasOps(entry.ops)) ? entries : void 0;
6335
- const input = nestedEntries ? [] : remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : args.values, table);
6807
+ const contextColumns = policies?.contextValues?.(tableName);
6808
+ const scope = policies?.scope?.(context);
6809
+ const input = nestedEntries ? [] : applyContextValuesAll(
6810
+ remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : args.values, table),
6811
+ contextColumns,
6812
+ context
6813
+ );
6336
6814
  const parsedInfo = (0, import_graphql_parse_resolve_info4.parseResolveInfo)(info, {
6337
6815
  deep: true
6338
6816
  });
@@ -6345,7 +6823,8 @@ var generateInsertArray3 = (db, tableName, table, tables, relationMap, baseType,
6345
6823
  table,
6346
6824
  pkNames,
6347
6825
  parsedInfo,
6348
- limits
6826
+ limits,
6827
+ scope
6349
6828
  });
6350
6829
  const returning = nestedEntries ? nested.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table) : columns;
6351
6830
  const runInsert = async (target, values) => {
@@ -6360,8 +6839,9 @@ var generateInsertArray3 = (db, tableName, table, tables, relationMap, baseType,
6360
6839
  runtime: nested,
6361
6840
  tableName,
6362
6841
  entries: nestedEntries,
6363
- remapValues: (values) => remapFromGraphQLSingleInput(values, table),
6364
- write: (tx, values) => runInsert(tx, [values])
6842
+ remapValues: (values) => applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),
6843
+ write: (tx, values) => runInsert(tx, [values]),
6844
+ context
6365
6845
  }) : await runInsert(executor, input);
6366
6846
  const enriched = hasRelations ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams) : result;
6367
6847
  return remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);
@@ -6373,7 +6853,7 @@ var generateInsertArray3 = (db, tableName, table, tables, relationMap, baseType,
6373
6853
  args: queryArgs
6374
6854
  };
6375
6855
  };
6376
- var generateInsertSingle3 = (db, tableName, table, tables, relationMap, baseType, fieldName, typeName, typeNameMapper, conflictDoNothing = false, txCtx, nested, limits) => {
6856
+ var generateInsertSingle3 = (db, tableName, table, tables, relationMap, baseType, fieldName, typeName, typeNameMapper, conflictDoNothing = false, txCtx, nested, limits, policies) => {
6377
6857
  const queryArgs = {
6378
6858
  values: {
6379
6859
  type: new import_graphql10.GraphQLNonNull(baseType)
@@ -6387,7 +6867,13 @@ var generateInsertSingle3 = (db, tableName, table, tables, relationMap, baseType
6387
6867
  return await runMutation(db, context, info, txCtx, async (executor) => {
6388
6868
  const entry = nested?.enabled(tableName) ? nested.split(tableName, args.values) : void 0;
6389
6869
  const nestedEntry = entry && nested.hasOps(entry.ops) ? entry : void 0;
6390
- const input = nestedEntry ? {} : remapFromGraphQLSingleInput(entry ? entry.columns : args.values, table);
6870
+ const contextColumns = policies?.contextValues?.(tableName);
6871
+ const scope = policies?.scope?.(context);
6872
+ const input = nestedEntry ? {} : applyContextValues(
6873
+ remapFromGraphQLSingleInput(entry ? entry.columns : args.values, table),
6874
+ contextColumns,
6875
+ context
6876
+ );
6391
6877
  const parsedInfo = (0, import_graphql_parse_resolve_info4.parseResolveInfo)(info, {
6392
6878
  deep: true
6393
6879
  });
@@ -6400,7 +6886,8 @@ var generateInsertSingle3 = (db, tableName, table, tables, relationMap, baseType
6400
6886
  table,
6401
6887
  pkNames,
6402
6888
  parsedInfo,
6403
- limits
6889
+ limits,
6890
+ scope
6404
6891
  });
6405
6892
  const returning = nestedEntry ? nested.withJoinColumns(tableName, nestedEntry.ops, { ...columns }, table) : columns;
6406
6893
  const runInsert = async (target, values) => {
@@ -6415,8 +6902,9 @@ var generateInsertSingle3 = (db, tableName, table, tables, relationMap, baseType
6415
6902
  runtime: nested,
6416
6903
  tableName,
6417
6904
  entries: [nestedEntry],
6418
- remapValues: (values) => remapFromGraphQLSingleInput(values, table),
6419
- write: runInsert
6905
+ remapValues: (values) => applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),
6906
+ write: runInsert,
6907
+ context
6420
6908
  }) : await runInsert(executor, input);
6421
6909
  if (!result[0]) {
6422
6910
  if (!conflictDoNothing) {
@@ -6434,7 +6922,7 @@ var generateInsertSingle3 = (db, tableName, table, tables, relationMap, baseType
6434
6922
  args: queryArgs
6435
6923
  };
6436
6924
  };
6437
- var generateUpsert3 = (db, tableName, table, tables, relationMap, baseType, onConflictType, uniqueSets, fieldName, typeName, single, typeNameMapper, filterCtx, txCtx, nested, limits) => {
6925
+ var generateUpsert3 = (db, tableName, table, tables, relationMap, baseType, onConflictType, uniqueSets, fieldName, typeName, single, typeNameMapper, filterCtx, txCtx, nested, limits, policies) => {
6438
6926
  const queryArgs = {
6439
6927
  values: {
6440
6928
  type: single ? new import_graphql10.GraphQLNonNull(baseType) : new import_graphql10.GraphQLNonNull(new import_graphql10.GraphQLList(new import_graphql10.GraphQLNonNull(baseType)))
@@ -6456,7 +6944,13 @@ var generateUpsert3 = (db, tableName, table, tables, relationMap, baseType, onCo
6456
6944
  }
6457
6945
  const entries = nested?.enabled(tableName) ? supplied.map((values) => nested.split(tableName, values)) : void 0;
6458
6946
  const nestedEntries = entries?.some((entry) => nested.hasOps(entry.ops)) ? entries : void 0;
6459
- const input = nestedEntries ? [] : remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table);
6947
+ const contextColumns = policies?.contextValues?.(tableName);
6948
+ const scope = policies?.scope?.(context);
6949
+ const input = nestedEntries ? [] : applyContextValuesAll(
6950
+ remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table),
6951
+ contextColumns,
6952
+ context
6953
+ );
6460
6954
  const parsedInfo = (0, import_graphql_parse_resolve_info4.parseResolveInfo)(info, { deep: true });
6461
6955
  const { columns, hasRelations, withParams } = prepareMutationRelationColumns({
6462
6956
  relationMap,
@@ -6467,7 +6961,8 @@ var generateUpsert3 = (db, tableName, table, tables, relationMap, baseType, onCo
6467
6961
  table,
6468
6962
  pkNames,
6469
6963
  parsedInfo,
6470
- limits
6964
+ limits,
6965
+ scope
6471
6966
  });
6472
6967
  const returning = nestedEntries ? nested.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table) : columns;
6473
6968
  const runUpsert = async (target, values) => {
@@ -6482,7 +6977,8 @@ var generateUpsert3 = (db, tableName, table, tables, relationMap, baseType, onCo
6482
6977
  buildWhere: (where) => extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))
6483
6978
  });
6484
6979
  let query = target.insert(table).values(values).returning(returning);
6485
- query = plan.action === "NOTHING" ? query.onConflictDoNothing(plan.target ? { target: plan.target } : void 0) : query.onConflictDoUpdate({ target: plan.target, set: plan.set, setWhere: plan.setWhere });
6980
+ const setWhere = withScope(scope, tableName, table, plan.setWhere);
6981
+ query = plan.action === "NOTHING" ? query.onConflictDoNothing(plan.target ? { target: plan.target } : void 0) : query.onConflictDoUpdate({ target: plan.target, set: plan.set, setWhere });
6486
6982
  return await query;
6487
6983
  };
6488
6984
  const result = nestedEntries ? await writeWithNestedOps({
@@ -6490,8 +6986,9 @@ var generateUpsert3 = (db, tableName, table, tables, relationMap, baseType, onCo
6490
6986
  runtime: nested,
6491
6987
  tableName,
6492
6988
  entries: nestedEntries,
6493
- remapValues: (values) => remapFromGraphQLSingleInput(values, table),
6494
- write: (tx, values) => runUpsert(tx, [values])
6989
+ remapValues: (values) => applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),
6990
+ write: (tx, values) => runUpsert(tx, [values]),
6991
+ context
6495
6992
  }) : await runUpsert(executor, input);
6496
6993
  if (single && !result[0]) {
6497
6994
  return void 0;
@@ -6506,7 +7003,7 @@ var generateUpsert3 = (db, tableName, table, tables, relationMap, baseType, onCo
6506
7003
  args: queryArgs
6507
7004
  };
6508
7005
  };
6509
- var generateUpdate3 = (db, tableName, table, tables, relationMap, setArgs, filterArgs, fieldName, typeName, single, requireWhere, typeNameMapper, filterCtx, txCtx, nested, limits) => {
7006
+ var generateUpdate3 = (db, tableName, table, tables, relationMap, setArgs, filterArgs, fieldName, typeName, single, requireWhere, typeNameMapper, filterCtx, txCtx, nested, limits, policies) => {
6510
7007
  const queryArgs = {
6511
7008
  set: {
6512
7009
  type: new import_graphql10.GraphQLNonNull(setArgs)
@@ -6522,6 +7019,7 @@ var generateUpdate3 = (db, tableName, table, tables, relationMap, setArgs, filte
6522
7019
  try {
6523
7020
  return await runMutation(db, context, info, txCtx, async (executor) => {
6524
7021
  const { where, set } = args;
7022
+ const scope = policies?.scope?.(context);
6525
7023
  const parsedInfo = (0, import_graphql_parse_resolve_info4.parseResolveInfo)(info, {
6526
7024
  deep: true
6527
7025
  });
@@ -6534,16 +7032,25 @@ var generateUpdate3 = (db, tableName, table, tables, relationMap, setArgs, filte
6534
7032
  table,
6535
7033
  pkNames,
6536
7034
  parsedInfo,
6537
- limits
7035
+ limits,
7036
+ scope
6538
7037
  });
6539
7038
  const entry = nested?.enabled(tableName) ? nested.split(tableName, set) : void 0;
6540
7039
  const nestedOps = entry && nested.hasOps(entry.ops) ? entry.ops : void 0;
6541
- const input = remapUpdateInput(entry ? entry.columns : set, table, tableName);
7040
+ const input = stripContextValues(
7041
+ remapUpdateInput(entry ? entry.columns : set, table, tableName),
7042
+ policies?.contextValues?.(tableName)
7043
+ );
6542
7044
  if (!Object.keys(input).length && !nestedOps) {
6543
7045
  throw new import_graphql10.GraphQLError("Unable to update with no values specified!");
6544
7046
  }
6545
7047
  const relationCtx = relationFilterCtx(filterCtx, tableName);
6546
- const filters = single || requireWhere ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx) : where ? extractFilters(table, tableName, where, relationCtx) : void 0;
7048
+ const filters = withScope(
7049
+ scope,
7050
+ tableName,
7051
+ table,
7052
+ single || requireWhere ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx) : where ? extractFilters(table, tableName, where, relationCtx) : void 0
7053
+ );
6547
7054
  if (single) {
6548
7055
  await assertSingleMatch(executor, table, filters, fieldName);
6549
7056
  }
@@ -6563,7 +7070,8 @@ var generateUpdate3 = (db, tableName, table, tables, relationMap, setArgs, filte
6563
7070
  columns: input,
6564
7071
  ops: nestedOps,
6565
7072
  remapValues: (values) => values,
6566
- write: runUpdate
7073
+ write: runUpdate,
7074
+ context
6567
7075
  }) : await runUpdate(executor, input);
6568
7076
  if (single && result.length > 1) {
6569
7077
  throw new import_graphql10.GraphQLError(`${fieldName}: 'where' matched more than one row!`);
@@ -6581,7 +7089,7 @@ var generateUpdate3 = (db, tableName, table, tables, relationMap, setArgs, filte
6581
7089
  args: queryArgs
6582
7090
  };
6583
7091
  };
6584
- var generateUpdateMany3 = (db, tableName, table, tables, relationMap, updateManyInput, fieldName, typeName, typeNameMapper, filterCtx, txCtx, nested, limits) => {
7092
+ var generateUpdateMany3 = (db, tableName, table, tables, relationMap, updateManyInput, fieldName, typeName, typeNameMapper, filterCtx, txCtx, nested, limits, policies) => {
6585
7093
  const queryArgs = {
6586
7094
  updates: {
6587
7095
  type: new import_graphql10.GraphQLNonNull(new import_graphql10.GraphQLList(new import_graphql10.GraphQLNonNull(updateManyInput)))
@@ -6597,6 +7105,8 @@ var generateUpdateMany3 = (db, tableName, table, tables, relationMap, updateMany
6597
7105
  if (!updates.length) {
6598
7106
  throw new import_graphql10.GraphQLError("No updates were provided!");
6599
7107
  }
7108
+ const scope = policies?.scope?.(context);
7109
+ const contextColumns = policies?.contextValues?.(tableName);
6600
7110
  const parsedInfo = (0, import_graphql_parse_resolve_info4.parseResolveInfo)(info, {
6601
7111
  deep: true
6602
7112
  });
@@ -6609,19 +7119,28 @@ var generateUpdateMany3 = (db, tableName, table, tables, relationMap, updateMany
6609
7119
  table,
6610
7120
  pkNames,
6611
7121
  parsedInfo,
6612
- limits
7122
+ limits,
7123
+ scope
6613
7124
  });
6614
7125
  const entries = updates.map(({ where, set }) => {
6615
7126
  const split = nested?.enabled(tableName) ? nested.split(tableName, set) : void 0;
6616
7127
  const ops = split && nested.hasOps(split.ops) ? split.ops : void 0;
6617
- const input = remapUpdateInput(split ? split.columns : set, table, tableName);
7128
+ const input = stripContextValues(
7129
+ remapUpdateInput(split ? split.columns : set, table, tableName),
7130
+ contextColumns
7131
+ );
6618
7132
  if (!Object.keys(input).length && !ops) {
6619
7133
  throw new import_graphql10.GraphQLError("Unable to update with no values specified!");
6620
7134
  }
6621
7135
  return {
6622
7136
  set: input,
6623
7137
  ops,
6624
- filters: where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0
7138
+ filters: withScope(
7139
+ scope,
7140
+ tableName,
7141
+ table,
7142
+ where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : void 0
7143
+ )
6625
7144
  };
6626
7145
  });
6627
7146
  const anyNested = entries.some((entry) => entry.ops);
@@ -6639,7 +7158,7 @@ var generateUpdateMany3 = (db, tableName, table, tables, relationMap, updateMany
6639
7158
  return query.returning(returning).all();
6640
7159
  };
6641
7160
  const runNestedEntry = async (tx, entry) => {
6642
- const values = entry.ops ? { ...entry.set, ...await nested.applyParentSide(tx, tableName, entry.ops) } : entry.set;
7161
+ const values = entry.ops ? { ...entry.set, ...await nested.applyParentSide(tx, tableName, entry.ops, context) } : entry.set;
6643
7162
  const writes = Object.keys(values).length > 0;
6644
7163
  let query = writes ? tx.update(table).set(values) : tx.select(returning).from(table);
6645
7164
  if (entry.filters) {
@@ -6647,7 +7166,7 @@ var generateUpdateMany3 = (db, tableName, table, tables, relationMap, updateMany
6647
7166
  }
6648
7167
  const rows = await (writes ? query.returning(returning) : query);
6649
7168
  if (entry.ops) {
6650
- await nested.applyChildSide(tx, tableName, entry.ops, rows);
7169
+ await nested.applyChildSide(tx, tableName, entry.ops, rows, context);
6651
7170
  }
6652
7171
  return rows;
6653
7172
  };
@@ -6700,7 +7219,8 @@ var generateUpdateMany3 = (db, tableName, table, tables, relationMap, updateMany
6700
7219
  args: queryArgs
6701
7220
  };
6702
7221
  };
6703
- var generateDelete3 = (db, tableName, table, filterArgs, fieldName, typeName, single, requireWhere, filterCtx, selectionCtx, txCtx) => {
7222
+ var generateDelete3 = (db, tableName, table, filterArgs, fieldName, typeName, single, requireWhere, filterCtx, selectionCtx, txCtx, policies, restore = false) => {
7223
+ const softDelete = policies?.softDelete?.(tableName);
6704
7224
  const queryArgs = {
6705
7225
  where: {
6706
7226
  type: single || requireWhere ? new import_graphql10.GraphQLNonNull(filterArgs) : filterArgs
@@ -6712,6 +7232,7 @@ var generateDelete3 = (db, tableName, table, filterArgs, fieldName, typeName, si
6712
7232
  try {
6713
7233
  return await runMutation(db, context, info, txCtx, async (executor) => {
6714
7234
  const { where } = args;
7235
+ const scope = policies?.scope?.(context);
6715
7236
  const parsedInfo = (0, import_graphql_parse_resolve_info4.parseResolveInfo)(info, {
6716
7237
  deep: true
6717
7238
  });
@@ -6721,11 +7242,17 @@ var generateDelete3 = (db, tableName, table, filterArgs, fieldName, typeName, si
6721
7242
  selectionCtx
6722
7243
  );
6723
7244
  const relationCtx = relationFilterCtx(filterCtx, tableName);
6724
- const filters = single || requireWhere ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx) : where ? extractFilters(table, tableName, where, relationCtx) : void 0;
7245
+ const filters = withScope(
7246
+ scope,
7247
+ tableName,
7248
+ table,
7249
+ single || requireWhere ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx) : where ? extractFilters(table, tableName, where, relationCtx) : void 0,
7250
+ restore ? "ONLY" : void 0
7251
+ );
6725
7252
  if (single) {
6726
7253
  await assertSingleMatch(executor, table, filters, fieldName);
6727
7254
  }
6728
- let query = executor.delete(table);
7255
+ let query = softDelete ? executor.update(table).set({ [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted() }) : executor.delete(table);
6729
7256
  if (filters) {
6730
7257
  query = query.where(filters);
6731
7258
  }
@@ -6780,12 +7307,17 @@ var generateSchemaData3 = (db, schema, relations, options) => {
6780
7307
  attachTargetPrimaryKeys(namedRelations, tables, sqlitePrimaryKeyPropNames);
6781
7308
  const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);
6782
7309
  const filterCtx = { tables, relationMap: namedRelations };
7310
+ const tablePolicies = options.policies;
7311
+ const contextValuesOf = tablePolicies?.contextValues;
7312
+ const softDeleteOf = tablePolicies?.softDelete;
7313
+ const policies = bindPolicies(tablePolicies, filterCtx);
6783
7314
  const resolverFactory = createRelationResolverFactory(
6784
7315
  db,
6785
7316
  tables,
6786
7317
  "nulls-smallest",
6787
7318
  filterCtx,
6788
- limits
7319
+ limits,
7320
+ tablePolicies
6789
7321
  );
6790
7322
  const cacheCtx = {
6791
7323
  genericFilterCache: /* @__PURE__ */ new Map(),
@@ -6803,6 +7335,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
6803
7335
  limits,
6804
7336
  docs: options.docs ?? {},
6805
7337
  primaryKeyOf: (name) => tables[name] ? sqlitePrimaryKeyPropNames(tables[name]) : [],
7338
+ contextValuesOf,
7339
+ softDeleteOf,
6806
7340
  featureOf
6807
7341
  };
6808
7342
  if (features.nestedWrites && db.resultKind === "sync") {
@@ -6818,8 +7352,13 @@ var generateSchemaData3 = (db, schema, relations, options) => {
6818
7352
  extractRelationJoinColumns
6819
7353
  ) : void 0;
6820
7354
  const nestedTypes = nestedPlans ? createNestedWriteTypes({ plans: nestedPlans, cacheCtx, typeNameMapper, insertPrefix: prefixes.insert }) : void 0;
6821
- const nestedRuntime = nestedPlans ? createNestedWriteRuntime({ plans: nestedPlans, filterCtx }) : void 0;
6822
- const relationAggregateFactory = anyTable("relationAggregates") ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx) : void 0;
7355
+ const nestedRuntime = nestedPlans ? createNestedWriteRuntime({
7356
+ plans: nestedPlans,
7357
+ filterCtx,
7358
+ policies: tablePolicies,
7359
+ contextValues: contextValuesOf
7360
+ }) : void 0;
7361
+ const relationAggregateFactory = anyTable("relationAggregates") ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx, tablePolicies) : void 0;
6823
7362
  const queries = {};
6824
7363
  const mutations = {};
6825
7364
  if (options.transactions && db.resultKind === "sync") {
@@ -6870,8 +7409,11 @@ var generateSchemaData3 = (db, schema, relations, options) => {
6870
7409
  updateCountFieldName,
6871
7410
  deleteFieldName,
6872
7411
  deleteSingleFieldName,
7412
+ restoreFieldName,
7413
+ restoreSingleFieldName,
6873
7414
  deleteCountFieldName
6874
7415
  } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);
7416
+ const softDeleteInfo = softDeleteOf?.(tableName);
6875
7417
  const selectArrGenerated = generateSelectArray3(
6876
7418
  db,
6877
7419
  tableName,
@@ -6884,7 +7426,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
6884
7426
  typeNameMapper,
6885
7427
  filterCtx,
6886
7428
  tableFeatures.distinct,
6887
- limits
7429
+ limits,
7430
+ policies
6888
7431
  );
6889
7432
  const selectSingleGenerated = generateSelectSingle3(
6890
7433
  db,
@@ -6897,7 +7440,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
6897
7440
  typeName,
6898
7441
  typeNameMapper,
6899
7442
  filterCtx,
6900
- limits
7443
+ limits,
7444
+ policies
6901
7445
  );
6902
7446
  const insertArrGenerated = tableFeatures.insert ? generateInsertArray3(
6903
7447
  db,
@@ -6912,7 +7456,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
6912
7456
  conflictDoNothing,
6913
7457
  mutationTxCtx,
6914
7458
  nestedRuntime,
6915
- limits
7459
+ limits,
7460
+ policies
6916
7461
  ) : void 0;
6917
7462
  const insertSingleGenerated = tableFeatures.insert ? generateInsertSingle3(
6918
7463
  db,
@@ -6927,7 +7472,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
6927
7472
  conflictDoNothing,
6928
7473
  mutationTxCtx,
6929
7474
  nestedRuntime,
6930
- limits
7475
+ limits,
7476
+ policies
6931
7477
  ) : void 0;
6932
7478
  const uniqueSets = tableFeatures.upsert ? getUniqueColumnSets(schema[tableName], import_sqlite_core2.getTableConfig) : [];
6933
7479
  const onConflictInput = tableFeatures.upsert ? generateOnConflictInput({
@@ -6953,7 +7499,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
6953
7499
  filterCtx,
6954
7500
  mutationTxCtx,
6955
7501
  nestedRuntime,
6956
- limits
7502
+ limits,
7503
+ policies
6957
7504
  ) : void 0;
6958
7505
  const upsertSingleGenerated = onConflictInput ? generateUpsert3(
6959
7506
  db,
@@ -6971,7 +7518,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
6971
7518
  filterCtx,
6972
7519
  mutationTxCtx,
6973
7520
  nestedRuntime,
6974
- limits
7521
+ limits,
7522
+ policies
6975
7523
  ) : void 0;
6976
7524
  const updateGenerated = tableFeatures.update ? generateUpdate3(
6977
7525
  db,
@@ -6989,7 +7537,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
6989
7537
  filterCtx,
6990
7538
  mutationTxCtx,
6991
7539
  nestedRuntime,
6992
- limits
7540
+ limits,
7541
+ policies
6993
7542
  ) : void 0;
6994
7543
  const updateSingleGenerated = tableFeatures.update ? generateUpdate3(
6995
7544
  db,
@@ -7007,7 +7556,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
7007
7556
  filterCtx,
7008
7557
  mutationTxCtx,
7009
7558
  nestedRuntime,
7010
- limits
7559
+ limits,
7560
+ policies
7011
7561
  ) : void 0;
7012
7562
  const updateManyInput = tableFeatures.update && tableFeatures.updateMany ? generateUpdateManyInput({ typeName, updatePrefix: prefixes.update, updateInput, tableFilters }) : void 0;
7013
7563
  const updateManyGenerated = updateManyInput ? generateUpdateMany3(
@@ -7023,7 +7573,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
7023
7573
  filterCtx,
7024
7574
  mutationTxCtx,
7025
7575
  nestedRuntime,
7026
- limits
7576
+ limits,
7577
+ policies
7027
7578
  ) : void 0;
7028
7579
  const deleteGenerated = tableFeatures.delete ? generateDelete3(
7029
7580
  db,
@@ -7036,7 +7587,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
7036
7587
  tableFeatures.requireWhere,
7037
7588
  filterCtx,
7038
7589
  { tableName, relationMap: namedRelations, tables },
7039
- mutationTxCtx
7590
+ mutationTxCtx,
7591
+ policies
7040
7592
  ) : void 0;
7041
7593
  const deleteSingleGenerated = tableFeatures.delete ? generateDelete3(
7042
7594
  db,
@@ -7049,7 +7601,38 @@ var generateSchemaData3 = (db, schema, relations, options) => {
7049
7601
  tableFeatures.requireWhere,
7050
7602
  filterCtx,
7051
7603
  { tableName, relationMap: namedRelations, tables },
7052
- mutationTxCtx
7604
+ mutationTxCtx,
7605
+ policies
7606
+ ) : void 0;
7607
+ const restoreGenerated = softDeleteInfo ? generateDelete3(
7608
+ db,
7609
+ tableName,
7610
+ schema[tableName],
7611
+ tableFilters,
7612
+ restoreFieldName,
7613
+ typeName,
7614
+ false,
7615
+ tableFeatures.requireWhere,
7616
+ filterCtx,
7617
+ { tableName, relationMap: namedRelations, tables },
7618
+ mutationTxCtx,
7619
+ policies,
7620
+ true
7621
+ ) : void 0;
7622
+ const restoreSingleGenerated = softDeleteInfo ? generateDelete3(
7623
+ db,
7624
+ tableName,
7625
+ schema[tableName],
7626
+ tableFilters,
7627
+ restoreSingleFieldName,
7628
+ typeName,
7629
+ true,
7630
+ tableFeatures.requireWhere,
7631
+ filterCtx,
7632
+ { tableName, relationMap: namedRelations, tables },
7633
+ mutationTxCtx,
7634
+ policies,
7635
+ true
7053
7636
  ) : void 0;
7054
7637
  const updateCountGenerated = tableFeatures.update && tableFeatures.countMutations ? generateWriteCount({
7055
7638
  db,
@@ -7083,7 +7666,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
7083
7666
  typeName,
7084
7667
  aggregateFieldName,
7085
7668
  tableFilters,
7086
- filterCtx
7669
+ filterCtx,
7670
+ tablePolicies
7087
7671
  ) : void 0;
7088
7672
  const groupByType = tableFeatures.aggregates && tableFeatures.groupBy ? generateGroupByType(schema[tableName], tableName, typeName, cacheCtx) : void 0;
7089
7673
  const groupByEnum = groupByType ? generateGroupByEnum(schema[tableName], tableName, typeName) : void 0;
@@ -7097,7 +7681,8 @@ var generateSchemaData3 = (db, schema, relations, options) => {
7097
7681
  tableFilters,
7098
7682
  groupByEnum,
7099
7683
  havingInput,
7100
- filterCtx
7684
+ filterCtx,
7685
+ tablePolicies
7101
7686
  ) : void 0;
7102
7687
  queries[selectArrGenerated.name] = {
7103
7688
  type: selectArrOutput,
@@ -7234,6 +7819,26 @@ var generateSchemaData3 = (db, schema, relations, options) => {
7234
7819
  }
7235
7820
  };
7236
7821
  }
7822
+ if (restoreGenerated) {
7823
+ mutations[restoreGenerated.name] = {
7824
+ type: arrTableItemOutput,
7825
+ args: restoreGenerated.args,
7826
+ resolve: restoreGenerated.resolver,
7827
+ extensions: {
7828
+ drizzle: drizzleMeta({ kind: "mutation", operation: "restore", single: false, targetArg: "where" })
7829
+ }
7830
+ };
7831
+ }
7832
+ if (restoreSingleGenerated) {
7833
+ mutations[restoreSingleGenerated.name] = {
7834
+ type: singleTableItemOutput,
7835
+ args: restoreSingleGenerated.args,
7836
+ resolve: restoreSingleGenerated.resolver,
7837
+ extensions: {
7838
+ drizzle: drizzleMeta({ kind: "mutation", operation: "restore", single: true, targetArg: "where" })
7839
+ }
7840
+ };
7841
+ }
7237
7842
  if (updateCountGenerated) {
7238
7843
  mutations[updateCountGenerated.name] = {
7239
7844
  type: new import_graphql10.GraphQLNonNull(import_graphql10.GraphQLInt),
@@ -7444,7 +8049,8 @@ var buildSchema = (db, config) => {
7444
8049
  insert: config?.prefixes?.insert ?? "create",
7445
8050
  delete: config?.prefixes?.delete ?? "delete",
7446
8051
  update: config?.prefixes?.update ?? "update",
7447
- upsert: config?.prefixes?.upsert ?? "upsert"
8052
+ upsert: config?.prefixes?.upsert ?? "upsert",
8053
+ restore: config?.prefixes?.restore ?? "restore"
7448
8054
  };
7449
8055
  const suffixes = {
7450
8056
  list: config?.suffixes?.list ?? "",
@@ -7489,6 +8095,66 @@ var buildSchema = (db, config) => {
7489
8095
  limitPolicyCache.set(tableName, resolved);
7490
8096
  return resolved;
7491
8097
  } : void 0;
8098
+ const scopeConfig = config?.scope;
8099
+ const contextValuesConfig = config?.contextValues;
8100
+ if (scopeConfig || contextValuesConfig) {
8101
+ const tableNames = new Set(tableKeys);
8102
+ for (const [tableName, hook] of Object.entries(scopeConfig ?? {})) {
8103
+ if (!tableNames.has(tableName)) {
8104
+ throw new Error(
8105
+ `Drizzle-GraphQL Error: config.scope names '${tableName}', which is not a table in the Drizzle schema.`
8106
+ );
8107
+ }
8108
+ if (typeof hook !== "function") {
8109
+ throw new Error(`Drizzle-GraphQL Error: config.scope.${tableName} must be a function.`);
8110
+ }
8111
+ }
8112
+ for (const [tableName, columnHooks] of Object.entries(contextValuesConfig ?? {})) {
8113
+ if (!tableNames.has(tableName)) {
8114
+ throw new Error(
8115
+ `Drizzle-GraphQL Error: config.contextValues names '${tableName}', which is not a table in the Drizzle schema.`
8116
+ );
8117
+ }
8118
+ const columns = (0, import_drizzle_orm11.getColumns)(schema[tableName]);
8119
+ for (const [columnName, hook] of Object.entries(columnHooks)) {
8120
+ if (!columns[columnName]) {
8121
+ throw new Error(
8122
+ `Drizzle-GraphQL Error: config.contextValues names '${tableName}.${columnName}', which is not a column of that table.`
8123
+ );
8124
+ }
8125
+ if (typeof hook !== "function") {
8126
+ throw new Error(`Drizzle-GraphQL Error: config.contextValues.${tableName}.${columnName} must be a function.`);
8127
+ }
8128
+ }
8129
+ }
8130
+ }
8131
+ const softDeleteConfig = config?.softDelete;
8132
+ const softDeleteInfos = /* @__PURE__ */ new Map();
8133
+ if (softDeleteConfig) {
8134
+ if (typeof softDeleteConfig === "function") {
8135
+ for (const tableName of tableKeys) {
8136
+ const declaration = softDeleteConfig(schema[tableName], tableName);
8137
+ if (declaration) {
8138
+ softDeleteInfos.set(tableName, resolveSoftDeleteInfo(schema[tableName], tableName, declaration));
8139
+ }
8140
+ }
8141
+ } else {
8142
+ const tableNames = new Set(tableKeys);
8143
+ for (const [tableName, declaration] of Object.entries(softDeleteConfig)) {
8144
+ if (!tableNames.has(tableName)) {
8145
+ throw new Error(
8146
+ `Drizzle-GraphQL Error: config.softDelete names '${tableName}', which is not a table in the Drizzle schema.`
8147
+ );
8148
+ }
8149
+ softDeleteInfos.set(tableName, resolveSoftDeleteInfo(schema[tableName], tableName, declaration));
8150
+ }
8151
+ }
8152
+ }
8153
+ const policies = scopeConfig || contextValuesConfig || softDeleteInfos.size ? {
8154
+ scope: scopeConfig ? (tableName) => scopeConfig[tableName] : void 0,
8155
+ contextValues: contextValuesConfig ? (tableName) => contextValuesConfig[tableName] : void 0,
8156
+ softDelete: softDeleteInfos.size ? (tableName) => softDeleteInfos.get(tableName) : void 0
8157
+ } : void 0;
7492
8158
  const exclude = config?.exclude;
7493
8159
  if (exclude) {
7494
8160
  const tableNames = new Set(tableKeys);
@@ -7606,6 +8272,7 @@ var buildSchema = (db, config) => {
7606
8272
  enumNameMapper: config?.enumNameMapper,
7607
8273
  transactions,
7608
8274
  limits,
8275
+ policies,
7609
8276
  exclude,
7610
8277
  docs: {
7611
8278
  describeColumn: config?.describeColumn,