prisma-sql 1.75.9 → 1.75.10
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.cjs +9 -596
- package/dist/generator.cjs.map +1 -1
- package/dist/generator.js +9 -596
- package/dist/generator.js.map +1 -1
- package/package.json +1 -1
package/dist/generator.cjs
CHANGED
|
@@ -70,7 +70,7 @@ var require_package = __commonJS({
|
|
|
70
70
|
"package.json"(exports$1, module) {
|
|
71
71
|
module.exports = {
|
|
72
72
|
name: "prisma-sql",
|
|
73
|
-
version: "1.75.
|
|
73
|
+
version: "1.75.10",
|
|
74
74
|
description: "Convert Prisma queries to optimized SQL with type safety. 2-7x faster than Prisma Client.",
|
|
75
75
|
main: "dist/index.cjs",
|
|
76
76
|
module: "dist/index.js",
|
|
@@ -7244,38 +7244,6 @@ function generateSQL2(directive) {
|
|
|
7244
7244
|
}
|
|
7245
7245
|
|
|
7246
7246
|
// src/utils/pure-utils.ts
|
|
7247
|
-
function toNumberOrZero(v) {
|
|
7248
|
-
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
7249
|
-
if (typeof v === "bigint") return Number(v);
|
|
7250
|
-
if (typeof v === "string" && v.trim() !== "") {
|
|
7251
|
-
const n = Number(v);
|
|
7252
|
-
if (Number.isFinite(n)) return n;
|
|
7253
|
-
}
|
|
7254
|
-
return 0;
|
|
7255
|
-
}
|
|
7256
|
-
function clampStatsMonotonic(avg, p95, p99, max, coverage) {
|
|
7257
|
-
const safeAvg = Math.max(1, avg);
|
|
7258
|
-
const safeP95 = Math.max(safeAvg, p95);
|
|
7259
|
-
const safeP99 = Math.max(safeP95, p99);
|
|
7260
|
-
const safeMax = Math.max(safeP99, max);
|
|
7261
|
-
const safeCoverage = Math.max(0, Math.min(1, coverage));
|
|
7262
|
-
return {
|
|
7263
|
-
avg: safeAvg,
|
|
7264
|
-
p95: safeP95,
|
|
7265
|
-
p99: safeP99,
|
|
7266
|
-
max: safeMax,
|
|
7267
|
-
coverage: safeCoverage
|
|
7268
|
-
};
|
|
7269
|
-
}
|
|
7270
|
-
function normalizeStats(row) {
|
|
7271
|
-
return clampStatsMonotonic(
|
|
7272
|
-
toNumberOrZero(row.avg),
|
|
7273
|
-
toNumberOrZero(row.p95),
|
|
7274
|
-
toNumberOrZero(row.p99),
|
|
7275
|
-
toNumberOrZero(row.max),
|
|
7276
|
-
toNumberOrZero(row.coverage)
|
|
7277
|
-
);
|
|
7278
|
-
}
|
|
7279
7247
|
function stableJson(value) {
|
|
7280
7248
|
return JSON.stringify(
|
|
7281
7249
|
value,
|
|
@@ -7312,486 +7280,6 @@ function countTotalQueries(queries) {
|
|
|
7312
7280
|
}
|
|
7313
7281
|
|
|
7314
7282
|
// src/cardinality-planner.ts
|
|
7315
|
-
function quoteIdent(dialect, ident) {
|
|
7316
|
-
return `"${ident.replace(/"/g, '""')}"`;
|
|
7317
|
-
}
|
|
7318
|
-
function createDatabaseExecutor(options) {
|
|
7319
|
-
return __async(this, null, function* () {
|
|
7320
|
-
const { databaseUrl, dialect, connectTimeoutMs = 3e4 } = options;
|
|
7321
|
-
if (dialect === "postgres") {
|
|
7322
|
-
const postgres = yield import('postgres');
|
|
7323
|
-
const sql = postgres.default(databaseUrl, {
|
|
7324
|
-
connect_timeout: Math.ceil(connectTimeoutMs / 1e3),
|
|
7325
|
-
max: 1
|
|
7326
|
-
});
|
|
7327
|
-
return {
|
|
7328
|
-
executor: {
|
|
7329
|
-
query: (q, params) => __async(null, null, function* () {
|
|
7330
|
-
return yield sql.unsafe(q, params != null ? params : []);
|
|
7331
|
-
})
|
|
7332
|
-
},
|
|
7333
|
-
cleanup: () => __async(null, null, function* () {
|
|
7334
|
-
yield sql.end();
|
|
7335
|
-
})
|
|
7336
|
-
};
|
|
7337
|
-
}
|
|
7338
|
-
throw new Error(`createDatabaseExecutor does not support dialect: ${dialect}`);
|
|
7339
|
-
});
|
|
7340
|
-
}
|
|
7341
|
-
function extractMeasurableOneToManyEdges(datamodel) {
|
|
7342
|
-
const modelByName = new Map(datamodel.models.map((m) => [m.name, m]));
|
|
7343
|
-
const edges = [];
|
|
7344
|
-
for (const parent of datamodel.models) {
|
|
7345
|
-
const pkFields = parent.fields.filter((f) => f.isId);
|
|
7346
|
-
if (pkFields.length === 0) continue;
|
|
7347
|
-
pkFields.map((f) => f.dbName || f.name);
|
|
7348
|
-
const parentTable = parent.dbName || parent.name;
|
|
7349
|
-
for (const f of parent.fields) {
|
|
7350
|
-
if (!f.relationName) continue;
|
|
7351
|
-
if (!f.isList) continue;
|
|
7352
|
-
const child = modelByName.get(f.type);
|
|
7353
|
-
if (!child) continue;
|
|
7354
|
-
const childRelField = child.fields.find(
|
|
7355
|
-
(cf) => cf.relationName === f.relationName && cf.type === parent.name
|
|
7356
|
-
);
|
|
7357
|
-
if (!childRelField) continue;
|
|
7358
|
-
const fkFieldNames = childRelField.relationFromFields || [];
|
|
7359
|
-
if (fkFieldNames.length === 0) continue;
|
|
7360
|
-
const fkFields = fkFieldNames.map((name) => {
|
|
7361
|
-
const fld = child.fields.find((x) => x.name === name);
|
|
7362
|
-
return fld ? fld.dbName || fld.name : name;
|
|
7363
|
-
});
|
|
7364
|
-
const refFieldNames = childRelField.relationToFields || [];
|
|
7365
|
-
if (refFieldNames.length === 0) continue;
|
|
7366
|
-
const references = refFieldNames.map((name) => {
|
|
7367
|
-
const fld = parent.fields.find((x) => x.name === name);
|
|
7368
|
-
return fld ? fld.dbName || fld.name : name;
|
|
7369
|
-
});
|
|
7370
|
-
if (fkFields.length !== references.length) continue;
|
|
7371
|
-
const childTable = child.dbName || child.name;
|
|
7372
|
-
edges.push({
|
|
7373
|
-
parentModel: parent.name,
|
|
7374
|
-
relName: f.name,
|
|
7375
|
-
childModel: child.name,
|
|
7376
|
-
parentTable,
|
|
7377
|
-
childTable,
|
|
7378
|
-
parentPkColumns: references,
|
|
7379
|
-
childFkColumns: fkFields,
|
|
7380
|
-
isMany: true
|
|
7381
|
-
});
|
|
7382
|
-
}
|
|
7383
|
-
}
|
|
7384
|
-
return edges;
|
|
7385
|
-
}
|
|
7386
|
-
function buildPostgresStatsSql(edge) {
|
|
7387
|
-
const childTable = quoteIdent("postgres", edge.childTable);
|
|
7388
|
-
const parentTable = quoteIdent("postgres", edge.parentTable);
|
|
7389
|
-
const groupCols = edge.childFkColumns.map((c) => quoteIdent("postgres", c)).join(", ");
|
|
7390
|
-
return `
|
|
7391
|
-
WITH counts AS (
|
|
7392
|
-
SELECT ${groupCols}, COUNT(*) AS cnt
|
|
7393
|
-
FROM ${childTable}
|
|
7394
|
-
GROUP BY ${groupCols}
|
|
7395
|
-
),
|
|
7396
|
-
total_parents AS (
|
|
7397
|
-
SELECT COUNT(*) AS total FROM ${parentTable}
|
|
7398
|
-
)
|
|
7399
|
-
SELECT
|
|
7400
|
-
AVG(cnt)::float AS avg,
|
|
7401
|
-
MAX(cnt)::int AS max,
|
|
7402
|
-
PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY cnt)::float AS p95,
|
|
7403
|
-
PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY cnt)::float AS p99,
|
|
7404
|
-
(SELECT COUNT(*) FROM counts)::float / GREATEST(1, (SELECT total FROM total_parents)) AS coverage
|
|
7405
|
-
FROM counts
|
|
7406
|
-
`.trim();
|
|
7407
|
-
}
|
|
7408
|
-
function buildSqliteStatsSql(edge) {
|
|
7409
|
-
const childTable = quoteIdent("sqlite", edge.childTable);
|
|
7410
|
-
const parentTable = quoteIdent("sqlite", edge.parentTable);
|
|
7411
|
-
const groupCols = edge.childFkColumns.map((c) => quoteIdent("sqlite", c)).join(", ");
|
|
7412
|
-
return `
|
|
7413
|
-
WITH counts AS (
|
|
7414
|
-
SELECT ${groupCols}, COUNT(*) AS cnt
|
|
7415
|
-
FROM ${childTable}
|
|
7416
|
-
GROUP BY ${groupCols}
|
|
7417
|
-
),
|
|
7418
|
-
n AS (
|
|
7419
|
-
SELECT COUNT(*) AS total FROM counts
|
|
7420
|
-
),
|
|
7421
|
-
parent_n AS (
|
|
7422
|
-
SELECT COUNT(*) AS total FROM ${parentTable}
|
|
7423
|
-
),
|
|
7424
|
-
ordered AS (
|
|
7425
|
-
SELECT cnt
|
|
7426
|
-
FROM counts
|
|
7427
|
-
ORDER BY cnt
|
|
7428
|
-
)
|
|
7429
|
-
SELECT
|
|
7430
|
-
(SELECT AVG(cnt) FROM counts) AS avg,
|
|
7431
|
-
(SELECT MAX(cnt) FROM counts) AS max,
|
|
7432
|
-
(
|
|
7433
|
-
SELECT cnt
|
|
7434
|
-
FROM ordered
|
|
7435
|
-
LIMIT 1
|
|
7436
|
-
OFFSET (
|
|
7437
|
-
SELECT
|
|
7438
|
-
CASE
|
|
7439
|
-
WHEN total <= 1 THEN 0
|
|
7440
|
-
ELSE CAST((0.95 * (total - 1)) AS INT)
|
|
7441
|
-
END
|
|
7442
|
-
FROM n
|
|
7443
|
-
)
|
|
7444
|
-
) AS p95,
|
|
7445
|
-
(
|
|
7446
|
-
SELECT cnt
|
|
7447
|
-
FROM ordered
|
|
7448
|
-
LIMIT 1
|
|
7449
|
-
OFFSET (
|
|
7450
|
-
SELECT
|
|
7451
|
-
CASE
|
|
7452
|
-
WHEN total <= 1 THEN 0
|
|
7453
|
-
ELSE CAST((0.99 * (total - 1)) AS INT)
|
|
7454
|
-
END
|
|
7455
|
-
FROM n
|
|
7456
|
-
)
|
|
7457
|
-
) AS p99,
|
|
7458
|
-
CAST((SELECT total FROM n) AS FLOAT) / MAX(1, (SELECT total FROM parent_n)) AS coverage
|
|
7459
|
-
`.trim();
|
|
7460
|
-
}
|
|
7461
|
-
function buildFanoutStatsSql(dialect, edge) {
|
|
7462
|
-
return dialect === "postgres" ? buildPostgresStatsSql(edge) : buildSqliteStatsSql(edge);
|
|
7463
|
-
}
|
|
7464
|
-
function findLargestTable(params) {
|
|
7465
|
-
return __async(this, null, function* () {
|
|
7466
|
-
var _a3;
|
|
7467
|
-
const { executor, dialect, datamodel } = params;
|
|
7468
|
-
let best = null;
|
|
7469
|
-
for (const model of datamodel.models) {
|
|
7470
|
-
const table = quoteIdent(dialect, model.dbName || model.name);
|
|
7471
|
-
try {
|
|
7472
|
-
const rows = yield executor.query(`SELECT COUNT(*) AS cnt FROM ${table}`);
|
|
7473
|
-
const count = toNumberOrZero((_a3 = rows[0]) == null ? void 0 : _a3.cnt);
|
|
7474
|
-
if (!best || count > best.rowCount) {
|
|
7475
|
-
best = { tableName: table, rowCount: count };
|
|
7476
|
-
}
|
|
7477
|
-
} catch (_) {
|
|
7478
|
-
}
|
|
7479
|
-
}
|
|
7480
|
-
return best;
|
|
7481
|
-
});
|
|
7482
|
-
}
|
|
7483
|
-
function measureRoundtripCost(params) {
|
|
7484
|
-
return __async(this, null, function* () {
|
|
7485
|
-
var _a3, _b;
|
|
7486
|
-
const { executor, dialect, datamodel } = params;
|
|
7487
|
-
const WARMUP = 5;
|
|
7488
|
-
const SAMPLES = 15;
|
|
7489
|
-
for (let i = 0; i < WARMUP; i++) {
|
|
7490
|
-
yield executor.query("SELECT 1");
|
|
7491
|
-
}
|
|
7492
|
-
const roundtripTimes = [];
|
|
7493
|
-
for (let i = 0; i < SAMPLES; i++) {
|
|
7494
|
-
const start = performance.now();
|
|
7495
|
-
yield executor.query("SELECT 1");
|
|
7496
|
-
roundtripTimes.push(performance.now() - start);
|
|
7497
|
-
}
|
|
7498
|
-
roundtripTimes.sort((a, b) => a - b);
|
|
7499
|
-
const medianRoundtrip = roundtripTimes[Math.floor(SAMPLES / 2)];
|
|
7500
|
-
console.log(
|
|
7501
|
-
` [roundtrip] SELECT 1 times (ms): min=${roundtripTimes[0].toFixed(3)} median=${medianRoundtrip.toFixed(3)} max=${roundtripTimes[SAMPLES - 1].toFixed(3)}`
|
|
7502
|
-
);
|
|
7503
|
-
const largest = yield findLargestTable({ executor, dialect, datamodel });
|
|
7504
|
-
if (!largest || largest.rowCount < 50) {
|
|
7505
|
-
console.log(
|
|
7506
|
-
` [roundtrip] Largest table: ${(_a3 = largest == null ? void 0 : largest.tableName) != null ? _a3 : "none"} (${(_b = largest == null ? void 0 : largest.rowCount) != null ? _b : 0} rows) \u2014 too small, using default 50`
|
|
7507
|
-
);
|
|
7508
|
-
return 50;
|
|
7509
|
-
}
|
|
7510
|
-
console.log(
|
|
7511
|
-
` [roundtrip] Using table ${largest.tableName} (${largest.rowCount} rows)`
|
|
7512
|
-
);
|
|
7513
|
-
return estimateFromQueryPairRatio({
|
|
7514
|
-
executor,
|
|
7515
|
-
tableName: largest.tableName,
|
|
7516
|
-
tableRowCount: largest.rowCount
|
|
7517
|
-
});
|
|
7518
|
-
});
|
|
7519
|
-
}
|
|
7520
|
-
function estimateFromQueryPairRatio(params) {
|
|
7521
|
-
return __async(this, null, function* () {
|
|
7522
|
-
const { executor, tableName, tableRowCount } = params;
|
|
7523
|
-
const WARMUP = 5;
|
|
7524
|
-
const SAMPLES = 10;
|
|
7525
|
-
const smallLimit = 1;
|
|
7526
|
-
const largeLimit = Math.min(1e3, tableRowCount);
|
|
7527
|
-
for (let i = 0; i < WARMUP; i++) {
|
|
7528
|
-
yield executor.query(`SELECT * FROM ${tableName} LIMIT ${largeLimit}`);
|
|
7529
|
-
}
|
|
7530
|
-
const smallTimes = [];
|
|
7531
|
-
for (let i = 0; i < SAMPLES; i++) {
|
|
7532
|
-
const start = performance.now();
|
|
7533
|
-
yield executor.query(`SELECT * FROM ${tableName} LIMIT ${smallLimit}`);
|
|
7534
|
-
smallTimes.push(performance.now() - start);
|
|
7535
|
-
}
|
|
7536
|
-
smallTimes.sort((a, b) => a - b);
|
|
7537
|
-
const medianSmall = smallTimes[Math.floor(SAMPLES / 2)];
|
|
7538
|
-
const largeTimes = [];
|
|
7539
|
-
let actualLargeRows = 0;
|
|
7540
|
-
for (let i = 0; i < SAMPLES; i++) {
|
|
7541
|
-
const start = performance.now();
|
|
7542
|
-
const rows = yield executor.query(
|
|
7543
|
-
`SELECT * FROM ${tableName} LIMIT ${largeLimit}`
|
|
7544
|
-
);
|
|
7545
|
-
largeTimes.push(performance.now() - start);
|
|
7546
|
-
actualLargeRows = rows.length;
|
|
7547
|
-
}
|
|
7548
|
-
largeTimes.sort((a, b) => a - b);
|
|
7549
|
-
const medianLarge = largeTimes[Math.floor(SAMPLES / 2)];
|
|
7550
|
-
const rowDiff = actualLargeRows - smallLimit;
|
|
7551
|
-
const timeDiff = medianLarge - medianSmall;
|
|
7552
|
-
console.log(
|
|
7553
|
-
` [roundtrip] LIMIT ${smallLimit}: median=${medianSmall.toFixed(3)}ms`
|
|
7554
|
-
);
|
|
7555
|
-
console.log(
|
|
7556
|
-
` [roundtrip] LIMIT ${largeLimit} (got ${actualLargeRows}): median=${medianLarge.toFixed(3)}ms`
|
|
7557
|
-
);
|
|
7558
|
-
console.log(
|
|
7559
|
-
` [roundtrip] Time diff: ${timeDiff.toFixed(3)}ms for ${rowDiff} rows`
|
|
7560
|
-
);
|
|
7561
|
-
if (rowDiff < 50 || timeDiff <= 0.05) {
|
|
7562
|
-
console.log(
|
|
7563
|
-
` [roundtrip] Insufficient signal (need \u226550 row diff and >0.05ms time diff), defaulting to 50`
|
|
7564
|
-
);
|
|
7565
|
-
return 50;
|
|
7566
|
-
}
|
|
7567
|
-
const perRow = timeDiff / rowDiff;
|
|
7568
|
-
const sequentialTimes = [];
|
|
7569
|
-
for (let i = 0; i < SAMPLES; i++) {
|
|
7570
|
-
const start = performance.now();
|
|
7571
|
-
yield executor.query(`SELECT * FROM ${tableName} LIMIT ${smallLimit}`);
|
|
7572
|
-
yield executor.query(`SELECT * FROM ${tableName} LIMIT ${smallLimit}`);
|
|
7573
|
-
yield executor.query(`SELECT * FROM ${tableName} LIMIT ${smallLimit}`);
|
|
7574
|
-
sequentialTimes.push(performance.now() - start);
|
|
7575
|
-
}
|
|
7576
|
-
sequentialTimes.sort((a, b) => a - b);
|
|
7577
|
-
const median3Sequential = sequentialTimes[Math.floor(SAMPLES / 2)];
|
|
7578
|
-
const marginalQueryCost = (median3Sequential - medianSmall) / 2;
|
|
7579
|
-
console.log(
|
|
7580
|
-
` [roundtrip] 3x sequential LIMIT 1: median=${median3Sequential.toFixed(3)}ms`
|
|
7581
|
-
);
|
|
7582
|
-
console.log(` [roundtrip] Single query: ${medianSmall.toFixed(3)}ms`);
|
|
7583
|
-
console.log(
|
|
7584
|
-
` [roundtrip] Marginal query cost: ${marginalQueryCost.toFixed(3)}ms`
|
|
7585
|
-
);
|
|
7586
|
-
console.log(` [roundtrip] Per-row cost: ${perRow.toFixed(4)}ms`);
|
|
7587
|
-
const equivalent = Math.round(marginalQueryCost / perRow);
|
|
7588
|
-
console.log(` [roundtrip] Raw equivalent: ${equivalent} rows`);
|
|
7589
|
-
const clamped = Math.max(10, Math.min(500, equivalent));
|
|
7590
|
-
console.log(` [roundtrip] Final (clamped): ${clamped} rows`);
|
|
7591
|
-
return clamped;
|
|
7592
|
-
});
|
|
7593
|
-
}
|
|
7594
|
-
function measureJsonOverhead(params) {
|
|
7595
|
-
return __async(this, null, function* () {
|
|
7596
|
-
const { executor, tableName, tableRowCount } = params;
|
|
7597
|
-
const WARMUP = 3;
|
|
7598
|
-
const SAMPLES = 10;
|
|
7599
|
-
const limit = Math.min(500, tableRowCount);
|
|
7600
|
-
const rawSql = `SELECT * FROM ${tableName} LIMIT ${limit}`;
|
|
7601
|
-
const colsResult = yield executor.query(
|
|
7602
|
-
`SELECT column_name FROM information_schema.columns WHERE table_name = ${tableName.replace(/"/g, "'")} LIMIT 10`
|
|
7603
|
-
);
|
|
7604
|
-
let aggSql;
|
|
7605
|
-
if (colsResult.length >= 3) {
|
|
7606
|
-
const cols = colsResult.slice(0, 6).map((r) => `"${r.column_name}"`);
|
|
7607
|
-
const aggExprs = cols.map((c) => `array_agg(${c})`).join(", ");
|
|
7608
|
-
const groupCol = cols[0];
|
|
7609
|
-
aggSql = `SELECT ${groupCol}, ${aggExprs} FROM ${tableName} GROUP BY ${groupCol} LIMIT ${limit}`;
|
|
7610
|
-
} else {
|
|
7611
|
-
aggSql = `SELECT json_agg(t) FROM (SELECT * FROM ${tableName} LIMIT ${limit}) t`;
|
|
7612
|
-
}
|
|
7613
|
-
for (let i = 0; i < WARMUP; i++) {
|
|
7614
|
-
yield executor.query(rawSql);
|
|
7615
|
-
yield executor.query(aggSql);
|
|
7616
|
-
}
|
|
7617
|
-
const rawTimes = [];
|
|
7618
|
-
for (let i = 0; i < SAMPLES; i++) {
|
|
7619
|
-
const start = performance.now();
|
|
7620
|
-
yield executor.query(rawSql);
|
|
7621
|
-
rawTimes.push(performance.now() - start);
|
|
7622
|
-
}
|
|
7623
|
-
rawTimes.sort((a, b) => a - b);
|
|
7624
|
-
const medianRaw = rawTimes[Math.floor(SAMPLES / 2)];
|
|
7625
|
-
const aggTimes = [];
|
|
7626
|
-
for (let i = 0; i < SAMPLES; i++) {
|
|
7627
|
-
const start = performance.now();
|
|
7628
|
-
yield executor.query(aggSql);
|
|
7629
|
-
aggTimes.push(performance.now() - start);
|
|
7630
|
-
}
|
|
7631
|
-
aggTimes.sort((a, b) => a - b);
|
|
7632
|
-
const medianAgg = aggTimes[Math.floor(SAMPLES / 2)];
|
|
7633
|
-
const factor = medianRaw > 0.01 ? medianAgg / medianRaw : 3;
|
|
7634
|
-
console.log(` [json] Raw ${limit} rows: ${medianRaw.toFixed(3)}ms`);
|
|
7635
|
-
console.log(` [json] array_agg grouped: ${medianAgg.toFixed(3)}ms`);
|
|
7636
|
-
console.log(` [json] Overhead factor: ${factor.toFixed(2)}x`);
|
|
7637
|
-
return Math.max(1.5, Math.min(8, factor));
|
|
7638
|
-
});
|
|
7639
|
-
}
|
|
7640
|
-
function collectPostgresStatsFromCatalog(params) {
|
|
7641
|
-
return __async(this, null, function* () {
|
|
7642
|
-
const { executor, datamodel } = params;
|
|
7643
|
-
const edges = extractMeasurableOneToManyEdges(datamodel);
|
|
7644
|
-
const out = {};
|
|
7645
|
-
const tablesToAnalyze = /* @__PURE__ */ new Set();
|
|
7646
|
-
for (const edge of edges) {
|
|
7647
|
-
tablesToAnalyze.add(edge.parentTable);
|
|
7648
|
-
tablesToAnalyze.add(edge.childTable);
|
|
7649
|
-
}
|
|
7650
|
-
for (const table of tablesToAnalyze) {
|
|
7651
|
-
try {
|
|
7652
|
-
yield executor.query(`ANALYZE ${quoteIdent("postgres", table)}`);
|
|
7653
|
-
} catch (_) {
|
|
7654
|
-
}
|
|
7655
|
-
}
|
|
7656
|
-
const tableStatsQuery = `
|
|
7657
|
-
SELECT
|
|
7658
|
-
c.relname as table_name,
|
|
7659
|
-
c.reltuples::bigint as row_count
|
|
7660
|
-
FROM pg_class c
|
|
7661
|
-
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
7662
|
-
WHERE c.relkind = 'r'
|
|
7663
|
-
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
7664
|
-
`;
|
|
7665
|
-
const tableStats = yield executor.query(tableStatsQuery, []);
|
|
7666
|
-
const rowCounts = /* @__PURE__ */ new Map();
|
|
7667
|
-
for (const row of tableStats) {
|
|
7668
|
-
const tableName = String(row.table_name);
|
|
7669
|
-
const count = toNumberOrZero(row.row_count);
|
|
7670
|
-
rowCounts.set(tableName, count);
|
|
7671
|
-
}
|
|
7672
|
-
for (const edge of edges) {
|
|
7673
|
-
const parentRows = rowCounts.get(edge.parentTable) || 0;
|
|
7674
|
-
const childRows = rowCounts.get(edge.childTable) || 0;
|
|
7675
|
-
if (parentRows === 0 || childRows === 0) {
|
|
7676
|
-
if (!out[edge.parentModel]) out[edge.parentModel] = {};
|
|
7677
|
-
out[edge.parentModel][edge.relName] = {
|
|
7678
|
-
avg: 1,
|
|
7679
|
-
p95: 1,
|
|
7680
|
-
p99: 1,
|
|
7681
|
-
max: 1,
|
|
7682
|
-
coverage: 0
|
|
7683
|
-
};
|
|
7684
|
-
continue;
|
|
7685
|
-
}
|
|
7686
|
-
const fkColumn = edge.childFkColumns[0];
|
|
7687
|
-
const statsQuery = `
|
|
7688
|
-
SELECT
|
|
7689
|
-
s.n_distinct,
|
|
7690
|
-
s.correlation,
|
|
7691
|
-
(s.most_common_freqs)[1] as max_freq
|
|
7692
|
-
FROM pg_stats s
|
|
7693
|
-
WHERE s.tablename = $1
|
|
7694
|
-
AND s.attname = $2
|
|
7695
|
-
AND s.schemaname NOT IN ('pg_catalog', 'information_schema')
|
|
7696
|
-
`;
|
|
7697
|
-
const statsRows = yield executor.query(statsQuery, [
|
|
7698
|
-
edge.childTable,
|
|
7699
|
-
fkColumn
|
|
7700
|
-
]);
|
|
7701
|
-
let avg;
|
|
7702
|
-
let p95;
|
|
7703
|
-
let p99;
|
|
7704
|
-
let max;
|
|
7705
|
-
let coverage;
|
|
7706
|
-
if (statsRows.length > 0) {
|
|
7707
|
-
const stats = statsRows[0];
|
|
7708
|
-
const nDistinct = toNumberOrZero(stats.n_distinct);
|
|
7709
|
-
const correlation = stats.correlation !== null ? Number(stats.correlation) : 0;
|
|
7710
|
-
const maxFreq = stats.max_freq !== null ? Number(stats.max_freq) : null;
|
|
7711
|
-
const distinctCount = nDistinct < 0 ? Math.abs(nDistinct) * childRows : nDistinct > 0 ? nDistinct : parentRows;
|
|
7712
|
-
avg = distinctCount > 0 ? childRows / distinctCount : childRows / parentRows;
|
|
7713
|
-
coverage = Math.min(1, distinctCount / parentRows);
|
|
7714
|
-
const skewFactor = Math.abs(correlation) > 0.5 ? 2.5 : 1.5;
|
|
7715
|
-
p95 = avg * skewFactor;
|
|
7716
|
-
p99 = avg * (skewFactor * 1.3);
|
|
7717
|
-
max = maxFreq ? Math.ceil(childRows * maxFreq) : Math.ceil(p99 * 1.5);
|
|
7718
|
-
} else {
|
|
7719
|
-
avg = childRows / parentRows;
|
|
7720
|
-
coverage = 1;
|
|
7721
|
-
p95 = avg * 2;
|
|
7722
|
-
p99 = avg * 3;
|
|
7723
|
-
max = avg * 5;
|
|
7724
|
-
}
|
|
7725
|
-
if (!out[edge.parentModel]) out[edge.parentModel] = {};
|
|
7726
|
-
out[edge.parentModel][edge.relName] = clampStatsMonotonic(
|
|
7727
|
-
Math.ceil(avg),
|
|
7728
|
-
Math.ceil(p95),
|
|
7729
|
-
Math.ceil(p99),
|
|
7730
|
-
Math.ceil(max),
|
|
7731
|
-
coverage
|
|
7732
|
-
);
|
|
7733
|
-
}
|
|
7734
|
-
return out;
|
|
7735
|
-
});
|
|
7736
|
-
}
|
|
7737
|
-
function collectPreciseCardinalities(params) {
|
|
7738
|
-
return __async(this, null, function* () {
|
|
7739
|
-
const { executor, datamodel, dialect } = params;
|
|
7740
|
-
const edges = extractMeasurableOneToManyEdges(datamodel);
|
|
7741
|
-
const out = {};
|
|
7742
|
-
for (const edge of edges) {
|
|
7743
|
-
const sql = buildFanoutStatsSql(dialect, edge);
|
|
7744
|
-
const rows = yield executor.query(sql, []);
|
|
7745
|
-
const row = rows[0] || {};
|
|
7746
|
-
const stats = normalizeStats(row);
|
|
7747
|
-
if (!out[edge.parentModel]) out[edge.parentModel] = {};
|
|
7748
|
-
out[edge.parentModel][edge.relName] = stats;
|
|
7749
|
-
}
|
|
7750
|
-
return out;
|
|
7751
|
-
});
|
|
7752
|
-
}
|
|
7753
|
-
function collectRelationCardinalities(params) {
|
|
7754
|
-
return __async(this, null, function* () {
|
|
7755
|
-
const { executor, datamodel, dialect, mode = "precise" } = params;
|
|
7756
|
-
if (dialect === "postgres" && mode === "fast") {
|
|
7757
|
-
const stats = yield collectPostgresStatsFromCatalog({ executor, datamodel });
|
|
7758
|
-
let allTrivial = true;
|
|
7759
|
-
for (const model of Object.values(stats)) {
|
|
7760
|
-
for (const rel of Object.values(model)) {
|
|
7761
|
-
if (rel.avg > 1 || rel.coverage > 0.5) {
|
|
7762
|
-
allTrivial = false;
|
|
7763
|
-
break;
|
|
7764
|
-
}
|
|
7765
|
-
}
|
|
7766
|
-
if (!allTrivial) break;
|
|
7767
|
-
}
|
|
7768
|
-
if (allTrivial && Object.keys(stats).length > 0) {
|
|
7769
|
-
console.warn("\u26A0 Catalog stats look stale, falling back to precise mode");
|
|
7770
|
-
return collectPreciseCardinalities({ executor, datamodel, dialect });
|
|
7771
|
-
}
|
|
7772
|
-
return stats;
|
|
7773
|
-
}
|
|
7774
|
-
return collectPreciseCardinalities({ executor, datamodel, dialect });
|
|
7775
|
-
});
|
|
7776
|
-
}
|
|
7777
|
-
function collectPlannerArtifacts(params) {
|
|
7778
|
-
return __async(this, null, function* () {
|
|
7779
|
-
const { executor, datamodel, dialect, mode } = params;
|
|
7780
|
-
const largest = yield findLargestTable({ executor, dialect, datamodel });
|
|
7781
|
-
const [relationStats, roundtripRowEquivalent, jsonRowFactor] = yield Promise.all([
|
|
7782
|
-
collectRelationCardinalities({ executor, datamodel, dialect, mode }),
|
|
7783
|
-
measureRoundtripCost({ executor, dialect, datamodel }),
|
|
7784
|
-
largest && largest.rowCount >= 50 && dialect === "postgres" ? measureJsonOverhead({
|
|
7785
|
-
executor,
|
|
7786
|
-
tableName: largest.tableName,
|
|
7787
|
-
tableRowCount: largest.rowCount
|
|
7788
|
-
}) : Promise.resolve(1.5)
|
|
7789
|
-
]);
|
|
7790
|
-
console.log(` Roundtrip cost: ~${roundtripRowEquivalent} row equivalents`);
|
|
7791
|
-
console.log(` JSON overhead factor: ${jsonRowFactor.toFixed(2)}x`);
|
|
7792
|
-
return { relationStats, roundtripRowEquivalent, jsonRowFactor };
|
|
7793
|
-
});
|
|
7794
|
-
}
|
|
7795
7283
|
function emitPlannerGeneratedModule(artifacts) {
|
|
7796
7284
|
return [
|
|
7797
7285
|
`export const RELATION_STATS = ${stableJson(artifacts.relationStats)} as const`,
|
|
@@ -7806,7 +7294,6 @@ function emitPlannerGeneratedModule(artifacts) {
|
|
|
7806
7294
|
}
|
|
7807
7295
|
|
|
7808
7296
|
// src/code-emitter.ts
|
|
7809
|
-
var DB_CONNECT_TIMEOUT_MS = 5e3;
|
|
7810
7297
|
function extractEnumMappings(datamodel) {
|
|
7811
7298
|
const mappings = {};
|
|
7812
7299
|
const fieldTypes = {};
|
|
@@ -7879,8 +7366,8 @@ function processAllModelDirectives(directiveResults, config) {
|
|
|
7879
7366
|
}
|
|
7880
7367
|
function generateClient(options) {
|
|
7881
7368
|
return __async(this, null, function* () {
|
|
7882
|
-
var _a3;
|
|
7883
|
-
const { datamodel, outputDir, config
|
|
7369
|
+
var _a3, _b;
|
|
7370
|
+
const { datamodel, outputDir, config } = options;
|
|
7884
7371
|
const runtimeImportPath = (_a3 = options.runtimeImportPath) != null ? _a3 : "prisma-sql";
|
|
7885
7372
|
setGlobalDialect(config.dialect);
|
|
7886
7373
|
const models = schemaParser.convertDMMFToModels(datamodel);
|
|
@@ -7895,28 +7382,11 @@ function generateClient(options) {
|
|
|
7895
7382
|
);
|
|
7896
7383
|
const absoluteOutputDir = path.resolve(process.cwd(), outputDir);
|
|
7897
7384
|
yield promises.mkdir(absoluteOutputDir, { recursive: true });
|
|
7898
|
-
|
|
7899
|
-
|
|
7900
|
-
|
|
7901
|
-
|
|
7902
|
-
|
|
7903
|
-
"\u23ED Skipping planner stats collection (PRISMA_SQL_SKIP_PLANNER)"
|
|
7904
|
-
);
|
|
7905
|
-
} else {
|
|
7906
|
-
plannerArtifacts = yield collectPlannerWithTimeout(
|
|
7907
|
-
options,
|
|
7908
|
-
config,
|
|
7909
|
-
datasourceUrl
|
|
7910
|
-
);
|
|
7911
|
-
}
|
|
7912
|
-
}
|
|
7913
|
-
if (!plannerArtifacts) {
|
|
7914
|
-
plannerArtifacts = {
|
|
7915
|
-
relationStats: {},
|
|
7916
|
-
roundtripRowEquivalent: 73,
|
|
7917
|
-
jsonRowFactor: 1.5
|
|
7918
|
-
};
|
|
7919
|
-
}
|
|
7385
|
+
const plannerArtifacts = (_b = options.plannerArtifacts) != null ? _b : {
|
|
7386
|
+
relationStats: {},
|
|
7387
|
+
roundtripRowEquivalent: 73,
|
|
7388
|
+
jsonRowFactor: 1.5
|
|
7389
|
+
};
|
|
7920
7390
|
const plannerCode = emitPlannerGeneratedModule(plannerArtifacts);
|
|
7921
7391
|
const plannerPath = path.join(absoluteOutputDir, "planner.generated.ts");
|
|
7922
7392
|
yield promises.writeFile(plannerPath, plannerCode);
|
|
@@ -7939,61 +7409,6 @@ function generateClient(options) {
|
|
|
7939
7409
|
console.log(`\u2713 Output: ${outputPath}`);
|
|
7940
7410
|
});
|
|
7941
7411
|
}
|
|
7942
|
-
var PLANNER_TOTAL_TIMEOUT_MS = 15e3;
|
|
7943
|
-
function collectPlannerWithTimeout(options, config, datasourceUrl) {
|
|
7944
|
-
return __async(this, null, function* () {
|
|
7945
|
-
const timeoutMs = Number(process.env.PRISMA_SQL_PLANNER_TIMEOUT_MS) || PLANNER_TOTAL_TIMEOUT_MS;
|
|
7946
|
-
let cleanup;
|
|
7947
|
-
let settled = false;
|
|
7948
|
-
const work = () => __async(null, null, function* () {
|
|
7949
|
-
let executor = options.executor;
|
|
7950
|
-
if (!executor && datasourceUrl) {
|
|
7951
|
-
const dbConn = yield createDatabaseExecutor({
|
|
7952
|
-
databaseUrl: datasourceUrl,
|
|
7953
|
-
dialect: config.dialect,
|
|
7954
|
-
connectTimeoutMs: DB_CONNECT_TIMEOUT_MS
|
|
7955
|
-
});
|
|
7956
|
-
executor = dbConn.executor;
|
|
7957
|
-
cleanup = dbConn.cleanup;
|
|
7958
|
-
}
|
|
7959
|
-
if (!executor) return void 0;
|
|
7960
|
-
console.log("\u{1F4CA} Collecting relation cardinalities and roundtrip cost...");
|
|
7961
|
-
return yield collectPlannerArtifacts({
|
|
7962
|
-
executor,
|
|
7963
|
-
datamodel: options.datamodel,
|
|
7964
|
-
dialect: config.dialect
|
|
7965
|
-
});
|
|
7966
|
-
});
|
|
7967
|
-
const timeout = new Promise((resolve3) => {
|
|
7968
|
-
const id = setTimeout(() => {
|
|
7969
|
-
settled = true;
|
|
7970
|
-
console.warn(
|
|
7971
|
-
`\u26A0 Planner stats collection timed out after ${timeoutMs}ms, using defaults`
|
|
7972
|
-
);
|
|
7973
|
-
resolve3(void 0);
|
|
7974
|
-
}, timeoutMs);
|
|
7975
|
-
if (typeof id === "object" && "unref" in id) id.unref();
|
|
7976
|
-
});
|
|
7977
|
-
try {
|
|
7978
|
-
const result = yield Promise.race([work(), timeout]);
|
|
7979
|
-
if (settled) return void 0;
|
|
7980
|
-
return result;
|
|
7981
|
-
} catch (error) {
|
|
7982
|
-
if (!settled) {
|
|
7983
|
-
console.warn(
|
|
7984
|
-
"\u26A0 Failed to collect planner stats:",
|
|
7985
|
-
error instanceof Error ? error.message : error
|
|
7986
|
-
);
|
|
7987
|
-
}
|
|
7988
|
-
return void 0;
|
|
7989
|
-
} finally {
|
|
7990
|
-
if (cleanup) {
|
|
7991
|
-
yield cleanup().catch(() => {
|
|
7992
|
-
});
|
|
7993
|
-
}
|
|
7994
|
-
}
|
|
7995
|
-
});
|
|
7996
|
-
}
|
|
7997
7412
|
function generateImports(runtimeImportPath) {
|
|
7998
7413
|
return `import {
|
|
7999
7414
|
buildSQL,
|
|
@@ -9078,9 +8493,7 @@ generatorHelper.generatorHandler({
|
|
|
9078
8493
|
yield generateClient({
|
|
9079
8494
|
datamodel: dmmf.datamodel,
|
|
9080
8495
|
outputDir,
|
|
9081
|
-
config
|
|
9082
|
-
datasourceUrl
|
|
9083
|
-
});
|
|
8496
|
+
config});
|
|
9084
8497
|
console.info("\u2713 Generated SQL client successfully");
|
|
9085
8498
|
});
|
|
9086
8499
|
}
|