@vantreeseba/drizzle-graphql 7.8.0 → 7.9.1

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/README.md CHANGED
@@ -945,6 +945,56 @@ supplies no `orderBy`:
945
945
  An explicit `orderBy` always takes precedence, composite primary keys are ordered by every
946
946
  key column, and an unpaginated list query is left unordered so no sort is paid for.
947
947
 
948
+ ## Default ordering
949
+
950
+ A table usually has one ordering that is right nearly every time it is read — newest first,
951
+ priority first, name alphabetical. `defaults` names that ordering once, and every query that
952
+ does not ask for its own gets it:
953
+
954
+ ```ts
955
+ buildSchema(db, {
956
+ defaults: {
957
+ Todos: { orderBy: { priority: 'desc', createdAt: 'desc' } },
958
+ Users: { orderBy: { name: 'asc' } },
959
+ },
960
+ });
961
+ ```
962
+
963
+ ```graphql
964
+ # ordered by priority desc, then createdAt desc — nothing in the query says so
965
+ { todos { id title } }
966
+ ```
967
+
968
+ Keys are the table's key in your Drizzle schema and the column's property name, so a typo in
969
+ either fails at `buildSchema` time rather than silently doing nothing. Each column takes
970
+ `'asc'`, `'desc'`, or a `{ direction, priority? }` object mirroring the `orderBy` argument.
971
+ Columns sort highest `priority` first, and the shorthand leaves it unset, so the shorthand
972
+ falls back to the order the keys are written in — the object form is there for when you would
973
+ rather state the precedence than depend on that:
974
+
975
+ ```ts
976
+ defaults: {
977
+ Todos: { orderBy: { createdAt: { direction: 'desc', priority: 1 }, priority: { direction: 'desc', priority: 2 } } },
978
+ }
979
+ ```
980
+
981
+ It applies to list queries, `<tableName>Single` queries, and to-many relation fields on both
982
+ the eager and the lazy relation paths — a relation takes the default of the table it *reads*,
983
+ not its parent's. To-one relation fields are a single row and take no ordering.
984
+
985
+ Two details worth stating plainly:
986
+
987
+ - **Any `orderBy` in the request wins outright.** The default is a fallback for a missing
988
+ argument, not a base that client ordering is appended to. To ask for *no* ordering, pass
989
+ `orderBy: {}` — an empty object is still an argument, so it suppresses the default.
990
+ - **A default ordering makes an unpaginated list query pay for a sort.** That is the point,
991
+ but it is a cost a table with no `defaults` entry does not pay; a build with no `defaults`
992
+ behaves exactly as before.
993
+
994
+ Cursor pagination composes with it: a default-ordered page is ordered by those columns plus
995
+ the primary key tiebreak, and its `cursor` values encode that same total order, so paging works
996
+ without the client restating the ordering.
997
+
948
998
  ## Cursor pagination
949
999
 
950
1000
  `OFFSET` pagination degrades linearly and shifts under concurrent writes. List queries also
@@ -1870,6 +1920,7 @@ that explains it, where there is one.
1870
1920
  | --- | --- | --- |
1871
1921
  | `mutations` | `true` | `false` omits the `Mutation` type entirely |
1872
1922
  | `features` | see [Choosing what gets generated](#choosing-what-gets-generated) | which operations are generated, per operation |
1923
+ | `exclude` | none | [tables and columns left out](#excluding-tables-and-columns) of the generated schema entirely |
1873
1924
  | `relationsDepthLimit` | unlimited | how deep relation fields are generated; `0` gives a flat, columns-only schema |
1874
1925
  | `prefixes` / `suffixes` / `typeNameMapper` | see [Naming](#naming) | operation and type names |
1875
1926
  | `scalars` / `mapColumnType` | built-in detection | [override a column's GraphQL type](#overriding-a-columns-scalar), by name or by rule |
@@ -1879,5 +1930,11 @@ that explains it, where there is one.
1879
1930
  | `conflictDoNothing` | `false` | PostgreSQL only — `ON CONFLICT DO NOTHING` on inserts, which makes `create<Table>Single` nullable |
1880
1931
  | `complexity` | on | [cost hints](#query-cost) in field extensions; `false` turns them off |
1881
1932
  | `transactions` | `'none'` | `'auto'` wraps a multi-mutation request in one [transaction](#transactions) |
1933
+ | `limits` | unbounded | [default and maximum page size](#bounding-page-size), globally or per table |
1934
+ | `defaults` | none | [per-table default `orderBy`](#default-ordering) for requests that omit one |
1935
+ | `scope` | none | [row-level predicate](#row-scoping-and-multi-tenancy) every read and write of a table is confined to |
1936
+ | `contextValues` | none | [columns the server stamps from context](#columns-the-server-owns) instead of accepting from the client |
1937
+ | `softDelete` | none | [tables that mark rows deleted](#soft-delete) instead of removing them |
1938
+ | `onWrite` | none | [hook that runs inside the mutation's own transaction](#write-hooks) |
1882
1939
  | `onError` | replaces driver errors | [error handling](#error-handling) hook — log, or surface a different error |
1883
1940
  | `eagerLoadRelations` | `true` | [which relations are pre-fetched](#overriding-a-relations-resolver-without-overfetching) with the parent query |
package/dist/README.md CHANGED
@@ -945,6 +945,56 @@ supplies no `orderBy`:
945
945
  An explicit `orderBy` always takes precedence, composite primary keys are ordered by every
946
946
  key column, and an unpaginated list query is left unordered so no sort is paid for.
947
947
 
948
+ ## Default ordering
949
+
950
+ A table usually has one ordering that is right nearly every time it is read — newest first,
951
+ priority first, name alphabetical. `defaults` names that ordering once, and every query that
952
+ does not ask for its own gets it:
953
+
954
+ ```ts
955
+ buildSchema(db, {
956
+ defaults: {
957
+ Todos: { orderBy: { priority: 'desc', createdAt: 'desc' } },
958
+ Users: { orderBy: { name: 'asc' } },
959
+ },
960
+ });
961
+ ```
962
+
963
+ ```graphql
964
+ # ordered by priority desc, then createdAt desc — nothing in the query says so
965
+ { todos { id title } }
966
+ ```
967
+
968
+ Keys are the table's key in your Drizzle schema and the column's property name, so a typo in
969
+ either fails at `buildSchema` time rather than silently doing nothing. Each column takes
970
+ `'asc'`, `'desc'`, or a `{ direction, priority? }` object mirroring the `orderBy` argument.
971
+ Columns sort highest `priority` first, and the shorthand leaves it unset, so the shorthand
972
+ falls back to the order the keys are written in — the object form is there for when you would
973
+ rather state the precedence than depend on that:
974
+
975
+ ```ts
976
+ defaults: {
977
+ Todos: { orderBy: { createdAt: { direction: 'desc', priority: 1 }, priority: { direction: 'desc', priority: 2 } } },
978
+ }
979
+ ```
980
+
981
+ It applies to list queries, `<tableName>Single` queries, and to-many relation fields on both
982
+ the eager and the lazy relation paths — a relation takes the default of the table it *reads*,
983
+ not its parent's. To-one relation fields are a single row and take no ordering.
984
+
985
+ Two details worth stating plainly:
986
+
987
+ - **Any `orderBy` in the request wins outright.** The default is a fallback for a missing
988
+ argument, not a base that client ordering is appended to. To ask for *no* ordering, pass
989
+ `orderBy: {}` — an empty object is still an argument, so it suppresses the default.
990
+ - **A default ordering makes an unpaginated list query pay for a sort.** That is the point,
991
+ but it is a cost a table with no `defaults` entry does not pay; a build with no `defaults`
992
+ behaves exactly as before.
993
+
994
+ Cursor pagination composes with it: a default-ordered page is ordered by those columns plus
995
+ the primary key tiebreak, and its `cursor` values encode that same total order, so paging works
996
+ without the client restating the ordering.
997
+
948
998
  ## Cursor pagination
949
999
 
950
1000
  `OFFSET` pagination degrades linearly and shifts under concurrent writes. List queries also
@@ -1870,6 +1920,7 @@ that explains it, where there is one.
1870
1920
  | --- | --- | --- |
1871
1921
  | `mutations` | `true` | `false` omits the `Mutation` type entirely |
1872
1922
  | `features` | see [Choosing what gets generated](#choosing-what-gets-generated) | which operations are generated, per operation |
1923
+ | `exclude` | none | [tables and columns left out](#excluding-tables-and-columns) of the generated schema entirely |
1873
1924
  | `relationsDepthLimit` | unlimited | how deep relation fields are generated; `0` gives a flat, columns-only schema |
1874
1925
  | `prefixes` / `suffixes` / `typeNameMapper` | see [Naming](#naming) | operation and type names |
1875
1926
  | `scalars` / `mapColumnType` | built-in detection | [override a column's GraphQL type](#overriding-a-columns-scalar), by name or by rule |
@@ -1879,5 +1930,11 @@ that explains it, where there is one.
1879
1930
  | `conflictDoNothing` | `false` | PostgreSQL only — `ON CONFLICT DO NOTHING` on inserts, which makes `create<Table>Single` nullable |
1880
1931
  | `complexity` | on | [cost hints](#query-cost) in field extensions; `false` turns them off |
1881
1932
  | `transactions` | `'none'` | `'auto'` wraps a multi-mutation request in one [transaction](#transactions) |
1933
+ | `limits` | unbounded | [default and maximum page size](#bounding-page-size), globally or per table |
1934
+ | `defaults` | none | [per-table default `orderBy`](#default-ordering) for requests that omit one |
1935
+ | `scope` | none | [row-level predicate](#row-scoping-and-multi-tenancy) every read and write of a table is confined to |
1936
+ | `contextValues` | none | [columns the server stamps from context](#columns-the-server-owns) instead of accepting from the client |
1937
+ | `softDelete` | none | [tables that mark rows deleted](#soft-delete) instead of removing them |
1938
+ | `onWrite` | none | [hook that runs inside the mutation's own transaction](#write-hooks) |
1882
1939
  | `onError` | replaces driver errors | [error handling](#error-handling) hook — log, or surface a different error |
1883
1940
  | `eagerLoadRelations` | `true` | [which relations are pre-fetched](#overriding-a-relations-resolver-without-overfetching) with the parent query |
package/dist/index.cjs CHANGED
@@ -464,6 +464,7 @@ var remapToGraphQLCore = (key, value, tableName, column, relationMap) => {
464
464
  return value;
465
465
  };
466
466
  var remapToGraphQLSingleOutput = (queryOutput, tableName, table, relationMap) => {
467
+ const columns = (0, import_drizzle_orm2.getTableColumns)(table);
467
468
  for (const [key, value] of Object.entries(queryOutput)) {
468
469
  if (value === void 0 || value === null) {
469
470
  const relEntry = value === null ? relationMap?.[tableName]?.[key] : void 0;
@@ -474,7 +475,7 @@ var remapToGraphQLSingleOutput = (queryOutput, tableName, table, relationMap) =>
474
475
  delete queryOutput[key];
475
476
  continue;
476
477
  }
477
- const column = table[key];
478
+ const column = columns[key];
478
479
  if (value === 0n && column && column.columnType === "SQLiteBigInt" && !column.notNull) {
479
480
  delete queryOutput[key];
480
481
  continue;
@@ -926,6 +927,7 @@ var resolveQueryExecutor = (db, context, tableName, buildTimeQueryBase) => {
926
927
  queryBase: buildTimeQueryBase ? executor?.query?.[tableName] ?? buildTimeQueryBase : buildTimeQueryBase
927
928
  };
928
929
  };
930
+ var DEFAULT_TRANSACTION_TIMEOUT_MS = 3e4;
929
931
  var createMutationTxCtx = (options) => options ? { timeoutMs: options.timeoutMs, fieldNames: /* @__PURE__ */ new Set(), states: /* @__PURE__ */ new WeakMap() } : void 0;
930
932
  var includedByDirectives = (node, variables) => {
931
933
  for (const directive of node.directives ?? []) {
@@ -1184,14 +1186,8 @@ var createRelationResolverFactory = (db, tables, nullOrdering, filterCtx, limits
1184
1186
  if (localValue == null) {
1185
1187
  return isOne ? null : [];
1186
1188
  }
1187
- const {
1188
- where: whereArg,
1189
- orderBy: orderByArg,
1190
- limit: requestedLimit,
1191
- offset,
1192
- after,
1193
- deleted
1194
- } = args ?? {};
1189
+ const { where: whereArg, limit: requestedLimit, offset, after, deleted } = args ?? {};
1190
+ const orderByArg = isOne ? args?.orderBy : withDefaultOrderBy(args ?? {}, targetTableName, policies?.defaultOrderBy).orderBy;
1195
1191
  const limit = applyLimitPolicy(requestedLimit, limitPolicy, `${tableName}.${relationName}`);
1196
1192
  const distinct = (args ?? {}).distinct?.length ? (args ?? {}).distinct : void 0;
1197
1193
  const cursorSelected = !isOne && !!info && selectsCursorField(info, targetTable);
@@ -1323,6 +1319,13 @@ var inputFieldDocs = (docs, column, tableName, columnName, fieldType) => {
1323
1319
  }
1324
1320
  return resolved;
1325
1321
  };
1322
+ var withDefaultOrderBy = (args, tableName, defaults) => {
1323
+ if (!defaults || args?.orderBy != null) {
1324
+ return args;
1325
+ }
1326
+ const fallback = defaults(tableName);
1327
+ return fallback ? { ...args, orderBy: fallback } : args;
1328
+ };
1326
1329
  var applyLimitPolicy = (limit, policy, fieldName) => {
1327
1330
  if (!policy) {
1328
1331
  return limit ?? void 0;
@@ -2789,11 +2792,12 @@ var withScope = (scope, tableName, table, condition, mode) => {
2789
2792
  const predicate = scope?.on(tableName, table, mode);
2790
2793
  return predicate ? (0, import_drizzle_orm4.and)(condition, predicate) : condition;
2791
2794
  };
2792
- var bindPolicies = (policies, filterCtx) => policies?.scope || policies?.contextValues || policies?.softDelete || policies?.onWrite ? {
2795
+ var bindPolicies = (policies, filterCtx) => policies?.scope || policies?.contextValues || policies?.softDelete || policies?.onWrite || policies?.defaultOrderBy ? {
2793
2796
  scope: policies.scope || policies.softDelete ? (context) => resolveScope(policies, context, filterCtx) : void 0,
2794
2797
  contextValues: policies.contextValues,
2795
2798
  softDelete: policies.softDelete,
2796
- onWrite: policies.onWrite
2799
+ onWrite: policies.onWrite,
2800
+ defaultOrderBy: policies.defaultOrderBy
2797
2801
  } : void 0;
2798
2802
  var applyContextValues = (values, hooks, context) => {
2799
2803
  if (!hooks) {
@@ -2822,7 +2826,7 @@ var stripContextValues = (values, hooks) => {
2822
2826
  }
2823
2827
  return values;
2824
2828
  };
2825
- var extractRelationsParamsInner = (relationMap, tables, tableName, typeName, originField, typeNameMapper, _isInitial = false, filterCtx, limits, scope) => {
2829
+ var extractRelationsParamsInner = (relationMap, tables, tableName, typeName, originField, typeNameMapper, _isInitial = false, filterCtx, limits, scope, defaultOrderBy) => {
2826
2830
  const relationsForTable = relationMap[tableName];
2827
2831
  if (!relationsForTable) {
2828
2832
  return void 0;
@@ -2864,7 +2868,7 @@ var extractRelationsParamsInner = (relationMap, tables, tableName, typeName, ori
2864
2868
  const thisRecord = {};
2865
2869
  thisRecord.columns = columns;
2866
2870
  const relationField = Object.values(baseField).find((e) => e.name === relName);
2867
- const relationArgs = relationField?.args;
2871
+ const relationArgs = (0, import_drizzle_orm4.is)(relEntry.relation, import_drizzle_orm4.One) ? relationField?.args : relationField && withDefaultOrderBy(relationField.args ?? {}, targetTableName, defaultOrderBy);
2868
2872
  const offset = relationArgs?.offset ?? void 0;
2869
2873
  const limit = (0, import_drizzle_orm4.is)(relEntry.relation, import_drizzle_orm4.One) ? relationArgs?.limit ?? void 0 : applyLimitPolicy(relationArgs?.limit, limits?.(targetTableName), `${tableName}.${relName}`);
2870
2874
  const relWhere = relationArgs?.where;
@@ -2893,14 +2897,15 @@ var extractRelationsParamsInner = (relationMap, tables, tableName, typeName, ori
2893
2897
  false,
2894
2898
  filterCtx,
2895
2899
  limits,
2896
- scope
2900
+ scope,
2901
+ defaultOrderBy
2897
2902
  ) : void 0;
2898
2903
  thisRecord.with = relWith;
2899
2904
  args[relName] = thisRecord;
2900
2905
  }
2901
2906
  return args;
2902
2907
  };
2903
- var extractRelationsParams = (relationMap, tables, tableName, info, typeName, typeNameMapper, filterCtx, limits, scope) => {
2908
+ var extractRelationsParams = (relationMap, tables, tableName, info, typeName, typeNameMapper, filterCtx, limits, scope, defaultOrderBy) => {
2904
2909
  if (!info) {
2905
2910
  return void 0;
2906
2911
  }
@@ -2914,7 +2919,8 @@ var extractRelationsParams = (relationMap, tables, tableName, info, typeName, ty
2914
2919
  true,
2915
2920
  filterCtx,
2916
2921
  limits,
2917
- scope
2922
+ scope,
2923
+ defaultOrderBy
2918
2924
  );
2919
2925
  };
2920
2926
  var pruneNonEagerRelations = (relationMap, shouldEagerLoad) => {
@@ -3325,7 +3331,8 @@ var prepareMutationRelationColumns = (params) => {
3325
3331
  typeNameMapper,
3326
3332
  void 0,
3327
3333
  params.limits,
3328
- params.scope
3334
+ params.scope,
3335
+ params.defaultOrderBy
3329
3336
  ) : void 0;
3330
3337
  const hasRelations = !!(withParams && Object.keys(withParams).length);
3331
3338
  const baseColumns = extractSelectedColumnsFromTreeSQLFormat(parsedInfo.fieldsByTypeName[typeName], table, {
@@ -3667,7 +3674,8 @@ var runRelationalSelect = async (opts) => {
3667
3674
  typeNameMapper,
3668
3675
  filterCtx,
3669
3676
  opts.limits,
3670
- scope
3677
+ scope,
3678
+ opts.defaultOrderBy
3671
3679
  ) : void 0
3672
3680
  };
3673
3681
  if (single) {
@@ -3921,7 +3929,7 @@ var parseAggregateRequest = (info, target, rootTypeName = `${target.typeName}Agg
3921
3929
  for (const field of Object.values(selectionTree)) {
3922
3930
  if (field.name === "count") {
3923
3931
  request.count = true;
3924
- request.selection.count = (0, import_drizzle_orm5.count)();
3932
+ request.selection["count"] = (0, import_drizzle_orm5.count)();
3925
3933
  continue;
3926
3934
  }
3927
3935
  if (!AGGREGATE_OPS.includes(field.name)) {
@@ -3947,7 +3955,7 @@ var parseAggregateRequest = (info, target, rootTypeName = `${target.typeName}Agg
3947
3955
  var assembleAggregateRow = (row, request, target) => {
3948
3956
  const result = {};
3949
3957
  if (request.count) {
3950
- result.count = row.count == null ? 0 : Number(row.count);
3958
+ result["count"] = row["count"] == null ? 0 : Number(row["count"]);
3951
3959
  }
3952
3960
  for (const op of AGGREGATE_OPS) {
3953
3961
  if (!request.ops[op].length) {
@@ -4273,7 +4281,8 @@ var generateSelectArray = (db, tableName, tables, relationMap, orderArgs, filter
4273
4281
  );
4274
4282
  return {
4275
4283
  name: fieldName,
4276
- resolver: async (_source, args, context, info) => {
4284
+ resolver: async (_source, rawArgs, context, info) => {
4285
+ const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);
4277
4286
  try {
4278
4287
  const parsedInfo = (0, import_graphql_parse_resolve_info2.parseResolveInfo)(info, { deep: true });
4279
4288
  const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);
@@ -4291,6 +4300,7 @@ var generateSelectArray = (db, tableName, tables, relationMap, orderArgs, filter
4291
4300
  single: false,
4292
4301
  filterCtx,
4293
4302
  limits,
4303
+ defaultOrderBy: policies?.defaultOrderBy,
4294
4304
  scope: policies?.scope?.(context),
4295
4305
  pkNames,
4296
4306
  db: executor,
@@ -4316,7 +4326,8 @@ var generateSelectSingle = (db, tableName, tables, relationMap, orderArgs, filte
4316
4326
  const pkNames = mysqlPrimaryKeyPropNames(table);
4317
4327
  return {
4318
4328
  name: fieldName,
4319
- resolver: async (_source, args, context, info) => {
4329
+ resolver: async (_source, rawArgs, context, info) => {
4330
+ const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);
4320
4331
  try {
4321
4332
  const parsedInfo = (0, import_graphql_parse_resolve_info2.parseResolveInfo)(info, { deep: true });
4322
4333
  const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);
@@ -4333,6 +4344,7 @@ var generateSelectSingle = (db, tableName, tables, relationMap, orderArgs, filte
4333
4344
  single: true,
4334
4345
  filterCtx,
4335
4346
  limits,
4347
+ defaultOrderBy: policies?.defaultOrderBy,
4336
4348
  scope: policies?.scope?.(context),
4337
4349
  pkNames,
4338
4350
  db: executor
@@ -4840,7 +4852,7 @@ var generateSchemaData = (db, schema, relations, options) => {
4840
4852
  const inputs = {};
4841
4853
  const outputs = {};
4842
4854
  if (["insert", "upsert", "update", "delete"].some((feature) => anyTable(feature))) {
4843
- outputs.MutationReturn = mutationReturnType;
4855
+ outputs["MutationReturn"] = mutationReturnType;
4844
4856
  }
4845
4857
  for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {
4846
4858
  const tableFeatures = featureOf(tableName);
@@ -5741,7 +5753,8 @@ var generateSelectArray2 = (db, tableName, tables, relationMap, orderArgs, filte
5741
5753
  );
5742
5754
  return {
5743
5755
  name: fieldName,
5744
- resolver: async (_source, args, context, info) => {
5756
+ resolver: async (_source, rawArgs, context, info) => {
5757
+ const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);
5745
5758
  try {
5746
5759
  const parsedInfo = (0, import_graphql_parse_resolve_info3.parseResolveInfo)(info, { deep: true });
5747
5760
  const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);
@@ -5762,6 +5775,7 @@ var generateSelectArray2 = (db, tableName, tables, relationMap, orderArgs, filte
5762
5775
  single: false,
5763
5776
  filterCtx,
5764
5777
  limits,
5778
+ defaultOrderBy: policies?.defaultOrderBy,
5765
5779
  pkNames,
5766
5780
  db: executor,
5767
5781
  scope,
@@ -5871,7 +5885,8 @@ var generateSelectSingle2 = (db, tableName, tables, relationMap, orderArgs, filt
5871
5885
  const pkNames = pgPrimaryKeyPropNames(table);
5872
5886
  return {
5873
5887
  name: fieldName,
5874
- resolver: async (_source, args, context, info) => {
5888
+ resolver: async (_source, rawArgs, context, info) => {
5889
+ const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);
5875
5890
  try {
5876
5891
  const parsedInfo = (0, import_graphql_parse_resolve_info3.parseResolveInfo)(info, { deep: true });
5877
5892
  const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);
@@ -5890,6 +5905,7 @@ var generateSelectSingle2 = (db, tableName, tables, relationMap, orderArgs, filt
5890
5905
  single: true,
5891
5906
  filterCtx,
5892
5907
  limits,
5908
+ defaultOrderBy: policies?.defaultOrderBy,
5893
5909
  pkNames,
5894
5910
  db: executor,
5895
5911
  scope
@@ -5983,7 +5999,8 @@ var generateInsertArray2 = (db, tableName, table, tables, relationMap, baseType,
5983
5999
  pkNames,
5984
6000
  parsedInfo,
5985
6001
  limits,
5986
- scope
6002
+ scope,
6003
+ defaultOrderBy: policies?.defaultOrderBy
5987
6004
  });
5988
6005
  const returning = nestedEntries ? nested.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table) : columns;
5989
6006
  const runInsert = async (target, values) => {
@@ -6073,7 +6090,8 @@ var generateInsertSingle2 = (db, tableName, table, tables, relationMap, baseType
6073
6090
  pkNames,
6074
6091
  parsedInfo,
6075
6092
  limits,
6076
- scope
6093
+ scope,
6094
+ defaultOrderBy: policies?.defaultOrderBy
6077
6095
  });
6078
6096
  const returning = nestedEntry ? nested.withJoinColumns(tableName, nestedEntry.ops, { ...columns }, table) : columns;
6079
6097
  const runInsert = async (target, values) => {
@@ -6175,7 +6193,8 @@ var generateUpsert2 = (db, tableName, table, tables, relationMap, baseType, onCo
6175
6193
  pkNames,
6176
6194
  parsedInfo,
6177
6195
  limits,
6178
- scope
6196
+ scope,
6197
+ defaultOrderBy: policies?.defaultOrderBy
6179
6198
  });
6180
6199
  const returning = nestedEntries ? nested.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table) : columns;
6181
6200
  const runUpsert = async (target, values) => {
@@ -6273,7 +6292,8 @@ var generateUpdate2 = (db, tableName, table, tables, relationMap, setArgs, filte
6273
6292
  pkNames,
6274
6293
  parsedInfo,
6275
6294
  limits,
6276
- scope
6295
+ scope,
6296
+ defaultOrderBy: policies?.defaultOrderBy
6277
6297
  });
6278
6298
  const entry = nested?.enabled(tableName) ? nested.split(tableName, set) : void 0;
6279
6299
  const nestedOps = entry && nested.hasOps(entry.ops) ? entry.ops : void 0;
@@ -6387,7 +6407,8 @@ var generateUpdateMany2 = (db, tableName, table, tables, relationMap, updateMany
6387
6407
  pkNames,
6388
6408
  parsedInfo,
6389
6409
  limits,
6390
- scope
6410
+ scope,
6411
+ defaultOrderBy: policies?.defaultOrderBy
6391
6412
  });
6392
6413
  const entries = updates.map(({ where, set }) => {
6393
6414
  const split = nested?.enabled(tableName) ? nested.split(tableName, set) : void 0;
@@ -6582,7 +6603,7 @@ function generateSchemaData2(db, schema, relations, options) {
6582
6603
  for (const excluded of excludedTables) {
6583
6604
  delete namedRelations[excluded];
6584
6605
  }
6585
- attachTargetPrimaryKeys(namedRelations, tables, pgPrimaryKeyPropNames);
6606
+ attachTargetPrimaryKeys(namedRelations, tables, (table) => pgPrimaryKeyPropNames(table));
6586
6607
  const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);
6587
6608
  const filterCtx = { tables, relationMap: namedRelations };
6588
6609
  const tablePolicies = options.policies;
@@ -7191,7 +7212,8 @@ var generateSelectArray3 = (db, tableName, tables, relationMap, orderArgs, filte
7191
7212
  );
7192
7213
  return {
7193
7214
  name: fieldName,
7194
- resolver: async (_source, args, context, info) => {
7215
+ resolver: async (_source, rawArgs, context, info) => {
7216
+ const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);
7195
7217
  try {
7196
7218
  const parsedInfo = (0, import_graphql_parse_resolve_info4.parseResolveInfo)(info, { deep: true });
7197
7219
  const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);
@@ -7209,6 +7231,7 @@ var generateSelectArray3 = (db, tableName, tables, relationMap, orderArgs, filte
7209
7231
  single: false,
7210
7232
  filterCtx,
7211
7233
  limits,
7234
+ defaultOrderBy: policies?.defaultOrderBy,
7212
7235
  pkNames,
7213
7236
  db: executor,
7214
7237
  scope: policies?.scope?.(context),
@@ -7234,7 +7257,8 @@ var generateSelectSingle3 = (db, tableName, tables, relationMap, orderArgs, filt
7234
7257
  const pkNames = sqlitePrimaryKeyPropNames(table);
7235
7258
  return {
7236
7259
  name: fieldName,
7237
- resolver: async (_source, args, context, info) => {
7260
+ resolver: async (_source, rawArgs, context, info) => {
7261
+ const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);
7238
7262
  try {
7239
7263
  const parsedInfo = (0, import_graphql_parse_resolve_info4.parseResolveInfo)(info, { deep: true });
7240
7264
  const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);
@@ -7251,6 +7275,7 @@ var generateSelectSingle3 = (db, tableName, tables, relationMap, orderArgs, filt
7251
7275
  single: true,
7252
7276
  filterCtx,
7253
7277
  limits,
7278
+ defaultOrderBy: policies?.defaultOrderBy,
7254
7279
  pkNames,
7255
7280
  db: executor,
7256
7281
  scope: policies?.scope?.(context)
@@ -7315,7 +7340,8 @@ var generateInsertArray3 = (db, tableName, table, tables, relationMap, baseType,
7315
7340
  pkNames,
7316
7341
  parsedInfo,
7317
7342
  limits,
7318
- scope
7343
+ scope,
7344
+ defaultOrderBy: policies?.defaultOrderBy
7319
7345
  });
7320
7346
  const returning = nestedEntries ? nested.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table) : columns;
7321
7347
  const runInsert = async (target, values) => {
@@ -7405,7 +7431,8 @@ var generateInsertSingle3 = (db, tableName, table, tables, relationMap, baseType
7405
7431
  pkNames,
7406
7432
  parsedInfo,
7407
7433
  limits,
7408
- scope
7434
+ scope,
7435
+ defaultOrderBy: policies?.defaultOrderBy
7409
7436
  });
7410
7437
  const returning = nestedEntry ? nested.withJoinColumns(tableName, nestedEntry.ops, { ...columns }, table) : columns;
7411
7438
  const runInsert = async (target, values) => {
@@ -7507,7 +7534,8 @@ var generateUpsert3 = (db, tableName, table, tables, relationMap, baseType, onCo
7507
7534
  pkNames,
7508
7535
  parsedInfo,
7509
7536
  limits,
7510
- scope
7537
+ scope,
7538
+ defaultOrderBy: policies?.defaultOrderBy
7511
7539
  });
7512
7540
  const returning = nestedEntries ? nested.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table) : columns;
7513
7541
  const runUpsert = async (target, values) => {
@@ -7605,7 +7633,8 @@ var generateUpdate3 = (db, tableName, table, tables, relationMap, setArgs, filte
7605
7633
  pkNames,
7606
7634
  parsedInfo,
7607
7635
  limits,
7608
- scope
7636
+ scope,
7637
+ defaultOrderBy: policies?.defaultOrderBy
7609
7638
  });
7610
7639
  const entry = nested?.enabled(tableName) ? nested.split(tableName, set) : void 0;
7611
7640
  const nestedOps = entry && nested.hasOps(entry.ops) ? entry.ops : void 0;
@@ -7719,7 +7748,8 @@ var generateUpdateMany3 = (db, tableName, table, tables, relationMap, updateMany
7719
7748
  pkNames,
7720
7749
  parsedInfo,
7721
7750
  limits,
7722
- scope
7751
+ scope,
7752
+ defaultOrderBy: policies?.defaultOrderBy
7723
7753
  });
7724
7754
  const entries = updates.map(({ where, set }) => {
7725
7755
  const split = nested?.enabled(tableName) ? nested.split(tableName, set) : void 0;
@@ -8706,7 +8736,9 @@ var buildSchema = (db, config) => {
8706
8736
  aggregateCost: (complexityConfig === true ? void 0 : complexityConfig.aggregateCost) ?? 10
8707
8737
  };
8708
8738
  const transactionsOpt = config?.transactions;
8709
- const transactions = transactionsOpt === void 0 || transactionsOpt === "none" ? void 0 : { timeoutMs: (transactionsOpt === "auto" ? void 0 : transactionsOpt.timeoutMs) ?? 3e4 };
8739
+ const transactions = transactionsOpt === void 0 || transactionsOpt === "none" ? void 0 : {
8740
+ timeoutMs: (transactionsOpt === "auto" ? void 0 : transactionsOpt.timeoutMs) ?? DEFAULT_TRANSACTION_TIMEOUT_MS
8741
+ };
8710
8742
  const limitsConfig = config?.limits;
8711
8743
  if (limitsConfig) {
8712
8744
  const check = (policy, where) => {
@@ -8734,6 +8766,46 @@ var buildSchema = (db, config) => {
8734
8766
  limitPolicyCache.set(tableName, resolved);
8735
8767
  return resolved;
8736
8768
  } : void 0;
8769
+ const defaultsConfig = config?.defaults;
8770
+ const defaultOrderByByTable = /* @__PURE__ */ new Map();
8771
+ if (defaultsConfig) {
8772
+ const defaultsTableNames = new Set(tableKeys);
8773
+ for (const [tableName, tableDefaults] of Object.entries(defaultsConfig)) {
8774
+ if (!defaultsTableNames.has(tableName)) {
8775
+ throw new Error(
8776
+ `Drizzle-GraphQL Error: config.defaults names '${tableName}', which is not a table in the Drizzle schema.`
8777
+ );
8778
+ }
8779
+ const orderBy = tableDefaults?.orderBy;
8780
+ if (!orderBy || !Object.keys(orderBy).length) {
8781
+ continue;
8782
+ }
8783
+ const columns = (0, import_drizzle_orm11.getColumns)(schema[tableName]);
8784
+ const normalized = {};
8785
+ for (const [columnName, entry] of Object.entries(orderBy)) {
8786
+ if (!columns[columnName]) {
8787
+ throw new Error(
8788
+ `Drizzle-GraphQL Error: config.defaults.${tableName}.orderBy names '${columnName}', which is not a column of '${tableName}'.`
8789
+ );
8790
+ }
8791
+ const direction = typeof entry === "string" ? entry : entry?.direction;
8792
+ if (direction !== "asc" && direction !== "desc") {
8793
+ throw new Error(
8794
+ `Drizzle-GraphQL Error: config.defaults.${tableName}.orderBy.${columnName} must be 'asc', 'desc', or { direction, priority? }.`
8795
+ );
8796
+ }
8797
+ const priority = typeof entry === "string" ? void 0 : entry?.priority;
8798
+ if (priority !== void 0 && !Number.isInteger(priority)) {
8799
+ throw new Error(
8800
+ `Drizzle-GraphQL Error: config.defaults.${tableName}.orderBy.${columnName}.priority must be an integer.`
8801
+ );
8802
+ }
8803
+ normalized[columnName] = priority === void 0 ? { direction } : { direction, priority };
8804
+ }
8805
+ defaultOrderByByTable.set(tableName, normalized);
8806
+ }
8807
+ }
8808
+ const defaultOrderBy = defaultOrderByByTable.size ? (tableName) => defaultOrderByByTable.get(tableName) : void 0;
8737
8809
  const scopeConfig = config?.scope;
8738
8810
  const contextValuesConfig = config?.contextValues;
8739
8811
  if (scopeConfig || contextValuesConfig) {
@@ -8814,11 +8886,12 @@ var buildSchema = (db, config) => {
8814
8886
  }
8815
8887
  }
8816
8888
  const onWrite = globalWriteHooks || writeHooks.size ? (tableName) => globalWriteHooks ?? writeHooks.get(tableName) : void 0;
8817
- const policies = scopeConfig || contextValuesConfig || softDeleteInfos.size || onWrite ? {
8889
+ const policies = scopeConfig || contextValuesConfig || softDeleteInfos.size || onWrite || defaultOrderBy ? {
8818
8890
  scope: scopeConfig ? (tableName) => scopeConfig[tableName] : void 0,
8819
8891
  contextValues: contextValuesConfig ? (tableName) => contextValuesConfig[tableName] : void 0,
8820
8892
  softDelete: softDeleteInfos.size ? (tableName) => softDeleteInfos.get(tableName) : void 0,
8821
- onWrite
8893
+ onWrite,
8894
+ defaultOrderBy
8822
8895
  } : void 0;
8823
8896
  const exclude = config?.exclude;
8824
8897
  if (exclude) {