prisma-sql 1.5.0 → 1.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/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,14 +47,17 @@ 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.7.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",
61
57
  types: "dist/index.d.ts",
58
+ bin: {
59
+ "prisma-sql-generator": "./dist/generator.cjs"
60
+ },
62
61
  exports: {
63
62
  ".": {
64
63
  types: "./dist/index.d.ts",
@@ -149,6 +148,14 @@ var require_package = __commonJS({
149
148
  }
150
149
  });
151
150
 
151
+ // src/generator.ts
152
+ var import_generator_helper = require("@prisma/generator-helper");
153
+
154
+ // src/code-emitter.ts
155
+ var import_schema_parser11 = require("@dee-wan/schema-parser");
156
+ var import_promises = require("fs/promises");
157
+ var import_path = require("path");
158
+
152
159
  // src/sql-builder-dialect.ts
153
160
  var globalDialect = "postgres";
154
161
  function setGlobalDialect(dialect) {
@@ -464,6 +471,7 @@ var Wildcards = Object.freeze({
464
471
  [Ops.ENDS_WITH]: (v) => `%${v}`
465
472
  });
466
473
  var REGEX_CACHE = {
474
+ PARAM_PLACEHOLDER: /\$(\d+)/g,
467
475
  VALID_IDENTIFIER: /^[a-z_][a-z0-9_]*$/
468
476
  };
469
477
  var LIMITS = Object.freeze({
@@ -768,7 +776,7 @@ function validateMappingsAgainstPlaceholders(mappings, placeholders, max, dialec
768
776
  const mappingIndices = /* @__PURE__ */ new Set();
769
777
  for (const mapping of mappings) {
770
778
  validateMappingIndex(mapping, max);
771
- ensureUniqueMappingIndex(mappingIndices, mapping.index);
779
+ ensureUniqueMappingIndex(mappingIndices, mapping.index, dialect);
772
780
  ensureMappingIndexExistsInSql(placeholders, mapping.index);
773
781
  validateMappingValueShape(mapping);
774
782
  }
@@ -958,6 +966,9 @@ function joinCondition(field, parentAlias, childAlias) {
958
966
  function getModelByName(schemas, name) {
959
967
  return schemas.find((m) => m.name === name);
960
968
  }
969
+
970
+ // src/builder/where/operators-scalar.ts
971
+ var import_schema_parser = require("@dee-wan/schema-parser");
961
972
  function buildNotComposite(expr, val, params, dialect, buildOp, separator) {
962
973
  const entries = Object.entries(val).filter(
963
974
  ([k, v]) => k !== "mode" && v !== void 0
@@ -986,7 +997,7 @@ function buildScalarOperator(expr, op, val, params, mode, fieldType, dialect) {
986
997
  }
987
998
  if (op === Ops.EQUALS && mode === Modes.INSENSITIVE && isNotNullish(dialect)) {
988
999
  const placeholder = params.addAuto(val);
989
- return caseInsensitiveEquals(expr, placeholder);
1000
+ return caseInsensitiveEquals(expr, placeholder, dialect);
990
1001
  }
991
1002
  const STRING_LIKE_OPS = /* @__PURE__ */ new Set([
992
1003
  Ops.CONTAINS,
@@ -1057,7 +1068,7 @@ function buildDynamicLikePattern(op, placeholder, dialect) {
1057
1068
  }
1058
1069
  function handleLikeOperator(expr, op, val, params, mode, dialect) {
1059
1070
  if (val === void 0) return "";
1060
- if (isDynamicParameter(val)) {
1071
+ if ((0, import_schema_parser.isDynamicParameter)(val)) {
1061
1072
  const placeholder2 = params.addAuto(val);
1062
1073
  const patternExpr = buildDynamicLikePattern(op, placeholder2, dialect);
1063
1074
  if (mode === Modes.INSENSITIVE) {
@@ -1073,7 +1084,7 @@ function handleLikeOperator(expr, op, val, params, mode, dialect) {
1073
1084
  }
1074
1085
  function handleInOperator(expr, op, val, params, dialect) {
1075
1086
  if (val === void 0) return "";
1076
- if (isDynamicParameter(val)) {
1087
+ if ((0, import_schema_parser.isDynamicParameter)(val)) {
1077
1088
  const placeholder2 = params.addAuto(val);
1078
1089
  return op === Ops.IN ? inArray(expr, placeholder2, dialect) : notInArray(expr, placeholder2, dialect);
1079
1090
  }
@@ -1106,8 +1117,11 @@ function handleComparisonOperator(expr, op, val, params) {
1106
1117
  const placeholder = params.addAuto(val);
1107
1118
  return `${expr} ${sqlOp} ${placeholder}`;
1108
1119
  }
1120
+
1121
+ // src/builder/where/operators-array.ts
1122
+ var import_schema_parser2 = require("@dee-wan/schema-parser");
1109
1123
  function buildArrayParam(val, params, dialect) {
1110
- if (isDynamicParameter(val)) {
1124
+ if ((0, import_schema_parser2.isDynamicParameter)(val)) {
1111
1125
  return params.addAuto(val);
1112
1126
  }
1113
1127
  if (!Array.isArray(val)) {
@@ -1181,7 +1195,7 @@ function handleArrayHas(expr, val, params, cast, dialect) {
1181
1195
  value: val
1182
1196
  });
1183
1197
  }
1184
- if (!isDynamicParameter(val) && Array.isArray(val)) {
1198
+ if (!(0, import_schema_parser2.isDynamicParameter)(val) && Array.isArray(val)) {
1185
1199
  throw createError(`has requires scalar value (single element), not array`, {
1186
1200
  operator: Ops.HAS,
1187
1201
  value: val
@@ -1198,7 +1212,7 @@ function handleArrayHas(expr, val, params, cast, dialect) {
1198
1212
  }
1199
1213
  function handleArrayHasSome(expr, val, params, cast, dialect) {
1200
1214
  if (val === void 0) return "";
1201
- if (isDynamicParameter(val)) {
1215
+ if ((0, import_schema_parser2.isDynamicParameter)(val)) {
1202
1216
  const placeholder2 = params.addAuto(val);
1203
1217
  return arrayOverlaps(expr, placeholder2, cast, dialect);
1204
1218
  }
@@ -1870,6 +1884,9 @@ function createAliasGenerator(maxAliases = 1e4) {
1870
1884
  }
1871
1885
  };
1872
1886
  }
1887
+
1888
+ // src/builder/shared/param-store.ts
1889
+ var import_schema_parser3 = require("@dee-wan/schema-parser");
1873
1890
  var MAX_PARAM_INDEX = Number.MAX_SAFE_INTEGER - 1e3;
1874
1891
  function assertSameLength(params, mappings) {
1875
1892
  if (params.length !== mappings.length) {
@@ -2000,8 +2017,8 @@ function createStoreInternal(startIndex, initialParams = [], initialMappings = [
2000
2017
  return dynamicName === void 0 ? addStatic(value) : addDynamic(dynamicName);
2001
2018
  }
2002
2019
  function addAuto(value) {
2003
- if (isDynamicParameter(value)) {
2004
- const dynamicName = extractDynamicName(value);
2020
+ if ((0, import_schema_parser3.isDynamicParameter)(value)) {
2021
+ const dynamicName = (0, import_schema_parser3.extractDynamicName)(value);
2005
2022
  return add(void 0, dynamicName);
2006
2023
  }
2007
2024
  return add(value);
@@ -2090,10 +2107,13 @@ function buildWhereClause(where, options) {
2090
2107
  }
2091
2108
  return publicResult;
2092
2109
  }
2110
+
2111
+ // src/builder/shared/int-like.ts
2112
+ var import_schema_parser4 = require("@dee-wan/schema-parser");
2093
2113
  function normalizeIntLike(name, v, opts = {}) {
2094
2114
  var _a, _b;
2095
2115
  if (!isNotNullish(v)) return void 0;
2096
- if (isDynamicParameter(v)) return v;
2116
+ if ((0, import_schema_parser4.isDynamicParameter)(v)) return v;
2097
2117
  if (typeof v !== "number" || !Number.isFinite(v) || !Number.isInteger(v)) {
2098
2118
  throw new Error(`${name} must be an integer`);
2099
2119
  }
@@ -2110,6 +2130,9 @@ function normalizeIntLike(name, v, opts = {}) {
2110
2130
  }
2111
2131
  return v;
2112
2132
  }
2133
+
2134
+ // src/builder/shared/dynamic-params.ts
2135
+ var import_schema_parser5 = require("@dee-wan/schema-parser");
2113
2136
  function scopeName(scope, dynamicName) {
2114
2137
  const s = String(scope).trim();
2115
2138
  const dn = String(dynamicName).trim();
@@ -2117,13 +2140,16 @@ function scopeName(scope, dynamicName) {
2117
2140
  return `${s}:${dn}`;
2118
2141
  }
2119
2142
  function addAutoScoped(params, value, scope) {
2120
- if (isDynamicParameter(value)) {
2121
- const dn = extractDynamicName(value);
2143
+ if ((0, import_schema_parser5.isDynamicParameter)(value)) {
2144
+ const dn = (0, import_schema_parser5.extractDynamicName)(value);
2122
2145
  return params.add(void 0, scopeName(scope, dn));
2123
2146
  }
2124
2147
  return params.add(value);
2125
2148
  }
2126
2149
 
2150
+ // src/builder/pagination.ts
2151
+ var import_schema_parser6 = require("@dee-wan/schema-parser");
2152
+
2127
2153
  // src/builder/shared/order-by-utils.ts
2128
2154
  var flipNulls = (v) => {
2129
2155
  const s = String(v).toLowerCase();
@@ -2259,7 +2285,7 @@ function normalizeFiniteInteger(name, v) {
2259
2285
  return v;
2260
2286
  }
2261
2287
  function normalizeNonNegativeInt(name, v) {
2262
- if (isDynamicParameter(v)) return v;
2288
+ if ((0, import_schema_parser6.isDynamicParameter)(v)) return v;
2263
2289
  const n = normalizeFiniteInteger(name, v);
2264
2290
  if (n < 0) {
2265
2291
  throw new Error(`${name} must be >= 0`);
@@ -2273,7 +2299,7 @@ function hasNonNullishProp(v, key) {
2273
2299
  return isPlainObject(v) && key in v && isNotNullish(v[key]);
2274
2300
  }
2275
2301
  function normalizeIntegerOrDynamic(name, v) {
2276
- if (isDynamicParameter(v)) return v;
2302
+ if ((0, import_schema_parser6.isDynamicParameter)(v)) return v;
2277
2303
  return normalizeFiniteInteger(name, v);
2278
2304
  }
2279
2305
  function readSkipTake(relArgs) {
@@ -2506,6 +2532,9 @@ function getPaginationParams(method, args) {
2506
2532
  return {};
2507
2533
  }
2508
2534
 
2535
+ // src/builder/select/assembly.ts
2536
+ var import_schema_parser7 = require("@dee-wan/schema-parser");
2537
+
2509
2538
  // src/builder/select/fields.ts
2510
2539
  function toSelectEntries(select) {
2511
2540
  const out = [];
@@ -3341,7 +3370,7 @@ function appendPagination(sql, spec) {
3341
3370
  const isFindUniqueOrFirst = method === "findUnique" || method === "findFirst";
3342
3371
  if (isFindUniqueOrFirst) {
3343
3372
  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";
3373
+ const hasSkip = isNotNullish(pagination.skip) && ((0, import_schema_parser7.isDynamicParameter)(pagination.skip) || typeof pagination.skip === "number" && pagination.skip > 0) && method === "findFirst";
3345
3374
  if (hasSkip) {
3346
3375
  const placeholder = addAutoScoped(
3347
3376
  params,
@@ -3574,7 +3603,7 @@ function normalizeArgsForNegativeTake(method, args) {
3574
3603
  }
3575
3604
  function normalizeArgsForDialect(dialect, args, model) {
3576
3605
  if (dialect !== "postgres") return args;
3577
- return applyPostgresDistinctOrderBy(args);
3606
+ return applyPostgresDistinctOrderBy(args, model);
3578
3607
  }
3579
3608
  function buildCursorClauseIfAny(input) {
3580
3609
  const { cursor, orderBy, tableName, alias, params, dialect } = input;
@@ -3653,7 +3682,9 @@ function buildSelectSql(input) {
3653
3682
  const argsForSql = normalizeArgsForNegativeTake(method, args);
3654
3683
  const normalizedArgs = normalizeArgsForDialect(
3655
3684
  dialectToUse,
3656
- argsForSql);
3685
+ argsForSql,
3686
+ model
3687
+ );
3657
3688
  validateDistinct(model, normalizedArgs.distinct);
3658
3689
  validateOrderBy(model, normalizedArgs.orderBy);
3659
3690
  validateCursor(model, normalizedArgs.cursor);
@@ -3669,6 +3700,9 @@ function buildSelectSql(input) {
3669
3700
  });
3670
3701
  return constructFinalSql(spec);
3671
3702
  }
3703
+
3704
+ // src/builder/aggregates.ts
3705
+ var import_schema_parser8 = require("@dee-wan/schema-parser");
3672
3706
  var MODEL_FIELD_CACHE = /* @__PURE__ */ new WeakMap();
3673
3707
  var NUMERIC_TYPES = /* @__PURE__ */ new Set(["Int", "Float", "Decimal", "BigInt"]);
3674
3708
  var AGGREGATES = [
@@ -3763,7 +3797,7 @@ function buildNullComparison(expr, op) {
3763
3797
  throw new Error(`Operator '${op}' doesn't support null in HAVING`);
3764
3798
  }
3765
3799
  function buildInComparison(expr, op, val, params, dialect) {
3766
- if (isDynamicParameter(val)) {
3800
+ if ((0, import_schema_parser8.isDynamicParameter)(val)) {
3767
3801
  const placeholder2 = addHavingParam(params, op, val);
3768
3802
  return op === Ops.IN ? inArray(expr, placeholder2, dialect) : notInArray(expr, placeholder2, dialect);
3769
3803
  }
@@ -4088,7 +4122,7 @@ function buildGroupBySql(args, whereResult, tableName, alias, model, dialect) {
4088
4122
  assertSafeAlias(alias);
4089
4123
  assertSafeTableRef(tableName);
4090
4124
  const byFields = assertGroupByBy(args, model);
4091
- const d = getGlobalDialect();
4125
+ const d = dialect != null ? dialect : getGlobalDialect();
4092
4126
  const params = createParamStore(whereResult.nextParamIndex);
4093
4127
  const { groupFields, selectFields } = buildGroupBySelectParts(
4094
4128
  args,
@@ -4124,7 +4158,7 @@ function buildGroupBySql(args, whereResult, tableName, alias, model, dialect) {
4124
4158
  function buildCountSql(whereResult, tableName, alias, skip, dialect) {
4125
4159
  assertSafeAlias(alias);
4126
4160
  assertSafeTableRef(tableName);
4127
- const d = getGlobalDialect();
4161
+ const d = dialect != null ? dialect : getGlobalDialect();
4128
4162
  const whereClause = isValidWhereClause(whereResult.clause) ? `${SQL_TEMPLATES.WHERE} ${whereResult.clause}` : "";
4129
4163
  const params = createParamStore(whereResult.nextParamIndex);
4130
4164
  const baseSubSelect = [
@@ -4161,7 +4195,7 @@ function buildCountSql(whereResult, tableName, alias, skip, dialect) {
4161
4195
  });
4162
4196
  }
4163
4197
  function applyCountSkip(subSelect, normalizedSkip, params, dialect) {
4164
- const shouldApply = isDynamicParameter(normalizedSkip) || typeof normalizedSkip === "number" && normalizedSkip > 0;
4198
+ const shouldApply = (0, import_schema_parser8.isDynamicParameter)(normalizedSkip) || typeof normalizedSkip === "number" && normalizedSkip > 0;
4165
4199
  if (!shouldApply) return subSelect;
4166
4200
  const placeholder = addAutoScoped(params, normalizedSkip, "count.skip");
4167
4201
  if (dialect === "sqlite") {
@@ -4169,6 +4203,9 @@ function applyCountSkip(subSelect, normalizedSkip, params, dialect) {
4169
4203
  }
4170
4204
  return `${subSelect} ${SQL_TEMPLATES.OFFSET} ${placeholder}`;
4171
4205
  }
4206
+
4207
+ // src/sql-generator.ts
4208
+ var import_schema_parser9 = require("@dee-wan/schema-parser");
4172
4209
  function safeAlias(input) {
4173
4210
  const raw = String(input).toLowerCase();
4174
4211
  const cleaned = raw.replace(/[^a-z0-9_]/g, "_");
@@ -4270,7 +4307,7 @@ function buildParamsFromMappings(mappings) {
4270
4307
  }
4271
4308
  function resolveModelContext(directive) {
4272
4309
  const { model, datamodel } = directive.context;
4273
- const schemaModels = convertDMMFToModels(datamodel);
4310
+ const schemaModels = (0, import_schema_parser9.convertDMMFToModels)(datamodel);
4274
4311
  const modelDef = getModelByName(schemaModels, model.name);
4275
4312
  if (!modelDef) throw new Error(`Model ${model.name} not found in schema`);
4276
4313
  return { schemaModels, modelDef };
@@ -4365,6 +4402,9 @@ function generateSQL(directive) {
4365
4402
  normalizedMappings: normalized.paramMappings
4366
4403
  });
4367
4404
  }
4405
+
4406
+ // src/index.ts
4407
+ var import_schema_parser10 = require("@dee-wan/schema-parser");
4368
4408
  function generateSQL2(directive) {
4369
4409
  return generateSQL(directive);
4370
4410
  }
@@ -4374,8 +4414,8 @@ function generateClient(options) {
4374
4414
  return __async(this, null, function* () {
4375
4415
  const { datamodel, outputDir, config } = options;
4376
4416
  setGlobalDialect(config.dialect);
4377
- const models = convertDMMFToModels(datamodel);
4378
- const directiveResults = processAllDirectives(
4417
+ const models = (0, import_schema_parser11.convertDMMFToModels)(datamodel);
4418
+ const directiveResults = (0, import_schema_parser11.processAllDirectives)(
4379
4419
  datamodel.models,
4380
4420
  datamodel,
4381
4421
  {
@@ -4407,9 +4447,9 @@ function generateClient(options) {
4407
4447
  queries.set(modelName, modelQueries);
4408
4448
  }
4409
4449
  }
4410
- yield mkdir(outputDir, { recursive: true });
4450
+ yield (0, import_promises.mkdir)(outputDir, { recursive: true });
4411
4451
  const code = generateCode(models, queries, config.dialect);
4412
- yield writeFile(join(outputDir, "index.ts"), code);
4452
+ yield (0, import_promises.writeFile)((0, import_path.join)(outputDir, "index.ts"), code);
4413
4453
  const totalQueries = Array.from(queries.values()).reduce(
4414
4454
  (sum, m) => sum + m.size,
4415
4455
  0
@@ -4600,6 +4640,9 @@ ${queryEntries.join(",\n")}
4600
4640
  ${entries.join(",\n")}
4601
4641
  }`;
4602
4642
  }
4643
+
4644
+ // src/generator.ts
4645
+ var import_internals = require("@prisma/internals");
4603
4646
  var { version } = require_package();
4604
4647
  function getDialectFromProvider(provider) {
4605
4648
  const normalized = provider.toLowerCase();
@@ -4610,7 +4653,7 @@ function getDialectFromProvider(provider) {
4610
4653
  `Unsupported database provider: ${provider}. Supported: postgresql, postgres, sqlite`
4611
4654
  );
4612
4655
  }
4613
- generatorHandler({
4656
+ (0, import_generator_helper.generatorHandler)({
4614
4657
  onManifest() {
4615
4658
  return {
4616
4659
  version,
@@ -4630,7 +4673,7 @@ generatorHandler({
4630
4673
  const configDialect = generator.config.dialect;
4631
4674
  const dialect = configDialect || autoDialect;
4632
4675
  if (configDialect && configDialect !== autoDialect) {
4633
- logger.warn(
4676
+ import_internals.logger.warn(
4634
4677
  `Generator dialect (${configDialect}) differs from datasource provider (${datasources[0].provider}). Using generator config: ${configDialect}`
4635
4678
  );
4636
4679
  }
@@ -4639,18 +4682,16 @@ generatorHandler({
4639
4682
  skipInvalid: generator.config.skipInvalid === "true"
4640
4683
  };
4641
4684
  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}`);
4685
+ import_internals.logger.info(`Generating SQL client to ${outputDir}`);
4686
+ import_internals.logger.info(`Datasource: ${datasources[0].provider}`);
4687
+ import_internals.logger.info(`Dialect: ${config.dialect}`);
4688
+ import_internals.logger.info(`Skip invalid: ${config.skipInvalid}`);
4646
4689
  yield generateClient({
4647
4690
  datamodel: dmmf.datamodel,
4648
4691
  outputDir,
4649
4692
  config
4650
4693
  });
4651
- logger.info("\u2713 Generated SQL client successfully");
4694
+ import_internals.logger.info("\u2713 Generated SQL client successfully");
4652
4695
  });
4653
4696
  }
4654
4697
  });
4655
- //# sourceMappingURL=generator.js.map
4656
- //# sourceMappingURL=generator.js.map