prisma-sql 1.5.0 → 1.6.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/generator.js CHANGED
@@ -1,10 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { generatorHandler } from '@prisma/generator-helper';
3
- import { convertDMMFToModels, processAllDirectives, isDynamicParameter, extractDynamicName } from '@dee-wan/schema-parser';
4
- import { mkdir, writeFile } from 'fs/promises';
5
- import { join } from 'path';
6
- import { logger } from '@prisma/internals';
7
-
2
+ #!/usr/bin/env node
3
+ "use strict";
8
4
  var __defProp = Object.defineProperty;
9
5
  var __defProps = Object.defineProperties;
10
6
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
@@ -51,10 +47,10 @@ var __async = (__this, __arguments, generator) => {
51
47
 
52
48
  // package.json
53
49
  var require_package = __commonJS({
54
- "package.json"(exports$1, module) {
55
- module.exports = {
50
+ "package.json"(exports2, module2) {
51
+ module2.exports = {
56
52
  name: "prisma-sql",
57
- version: "1.5.0",
53
+ version: "1.6.0",
58
54
  description: "Convert Prisma queries to optimized SQL with type safety. 2-7x faster than Prisma Client.",
59
55
  main: "dist/index.cjs",
60
56
  module: "dist/index.js",
@@ -149,6 +145,14 @@ var require_package = __commonJS({
149
145
  }
150
146
  });
151
147
 
148
+ // src/generator.ts
149
+ var import_generator_helper = require("@prisma/generator-helper");
150
+
151
+ // src/code-emitter.ts
152
+ var import_schema_parser11 = require("@dee-wan/schema-parser");
153
+ var import_promises = require("fs/promises");
154
+ var import_path = require("path");
155
+
152
156
  // src/sql-builder-dialect.ts
153
157
  var globalDialect = "postgres";
154
158
  function setGlobalDialect(dialect) {
@@ -464,6 +468,7 @@ var Wildcards = Object.freeze({
464
468
  [Ops.ENDS_WITH]: (v) => `%${v}`
465
469
  });
466
470
  var REGEX_CACHE = {
471
+ PARAM_PLACEHOLDER: /\$(\d+)/g,
467
472
  VALID_IDENTIFIER: /^[a-z_][a-z0-9_]*$/
468
473
  };
469
474
  var LIMITS = Object.freeze({
@@ -768,7 +773,7 @@ function validateMappingsAgainstPlaceholders(mappings, placeholders, max, dialec
768
773
  const mappingIndices = /* @__PURE__ */ new Set();
769
774
  for (const mapping of mappings) {
770
775
  validateMappingIndex(mapping, max);
771
- ensureUniqueMappingIndex(mappingIndices, mapping.index);
776
+ ensureUniqueMappingIndex(mappingIndices, mapping.index, dialect);
772
777
  ensureMappingIndexExistsInSql(placeholders, mapping.index);
773
778
  validateMappingValueShape(mapping);
774
779
  }
@@ -958,6 +963,9 @@ function joinCondition(field, parentAlias, childAlias) {
958
963
  function getModelByName(schemas, name) {
959
964
  return schemas.find((m) => m.name === name);
960
965
  }
966
+
967
+ // src/builder/where/operators-scalar.ts
968
+ var import_schema_parser = require("@dee-wan/schema-parser");
961
969
  function buildNotComposite(expr, val, params, dialect, buildOp, separator) {
962
970
  const entries = Object.entries(val).filter(
963
971
  ([k, v]) => k !== "mode" && v !== void 0
@@ -986,7 +994,7 @@ function buildScalarOperator(expr, op, val, params, mode, fieldType, dialect) {
986
994
  }
987
995
  if (op === Ops.EQUALS && mode === Modes.INSENSITIVE && isNotNullish(dialect)) {
988
996
  const placeholder = params.addAuto(val);
989
- return caseInsensitiveEquals(expr, placeholder);
997
+ return caseInsensitiveEquals(expr, placeholder, dialect);
990
998
  }
991
999
  const STRING_LIKE_OPS = /* @__PURE__ */ new Set([
992
1000
  Ops.CONTAINS,
@@ -1057,7 +1065,7 @@ function buildDynamicLikePattern(op, placeholder, dialect) {
1057
1065
  }
1058
1066
  function handleLikeOperator(expr, op, val, params, mode, dialect) {
1059
1067
  if (val === void 0) return "";
1060
- if (isDynamicParameter(val)) {
1068
+ if ((0, import_schema_parser.isDynamicParameter)(val)) {
1061
1069
  const placeholder2 = params.addAuto(val);
1062
1070
  const patternExpr = buildDynamicLikePattern(op, placeholder2, dialect);
1063
1071
  if (mode === Modes.INSENSITIVE) {
@@ -1073,7 +1081,7 @@ function handleLikeOperator(expr, op, val, params, mode, dialect) {
1073
1081
  }
1074
1082
  function handleInOperator(expr, op, val, params, dialect) {
1075
1083
  if (val === void 0) return "";
1076
- if (isDynamicParameter(val)) {
1084
+ if ((0, import_schema_parser.isDynamicParameter)(val)) {
1077
1085
  const placeholder2 = params.addAuto(val);
1078
1086
  return op === Ops.IN ? inArray(expr, placeholder2, dialect) : notInArray(expr, placeholder2, dialect);
1079
1087
  }
@@ -1106,8 +1114,11 @@ function handleComparisonOperator(expr, op, val, params) {
1106
1114
  const placeholder = params.addAuto(val);
1107
1115
  return `${expr} ${sqlOp} ${placeholder}`;
1108
1116
  }
1117
+
1118
+ // src/builder/where/operators-array.ts
1119
+ var import_schema_parser2 = require("@dee-wan/schema-parser");
1109
1120
  function buildArrayParam(val, params, dialect) {
1110
- if (isDynamicParameter(val)) {
1121
+ if ((0, import_schema_parser2.isDynamicParameter)(val)) {
1111
1122
  return params.addAuto(val);
1112
1123
  }
1113
1124
  if (!Array.isArray(val)) {
@@ -1181,7 +1192,7 @@ function handleArrayHas(expr, val, params, cast, dialect) {
1181
1192
  value: val
1182
1193
  });
1183
1194
  }
1184
- if (!isDynamicParameter(val) && Array.isArray(val)) {
1195
+ if (!(0, import_schema_parser2.isDynamicParameter)(val) && Array.isArray(val)) {
1185
1196
  throw createError(`has requires scalar value (single element), not array`, {
1186
1197
  operator: Ops.HAS,
1187
1198
  value: val
@@ -1198,7 +1209,7 @@ function handleArrayHas(expr, val, params, cast, dialect) {
1198
1209
  }
1199
1210
  function handleArrayHasSome(expr, val, params, cast, dialect) {
1200
1211
  if (val === void 0) return "";
1201
- if (isDynamicParameter(val)) {
1212
+ if ((0, import_schema_parser2.isDynamicParameter)(val)) {
1202
1213
  const placeholder2 = params.addAuto(val);
1203
1214
  return arrayOverlaps(expr, placeholder2, cast, dialect);
1204
1215
  }
@@ -1870,6 +1881,9 @@ function createAliasGenerator(maxAliases = 1e4) {
1870
1881
  }
1871
1882
  };
1872
1883
  }
1884
+
1885
+ // src/builder/shared/param-store.ts
1886
+ var import_schema_parser3 = require("@dee-wan/schema-parser");
1873
1887
  var MAX_PARAM_INDEX = Number.MAX_SAFE_INTEGER - 1e3;
1874
1888
  function assertSameLength(params, mappings) {
1875
1889
  if (params.length !== mappings.length) {
@@ -2000,8 +2014,8 @@ function createStoreInternal(startIndex, initialParams = [], initialMappings = [
2000
2014
  return dynamicName === void 0 ? addStatic(value) : addDynamic(dynamicName);
2001
2015
  }
2002
2016
  function addAuto(value) {
2003
- if (isDynamicParameter(value)) {
2004
- const dynamicName = extractDynamicName(value);
2017
+ if ((0, import_schema_parser3.isDynamicParameter)(value)) {
2018
+ const dynamicName = (0, import_schema_parser3.extractDynamicName)(value);
2005
2019
  return add(void 0, dynamicName);
2006
2020
  }
2007
2021
  return add(value);
@@ -2090,10 +2104,13 @@ function buildWhereClause(where, options) {
2090
2104
  }
2091
2105
  return publicResult;
2092
2106
  }
2107
+
2108
+ // src/builder/shared/int-like.ts
2109
+ var import_schema_parser4 = require("@dee-wan/schema-parser");
2093
2110
  function normalizeIntLike(name, v, opts = {}) {
2094
2111
  var _a, _b;
2095
2112
  if (!isNotNullish(v)) return void 0;
2096
- if (isDynamicParameter(v)) return v;
2113
+ if ((0, import_schema_parser4.isDynamicParameter)(v)) return v;
2097
2114
  if (typeof v !== "number" || !Number.isFinite(v) || !Number.isInteger(v)) {
2098
2115
  throw new Error(`${name} must be an integer`);
2099
2116
  }
@@ -2110,6 +2127,9 @@ function normalizeIntLike(name, v, opts = {}) {
2110
2127
  }
2111
2128
  return v;
2112
2129
  }
2130
+
2131
+ // src/builder/shared/dynamic-params.ts
2132
+ var import_schema_parser5 = require("@dee-wan/schema-parser");
2113
2133
  function scopeName(scope, dynamicName) {
2114
2134
  const s = String(scope).trim();
2115
2135
  const dn = String(dynamicName).trim();
@@ -2117,13 +2137,16 @@ function scopeName(scope, dynamicName) {
2117
2137
  return `${s}:${dn}`;
2118
2138
  }
2119
2139
  function addAutoScoped(params, value, scope) {
2120
- if (isDynamicParameter(value)) {
2121
- const dn = extractDynamicName(value);
2140
+ if ((0, import_schema_parser5.isDynamicParameter)(value)) {
2141
+ const dn = (0, import_schema_parser5.extractDynamicName)(value);
2122
2142
  return params.add(void 0, scopeName(scope, dn));
2123
2143
  }
2124
2144
  return params.add(value);
2125
2145
  }
2126
2146
 
2147
+ // src/builder/pagination.ts
2148
+ var import_schema_parser6 = require("@dee-wan/schema-parser");
2149
+
2127
2150
  // src/builder/shared/order-by-utils.ts
2128
2151
  var flipNulls = (v) => {
2129
2152
  const s = String(v).toLowerCase();
@@ -2259,7 +2282,7 @@ function normalizeFiniteInteger(name, v) {
2259
2282
  return v;
2260
2283
  }
2261
2284
  function normalizeNonNegativeInt(name, v) {
2262
- if (isDynamicParameter(v)) return v;
2285
+ if ((0, import_schema_parser6.isDynamicParameter)(v)) return v;
2263
2286
  const n = normalizeFiniteInteger(name, v);
2264
2287
  if (n < 0) {
2265
2288
  throw new Error(`${name} must be >= 0`);
@@ -2273,7 +2296,7 @@ function hasNonNullishProp(v, key) {
2273
2296
  return isPlainObject(v) && key in v && isNotNullish(v[key]);
2274
2297
  }
2275
2298
  function normalizeIntegerOrDynamic(name, v) {
2276
- if (isDynamicParameter(v)) return v;
2299
+ if ((0, import_schema_parser6.isDynamicParameter)(v)) return v;
2277
2300
  return normalizeFiniteInteger(name, v);
2278
2301
  }
2279
2302
  function readSkipTake(relArgs) {
@@ -2506,6 +2529,9 @@ function getPaginationParams(method, args) {
2506
2529
  return {};
2507
2530
  }
2508
2531
 
2532
+ // src/builder/select/assembly.ts
2533
+ var import_schema_parser7 = require("@dee-wan/schema-parser");
2534
+
2509
2535
  // src/builder/select/fields.ts
2510
2536
  function toSelectEntries(select) {
2511
2537
  const out = [];
@@ -3341,7 +3367,7 @@ function appendPagination(sql, spec) {
3341
3367
  const isFindUniqueOrFirst = method === "findUnique" || method === "findFirst";
3342
3368
  if (isFindUniqueOrFirst) {
3343
3369
  const parts2 = [sql, SQL_TEMPLATES.LIMIT, "1"];
3344
- const hasSkip = isNotNullish(pagination.skip) && (isDynamicParameter(pagination.skip) || typeof pagination.skip === "number" && pagination.skip > 0) && method === "findFirst";
3370
+ const hasSkip = isNotNullish(pagination.skip) && ((0, import_schema_parser7.isDynamicParameter)(pagination.skip) || typeof pagination.skip === "number" && pagination.skip > 0) && method === "findFirst";
3345
3371
  if (hasSkip) {
3346
3372
  const placeholder = addAutoScoped(
3347
3373
  params,
@@ -3574,7 +3600,7 @@ function normalizeArgsForNegativeTake(method, args) {
3574
3600
  }
3575
3601
  function normalizeArgsForDialect(dialect, args, model) {
3576
3602
  if (dialect !== "postgres") return args;
3577
- return applyPostgresDistinctOrderBy(args);
3603
+ return applyPostgresDistinctOrderBy(args, model);
3578
3604
  }
3579
3605
  function buildCursorClauseIfAny(input) {
3580
3606
  const { cursor, orderBy, tableName, alias, params, dialect } = input;
@@ -3653,7 +3679,9 @@ function buildSelectSql(input) {
3653
3679
  const argsForSql = normalizeArgsForNegativeTake(method, args);
3654
3680
  const normalizedArgs = normalizeArgsForDialect(
3655
3681
  dialectToUse,
3656
- argsForSql);
3682
+ argsForSql,
3683
+ model
3684
+ );
3657
3685
  validateDistinct(model, normalizedArgs.distinct);
3658
3686
  validateOrderBy(model, normalizedArgs.orderBy);
3659
3687
  validateCursor(model, normalizedArgs.cursor);
@@ -3669,6 +3697,9 @@ function buildSelectSql(input) {
3669
3697
  });
3670
3698
  return constructFinalSql(spec);
3671
3699
  }
3700
+
3701
+ // src/builder/aggregates.ts
3702
+ var import_schema_parser8 = require("@dee-wan/schema-parser");
3672
3703
  var MODEL_FIELD_CACHE = /* @__PURE__ */ new WeakMap();
3673
3704
  var NUMERIC_TYPES = /* @__PURE__ */ new Set(["Int", "Float", "Decimal", "BigInt"]);
3674
3705
  var AGGREGATES = [
@@ -3763,7 +3794,7 @@ function buildNullComparison(expr, op) {
3763
3794
  throw new Error(`Operator '${op}' doesn't support null in HAVING`);
3764
3795
  }
3765
3796
  function buildInComparison(expr, op, val, params, dialect) {
3766
- if (isDynamicParameter(val)) {
3797
+ if ((0, import_schema_parser8.isDynamicParameter)(val)) {
3767
3798
  const placeholder2 = addHavingParam(params, op, val);
3768
3799
  return op === Ops.IN ? inArray(expr, placeholder2, dialect) : notInArray(expr, placeholder2, dialect);
3769
3800
  }
@@ -4088,7 +4119,7 @@ function buildGroupBySql(args, whereResult, tableName, alias, model, dialect) {
4088
4119
  assertSafeAlias(alias);
4089
4120
  assertSafeTableRef(tableName);
4090
4121
  const byFields = assertGroupByBy(args, model);
4091
- const d = getGlobalDialect();
4122
+ const d = dialect != null ? dialect : getGlobalDialect();
4092
4123
  const params = createParamStore(whereResult.nextParamIndex);
4093
4124
  const { groupFields, selectFields } = buildGroupBySelectParts(
4094
4125
  args,
@@ -4124,7 +4155,7 @@ function buildGroupBySql(args, whereResult, tableName, alias, model, dialect) {
4124
4155
  function buildCountSql(whereResult, tableName, alias, skip, dialect) {
4125
4156
  assertSafeAlias(alias);
4126
4157
  assertSafeTableRef(tableName);
4127
- const d = getGlobalDialect();
4158
+ const d = dialect != null ? dialect : getGlobalDialect();
4128
4159
  const whereClause = isValidWhereClause(whereResult.clause) ? `${SQL_TEMPLATES.WHERE} ${whereResult.clause}` : "";
4129
4160
  const params = createParamStore(whereResult.nextParamIndex);
4130
4161
  const baseSubSelect = [
@@ -4161,7 +4192,7 @@ function buildCountSql(whereResult, tableName, alias, skip, dialect) {
4161
4192
  });
4162
4193
  }
4163
4194
  function applyCountSkip(subSelect, normalizedSkip, params, dialect) {
4164
- const shouldApply = isDynamicParameter(normalizedSkip) || typeof normalizedSkip === "number" && normalizedSkip > 0;
4195
+ const shouldApply = (0, import_schema_parser8.isDynamicParameter)(normalizedSkip) || typeof normalizedSkip === "number" && normalizedSkip > 0;
4165
4196
  if (!shouldApply) return subSelect;
4166
4197
  const placeholder = addAutoScoped(params, normalizedSkip, "count.skip");
4167
4198
  if (dialect === "sqlite") {
@@ -4169,6 +4200,9 @@ function applyCountSkip(subSelect, normalizedSkip, params, dialect) {
4169
4200
  }
4170
4201
  return `${subSelect} ${SQL_TEMPLATES.OFFSET} ${placeholder}`;
4171
4202
  }
4203
+
4204
+ // src/sql-generator.ts
4205
+ var import_schema_parser9 = require("@dee-wan/schema-parser");
4172
4206
  function safeAlias(input) {
4173
4207
  const raw = String(input).toLowerCase();
4174
4208
  const cleaned = raw.replace(/[^a-z0-9_]/g, "_");
@@ -4270,7 +4304,7 @@ function buildParamsFromMappings(mappings) {
4270
4304
  }
4271
4305
  function resolveModelContext(directive) {
4272
4306
  const { model, datamodel } = directive.context;
4273
- const schemaModels = convertDMMFToModels(datamodel);
4307
+ const schemaModels = (0, import_schema_parser9.convertDMMFToModels)(datamodel);
4274
4308
  const modelDef = getModelByName(schemaModels, model.name);
4275
4309
  if (!modelDef) throw new Error(`Model ${model.name} not found in schema`);
4276
4310
  return { schemaModels, modelDef };
@@ -4365,6 +4399,9 @@ function generateSQL(directive) {
4365
4399
  normalizedMappings: normalized.paramMappings
4366
4400
  });
4367
4401
  }
4402
+
4403
+ // src/index.ts
4404
+ var import_schema_parser10 = require("@dee-wan/schema-parser");
4368
4405
  function generateSQL2(directive) {
4369
4406
  return generateSQL(directive);
4370
4407
  }
@@ -4374,8 +4411,8 @@ function generateClient(options) {
4374
4411
  return __async(this, null, function* () {
4375
4412
  const { datamodel, outputDir, config } = options;
4376
4413
  setGlobalDialect(config.dialect);
4377
- const models = convertDMMFToModels(datamodel);
4378
- const directiveResults = processAllDirectives(
4414
+ const models = (0, import_schema_parser11.convertDMMFToModels)(datamodel);
4415
+ const directiveResults = (0, import_schema_parser11.processAllDirectives)(
4379
4416
  datamodel.models,
4380
4417
  datamodel,
4381
4418
  {
@@ -4407,9 +4444,9 @@ function generateClient(options) {
4407
4444
  queries.set(modelName, modelQueries);
4408
4445
  }
4409
4446
  }
4410
- yield mkdir(outputDir, { recursive: true });
4447
+ yield (0, import_promises.mkdir)(outputDir, { recursive: true });
4411
4448
  const code = generateCode(models, queries, config.dialect);
4412
- yield writeFile(join(outputDir, "index.ts"), code);
4449
+ yield (0, import_promises.writeFile)((0, import_path.join)(outputDir, "index.ts"), code);
4413
4450
  const totalQueries = Array.from(queries.values()).reduce(
4414
4451
  (sum, m) => sum + m.size,
4415
4452
  0
@@ -4600,6 +4637,9 @@ ${queryEntries.join(",\n")}
4600
4637
  ${entries.join(",\n")}
4601
4638
  }`;
4602
4639
  }
4640
+
4641
+ // src/generator.ts
4642
+ var import_internals = require("@prisma/internals");
4603
4643
  var { version } = require_package();
4604
4644
  function getDialectFromProvider(provider) {
4605
4645
  const normalized = provider.toLowerCase();
@@ -4610,7 +4650,7 @@ function getDialectFromProvider(provider) {
4610
4650
  `Unsupported database provider: ${provider}. Supported: postgresql, postgres, sqlite`
4611
4651
  );
4612
4652
  }
4613
- generatorHandler({
4653
+ (0, import_generator_helper.generatorHandler)({
4614
4654
  onManifest() {
4615
4655
  return {
4616
4656
  version,
@@ -4630,7 +4670,7 @@ generatorHandler({
4630
4670
  const configDialect = generator.config.dialect;
4631
4671
  const dialect = configDialect || autoDialect;
4632
4672
  if (configDialect && configDialect !== autoDialect) {
4633
- logger.warn(
4673
+ import_internals.logger.warn(
4634
4674
  `Generator dialect (${configDialect}) differs from datasource provider (${datasources[0].provider}). Using generator config: ${configDialect}`
4635
4675
  );
4636
4676
  }
@@ -4639,18 +4679,16 @@ generatorHandler({
4639
4679
  skipInvalid: generator.config.skipInvalid === "true"
4640
4680
  };
4641
4681
  const outputDir = ((_a = generator.output) == null ? void 0 : _a.value) || "../node_modules/.prisma/client/sql";
4642
- logger.info(`Generating SQL client to ${outputDir}`);
4643
- logger.info(`Datasource: ${datasources[0].provider}`);
4644
- logger.info(`Dialect: ${config.dialect}`);
4645
- logger.info(`Skip invalid: ${config.skipInvalid}`);
4682
+ import_internals.logger.info(`Generating SQL client to ${outputDir}`);
4683
+ import_internals.logger.info(`Datasource: ${datasources[0].provider}`);
4684
+ import_internals.logger.info(`Dialect: ${config.dialect}`);
4685
+ import_internals.logger.info(`Skip invalid: ${config.skipInvalid}`);
4646
4686
  yield generateClient({
4647
4687
  datamodel: dmmf.datamodel,
4648
4688
  outputDir,
4649
4689
  config
4650
4690
  });
4651
- logger.info("\u2713 Generated SQL client successfully");
4691
+ import_internals.logger.info("\u2713 Generated SQL client successfully");
4652
4692
  });
4653
4693
  }
4654
4694
  });
4655
- //# sourceMappingURL=generator.js.map
4656
- //# sourceMappingURL=generator.js.map