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