hekireki 0.20.0 → 0.20.2
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 +27 -1
- package/dist/bin/activerecord.js +1 -1
- package/dist/bin/ajv.js +1 -1
- package/dist/bin/arktype.js +1 -1
- package/dist/bin/atlas.js +1 -1
- package/dist/bin/django.js +1 -1
- package/dist/bin/drizzle.js +1 -1
- package/dist/bin/ecto.js +1 -1
- package/dist/bin/effect.js +1 -1
- package/dist/bin/eloquent.js +1 -1
- package/dist/bin/er.js +1 -1
- package/dist/bin/gorm.js +1 -1
- package/dist/bin/hekireki.js +2 -2
- package/dist/bin/kysely.js +1 -1
- package/dist/bin/pydantic.js +1 -1
- package/dist/bin/sea-orm.js +1 -1
- package/dist/bin/sqlalchemy.js +1 -1
- package/dist/bin/typebox.js +1 -1
- package/dist/bin/valibot.js +1 -1
- package/dist/bin/zod.js +1 -1
- package/dist/{bin-CPb5ZV8W.js → bin-CjbhMZs0.js} +1 -1
- package/dist/{schema-DwMNeEei.js → schema-Ci19PgR9.js} +136 -1
- package/dist/{start-Blp4k61D.js → start-EKGd2Tvk.js} +4610 -197
- package/dist/studio/assets/chip-CLdO-gL5.js +1 -0
- package/dist/studio/assets/copy-CcAufM8p.js +1 -0
- package/dist/studio/assets/debounce-T36H3Pq5.js +3 -0
- package/dist/studio/assets/dist-Ax_1vG1u.js +12 -0
- package/dist/studio/assets/docs-DW8-viIy.js +24 -0
- package/dist/studio/assets/enums._name-C2s5pbQ3.js +1 -0
- package/dist/studio/assets/hooks-Ctp_pGlY.js +1 -0
- package/dist/studio/assets/index-BP1uJf2T.js +16 -0
- package/dist/studio/assets/index-CYncH7vk.css +2 -0
- package/dist/studio/assets/labels-BXtM_faz.js +1 -0
- package/dist/studio/assets/lazyRouteComponent-C6zg30cR.js +1 -0
- package/dist/studio/assets/lu-BKd2Ee9U.js +7 -0
- package/dist/studio/assets/models._name-BgQ9M7k3.js +1 -0
- package/dist/studio/assets/not-found-OmQoujxN.js +1 -0
- package/dist/studio/assets/prisma-BbI26USq.js +891 -0
- package/dist/studio/assets/routes-Bp4Bkwc2.js +1 -0
- package/dist/studio/assets/schema-gate-Dq_XVfAD.js +1 -0
- package/dist/studio/assets/schema-view-BuWOw5GX.js +8 -0
- package/dist/studio/assets/sql--CSU_IR2.js +7 -0
- package/dist/studio/assets/table-Dfy6EciQ.js +1 -0
- package/dist/studio/assets/tabs-Ce14hvOa.js +1 -0
- package/dist/studio/assets/useFormValidation-gdk4CRGT.js +1 -0
- package/dist/studio/assets/useMatch-CdyJXF1Q.js +1 -0
- package/dist/studio/assets/useMultipleSelectionState-a9-PqoPk.js +1 -0
- package/dist/studio/assets/useOverlayTriggerState-DCPjC07T.js +1 -0
- package/dist/studio/index.html +9 -5
- package/package.json +21 -8
- package/dist/studio/assets/cells-lAj-v64A.js +0 -2
- package/dist/studio/assets/docs-CpeTt3O2.js +0 -34
- package/dist/studio/assets/enums._name-My5PypWw.js +0 -1
- package/dist/studio/assets/hooks-CiUANSpJ.js +0 -1
- package/dist/studio/assets/index-C4wWEcwe.js +0 -188
- package/dist/studio/assets/index-ZSt1ppSG.css +0 -2
- package/dist/studio/assets/labels-DBXIkmbm.js +0 -1
- package/dist/studio/assets/lazyRouteComponent-DmCXXiGp.js +0 -1
- package/dist/studio/assets/models._name-oUX64rwK.js +0 -1
- package/dist/studio/assets/not-found-DxAsuyR5.js +0 -1
- package/dist/studio/assets/prisma-Bk53qnxm.js +0 -891
- package/dist/studio/assets/routes-ZmrohHNP.js +0 -1
- package/dist/studio/assets/schema-gate-DJ_-6NYR.js +0 -1
- package/dist/studio/assets/schema-view-BaoCWAL8.js +0 -8
- package/dist/studio/assets/sql-DpzkSc6F.js +0 -1
- package/dist/studio/assets/useMatch-D73HO_WB.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as readDirectory, c as writeFile$1, n as fileSystemLayer, o as readFile, r as isDirectory, s as watch } from "./file-yN0By3gn.js";
|
|
2
2
|
import { a as FormatError, c as SchemaParseError, d as UnknownModelError, f as FORBIDDEN_HOST_MESSAGE, h as STUDIO_HOSTNAME, i as FileWriteError, l as ServerListenError, n as DatabaseError, o as InvalidInputError, p as PRISMA_FILE_URI, r as DatabaseUnavailableError, s as SchemaLoadError, t as ContractViolationError, u as UnknownFileError } from "./bin/hekireki.js";
|
|
3
|
-
import {
|
|
3
|
+
import { n as makeSchema, p as isLoopbackHostname, t as makeAnalysisSchema } from "./schema-Ci19PgR9.js";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import { Context, Duration, Effect, Layer, ManagedRuntime, Match, Option, Stream } from "effect";
|
|
6
6
|
import path from "node:path";
|
|
@@ -351,7 +351,7 @@ const Dialect$2 = z$1.enum([
|
|
|
351
351
|
description: "The SQL dialect of the connected database",
|
|
352
352
|
example: "postgresql"
|
|
353
353
|
});
|
|
354
|
-
const Cell = z$1.union([
|
|
354
|
+
const Cell$1 = z$1.union([
|
|
355
355
|
z$1.string(),
|
|
356
356
|
z$1.number(),
|
|
357
357
|
z$1.boolean(),
|
|
@@ -384,7 +384,7 @@ z$1.object({
|
|
|
384
384
|
example: false
|
|
385
385
|
})
|
|
386
386
|
}).readonly().meta({ description: "The Prisma field the value is written to." }),
|
|
387
|
-
value: Cell
|
|
387
|
+
value: Cell$1
|
|
388
388
|
}).readonly().meta({ description: "A JSON cell from the UI and the Prisma field it is written to" });
|
|
389
389
|
/** Converts a JSON cell into the value the driver binds for the field type and dialect. */
|
|
390
390
|
function makeDbValue(input) {
|
|
@@ -398,196 +398,3996 @@ function makeDbValue(input) {
|
|
|
398
398
|
return value;
|
|
399
399
|
}
|
|
400
400
|
}
|
|
401
|
-
if (field.kind === "enum") return String(value);
|
|
402
|
-
switch (field.type) {
|
|
403
|
-
case "Int":
|
|
404
|
-
case "Float": {
|
|
405
|
-
if (typeof value === "number") return value;
|
|
406
|
-
if (typeof value === "boolean") return value ? 1 : 0;
|
|
407
|
-
const parsed = Number(value);
|
|
408
|
-
return Number.isNaN(parsed) ? value : parsed;
|
|
401
|
+
if (field.kind === "enum") return String(value);
|
|
402
|
+
switch (field.type) {
|
|
403
|
+
case "Int":
|
|
404
|
+
case "Float": {
|
|
405
|
+
if (typeof value === "number") return value;
|
|
406
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
407
|
+
const parsed = Number(value);
|
|
408
|
+
return Number.isNaN(parsed) ? value : parsed;
|
|
409
|
+
}
|
|
410
|
+
case "BigInt":
|
|
411
|
+
case "Decimal": return String(value);
|
|
412
|
+
case "Boolean": {
|
|
413
|
+
const flag = typeof value === "boolean" ? value : typeof value === "number" ? value !== 0 : value === "true" || value === "1";
|
|
414
|
+
return dialect === "sqlite" ? flag ? 1 : 0 : flag;
|
|
415
|
+
}
|
|
416
|
+
case "DateTime": return dialect === "sqlite" ? String(value) : new Date(String(value));
|
|
417
|
+
case "Bytes": return Buffer.from(String(value), "base64");
|
|
418
|
+
default: return String(value);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
z$1.object({
|
|
422
|
+
row: z$1.record(z$1.string(), z$1.unknown()).readonly().meta({ description: "The driver row keyed by column." }),
|
|
423
|
+
columnToField: z$1.map(z$1.string(), z$1.string()).meta({ description: "Column name to Prisma field name." }),
|
|
424
|
+
columnToEnum: z$1.map(z$1.string(), z$1.map(z$1.string(), z$1.string())).optional().meta({ description: "Column name to the Prisma name of each stored enum value." })
|
|
425
|
+
}).readonly().meta({ description: "A driver row and the column → field name mapping" });
|
|
426
|
+
/** Renames columns back to field names, maps `@map`ped enum values back, and serializes every cell. */
|
|
427
|
+
function makeRow(input) {
|
|
428
|
+
return Object.fromEntries(Object.entries(input.row).map(([column, value]) => {
|
|
429
|
+
const named = typeof value === "string" ? input.columnToEnum?.get(column)?.get(value) ?? value : value;
|
|
430
|
+
return [input.columnToField.get(column) ?? column, makeCell({ value: named })];
|
|
431
|
+
}));
|
|
432
|
+
}
|
|
433
|
+
z$1.object({
|
|
434
|
+
dialect: Dialect$2,
|
|
435
|
+
value: Cell$1
|
|
436
|
+
}).readonly().meta({
|
|
437
|
+
description: "A parameter value from the client and the dialect it is bound for",
|
|
438
|
+
example: {
|
|
439
|
+
dialect: "sqlite",
|
|
440
|
+
value: 1
|
|
441
|
+
}
|
|
442
|
+
});
|
|
443
|
+
/** The driver value for a JSON parameter: SQLite has no booleans, so they bind as 0 / 1. */
|
|
444
|
+
function makeBindValue(input) {
|
|
445
|
+
if (typeof input.value === "boolean" && input.dialect === "sqlite") return input.value ? 1 : 0;
|
|
446
|
+
return input.value;
|
|
447
|
+
}
|
|
448
|
+
//#endregion
|
|
449
|
+
//#region src/studio/server/domain/model.ts
|
|
450
|
+
const Model = z$1.object({
|
|
451
|
+
name: z$1.string().meta({
|
|
452
|
+
description: "The model name as declared.",
|
|
453
|
+
example: "User"
|
|
454
|
+
}),
|
|
455
|
+
dbName: z$1.string().nullable().meta({
|
|
456
|
+
description: "The @@map table name, when set.",
|
|
457
|
+
example: "users"
|
|
458
|
+
}),
|
|
459
|
+
primaryKey: z$1.array(z$1.string()).readonly().nullable().meta({ description: "The fields of a composite @@id, when the model has one." }),
|
|
460
|
+
fields: z$1.array(z$1.object({
|
|
461
|
+
name: z$1.string().meta({
|
|
462
|
+
description: "The Prisma field name.",
|
|
463
|
+
example: "createdAt"
|
|
464
|
+
}),
|
|
465
|
+
dbName: z$1.string().nullable().meta({
|
|
466
|
+
description: "The @map column name, when set.",
|
|
467
|
+
example: "created_at"
|
|
468
|
+
}),
|
|
469
|
+
kind: z$1.string().meta({
|
|
470
|
+
description: "scalar, object, enum or unsupported.",
|
|
471
|
+
example: "scalar"
|
|
472
|
+
}),
|
|
473
|
+
type: z$1.string().meta({
|
|
474
|
+
description: "The declared type.",
|
|
475
|
+
example: "DateTime"
|
|
476
|
+
}),
|
|
477
|
+
isList: z$1.boolean().meta({
|
|
478
|
+
description: "Whether the field is a list.",
|
|
479
|
+
example: false
|
|
480
|
+
}),
|
|
481
|
+
isId: z$1.boolean().meta({
|
|
482
|
+
description: "Whether the field is @id.",
|
|
483
|
+
example: false
|
|
484
|
+
}),
|
|
485
|
+
isUnique: z$1.boolean().meta({
|
|
486
|
+
description: "Whether the field is @unique.",
|
|
487
|
+
example: false
|
|
488
|
+
})
|
|
489
|
+
}).readonly()).readonly().meta({ description: "The fields of the model, relations included." })
|
|
490
|
+
}).readonly().meta({ description: "The part of a Studio model the SQL builders read" });
|
|
491
|
+
const Dialect$1 = z$1.enum([
|
|
492
|
+
"postgresql",
|
|
493
|
+
"mysql",
|
|
494
|
+
"sqlite"
|
|
495
|
+
]).meta({
|
|
496
|
+
description: "The SQL dialect of the connected database",
|
|
497
|
+
example: "postgresql"
|
|
498
|
+
});
|
|
499
|
+
const Row = z$1.record(z$1.string(), z$1.union([
|
|
500
|
+
z$1.string(),
|
|
501
|
+
z$1.number(),
|
|
502
|
+
z$1.boolean(),
|
|
503
|
+
z$1.null()
|
|
504
|
+
])).readonly().meta({ description: "A row keyed by Prisma field name" });
|
|
505
|
+
const Enums = z$1.array(z$1.object({
|
|
506
|
+
name: z$1.string().meta({
|
|
507
|
+
description: "The enum name as declared.",
|
|
508
|
+
example: "Role"
|
|
509
|
+
}),
|
|
510
|
+
values: z$1.array(z$1.object({
|
|
511
|
+
name: z$1.string().meta({
|
|
512
|
+
description: "The member name as declared.",
|
|
513
|
+
example: "ADMIN"
|
|
514
|
+
}),
|
|
515
|
+
dbName: z$1.string().nullable().meta({
|
|
516
|
+
description: "The @map stored value, when set.",
|
|
517
|
+
example: "admin"
|
|
518
|
+
})
|
|
519
|
+
}).readonly()).readonly().meta({ description: "The members of the enum." })
|
|
520
|
+
}).readonly()).readonly().meta({ description: "The schema enums, whose members may be `@map`ped to other names" });
|
|
521
|
+
z$1.object({ model: Model }).readonly().meta({ description: "A studio model" });
|
|
522
|
+
/** The scalar and enum fields, i.e. the table columns. */
|
|
523
|
+
function tableColumns(input) {
|
|
524
|
+
return input.model.fields.filter((f) => f.kind !== "object");
|
|
525
|
+
}
|
|
526
|
+
z$1.object({ field: z$1.object({
|
|
527
|
+
name: z$1.string().meta({
|
|
528
|
+
description: "The Prisma field name.",
|
|
529
|
+
example: "createdAt"
|
|
530
|
+
}),
|
|
531
|
+
dbName: z$1.string().nullable().meta({
|
|
532
|
+
description: "The @map column name, when set.",
|
|
533
|
+
example: "created_at"
|
|
534
|
+
})
|
|
535
|
+
}).readonly().meta({ description: "The field to name a column for." }) }).readonly().meta({ description: "A field with its optional @map name" });
|
|
536
|
+
/** The database column of a field: `@map` when present, else the field name. */
|
|
537
|
+
function columnName(input) {
|
|
538
|
+
return input.field.dbName ?? input.field.name;
|
|
539
|
+
}
|
|
540
|
+
z$1.object({ model: Model }).readonly().meta({ description: "A studio model" });
|
|
541
|
+
/** The fields that identify a row: `@@id`, then `@id`, then the first `@unique`; empty means read-only. */
|
|
542
|
+
function keyFields(input) {
|
|
543
|
+
const { model } = input;
|
|
544
|
+
const composite = model.primaryKey ?? [];
|
|
545
|
+
if (composite.length > 0) return composite;
|
|
546
|
+
const id = model.fields.find((f) => f.isId);
|
|
547
|
+
if (id) return [id.name];
|
|
548
|
+
const unique = model.fields.find((f) => f.isUnique && f.kind !== "object");
|
|
549
|
+
return unique ? [unique.name] : [];
|
|
550
|
+
}
|
|
551
|
+
z$1.object({ model: Model }).readonly().meta({ description: "A studio model" });
|
|
552
|
+
/** The database table of a model: `@@map` when present, else the model name. */
|
|
553
|
+
function tableName(input) {
|
|
554
|
+
return input.model.dbName ?? input.model.name;
|
|
555
|
+
}
|
|
556
|
+
/** The stored name of every member of an enum: its `@map`, else the member name. */
|
|
557
|
+
function memberNames(enums, type) {
|
|
558
|
+
return (enums.find((e) => e.name === type)?.values ?? []).map((value) => ({
|
|
559
|
+
name: value.name,
|
|
560
|
+
dbName: value.dbName ?? value.name
|
|
561
|
+
}));
|
|
562
|
+
}
|
|
563
|
+
z$1.object({
|
|
564
|
+
model: Model,
|
|
565
|
+
enums: Enums
|
|
566
|
+
}).readonly().meta({ description: "A model and the schema enums its fields may refer to" });
|
|
567
|
+
/**
|
|
568
|
+
* Per column, the stored value of each enum member by its Prisma name, for the enum fields whose
|
|
569
|
+
* members are `@map`ped. Writing `PUBLIC` into a column that holds `public` is a type error in
|
|
570
|
+
* PostgreSQL and a silent truncation in MySQL, so the value is translated on its way in.
|
|
571
|
+
*/
|
|
572
|
+
function makeEnumWriteValues(input) {
|
|
573
|
+
return new Map(tableColumns({ model: input.model }).filter((field) => field.kind === "enum").map((field) => [field.name, new Map(memberNames(input.enums, field.type).map((v) => [v.name, v.dbName]))]));
|
|
574
|
+
}
|
|
575
|
+
z$1.object({
|
|
576
|
+
model: Model,
|
|
577
|
+
enums: Enums
|
|
578
|
+
}).readonly().meta({ description: "A model and the schema enums its fields may refer to" });
|
|
579
|
+
/** Per column, the Prisma name of each enum member by its stored value, for reading rows back. */
|
|
580
|
+
function makeEnumReadValues(input) {
|
|
581
|
+
return new Map(tableColumns({ model: input.model }).filter((field) => field.kind === "enum").map((field) => [columnName({ field }), new Map(memberNames(input.enums, field.type).map((v) => [v.dbName, v.name]))]));
|
|
582
|
+
}
|
|
583
|
+
z$1.object({
|
|
584
|
+
model: Model,
|
|
585
|
+
dialect: Dialect$1,
|
|
586
|
+
row: Row,
|
|
587
|
+
enums: Enums.optional()
|
|
588
|
+
}).readonly().meta({ description: "A row keyed by field name to translate into column values" });
|
|
589
|
+
/** Maps `{ fieldName: cell }` from the UI to `{ columnName: driverValue }` for the database. */
|
|
590
|
+
function makeColumnValues(input) {
|
|
591
|
+
const fields = tableColumns({ model: input.model });
|
|
592
|
+
const enumValues = makeEnumWriteValues({
|
|
593
|
+
model: input.model,
|
|
594
|
+
enums: input.enums ?? []
|
|
595
|
+
});
|
|
596
|
+
return Object.fromEntries(Object.entries(input.row).flatMap(([name, value]) => {
|
|
597
|
+
const field = fields.find((f) => f.name === name);
|
|
598
|
+
if (!field) return [];
|
|
599
|
+
const stored = typeof value === "string" ? enumValues.get(name)?.get(value) ?? value : value;
|
|
600
|
+
return [[columnName({ field }), makeDbValue({
|
|
601
|
+
dialect: input.dialect,
|
|
602
|
+
field,
|
|
603
|
+
value: stored
|
|
604
|
+
})]];
|
|
605
|
+
}));
|
|
606
|
+
}
|
|
607
|
+
//#endregion
|
|
608
|
+
//#region src/studio/server/domain/plan.ts
|
|
609
|
+
z$1.object({
|
|
610
|
+
id: z$1.string().meta({
|
|
611
|
+
description: "The step id.",
|
|
612
|
+
example: "3"
|
|
613
|
+
}),
|
|
614
|
+
parent: z$1.string().nullable().meta({
|
|
615
|
+
description: "The parent step id.",
|
|
616
|
+
example: null
|
|
617
|
+
}),
|
|
618
|
+
label: z$1.string().meta({
|
|
619
|
+
description: "What the step does.",
|
|
620
|
+
example: "SCAN users"
|
|
621
|
+
}),
|
|
622
|
+
detail: z$1.string().nullable().meta({
|
|
623
|
+
description: "The rest of the line.",
|
|
624
|
+
example: null
|
|
625
|
+
}),
|
|
626
|
+
cost: z$1.number().nullable().meta({
|
|
627
|
+
description: "The estimated cost.",
|
|
628
|
+
example: null
|
|
629
|
+
}),
|
|
630
|
+
rows: z$1.number().nullable().meta({
|
|
631
|
+
description: "The estimated rows.",
|
|
632
|
+
example: null
|
|
633
|
+
})
|
|
634
|
+
}).meta({ description: "One step of an execution plan, flattened" });
|
|
635
|
+
const SqliteRow = z$1.object({
|
|
636
|
+
id: z$1.coerce.number().meta({
|
|
637
|
+
description: "The step id.",
|
|
638
|
+
example: 3
|
|
639
|
+
}),
|
|
640
|
+
parent: z$1.coerce.number().meta({
|
|
641
|
+
description: "The parent step id, 0 for a root.",
|
|
642
|
+
example: 0
|
|
643
|
+
}),
|
|
644
|
+
detail: z$1.string().meta({
|
|
645
|
+
description: "What the step does.",
|
|
646
|
+
example: "SCAN users"
|
|
647
|
+
})
|
|
648
|
+
}).meta({ description: "A row of EXPLAIN QUERY PLAN" });
|
|
649
|
+
z$1.object({ rows: z$1.array(z$1.record(z$1.string(), z$1.unknown())).readonly().meta({ description: "The rows EXPLAIN QUERY PLAN returned." }) }).readonly().meta({ description: "The output of SQLite EXPLAIN QUERY PLAN" });
|
|
650
|
+
/** SQLite's `EXPLAIN QUERY PLAN` rows: `id`, `parent` (0 for a root) and `detail`. */
|
|
651
|
+
function makeSqlitePlan(input) {
|
|
652
|
+
const rows = input.rows.flatMap((row) => {
|
|
653
|
+
const parsed = SqliteRow.safeParse(row);
|
|
654
|
+
return parsed.success ? [parsed.data] : [];
|
|
655
|
+
});
|
|
656
|
+
const ids = new Set(rows.map((row) => row.id));
|
|
657
|
+
return {
|
|
658
|
+
nodes: rows.map((row) => ({
|
|
659
|
+
id: String(row.id),
|
|
660
|
+
parent: row.parent === 0 || !ids.has(row.parent) ? null : String(row.parent),
|
|
661
|
+
label: row.detail,
|
|
662
|
+
detail: null,
|
|
663
|
+
cost: null,
|
|
664
|
+
rows: null
|
|
665
|
+
})),
|
|
666
|
+
raw: rows.map((row) => `${" ".repeat(depthOf(rows, row.id))}${row.detail}`).join("\n")
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
function depthOf(rows, id) {
|
|
670
|
+
const row = rows.find((candidate) => candidate.id === id);
|
|
671
|
+
if (row === void 0 || row.parent === 0) return 0;
|
|
672
|
+
return 1 + depthOf(rows, row.parent);
|
|
673
|
+
}
|
|
674
|
+
const PostgresPlan = z$1.object({
|
|
675
|
+
"Node Type": z$1.string().meta({
|
|
676
|
+
description: "The operator.",
|
|
677
|
+
example: "Seq Scan"
|
|
678
|
+
}),
|
|
679
|
+
"Relation Name": z$1.string().optional().meta({
|
|
680
|
+
description: "The table.",
|
|
681
|
+
example: "users"
|
|
682
|
+
}),
|
|
683
|
+
Alias: z$1.string().optional().meta({
|
|
684
|
+
description: "The alias.",
|
|
685
|
+
example: "u"
|
|
686
|
+
}),
|
|
687
|
+
"Index Name": z$1.string().optional().meta({
|
|
688
|
+
description: "The index.",
|
|
689
|
+
example: "users_pkey"
|
|
690
|
+
}),
|
|
691
|
+
"Join Type": z$1.string().optional().meta({
|
|
692
|
+
description: "Inner, Left, ...",
|
|
693
|
+
example: "Inner"
|
|
694
|
+
}),
|
|
695
|
+
"Total Cost": z$1.number().optional().meta({
|
|
696
|
+
description: "The estimated cost.",
|
|
697
|
+
example: 1.5
|
|
698
|
+
}),
|
|
699
|
+
"Plan Rows": z$1.number().optional().meta({
|
|
700
|
+
description: "The estimated rows.",
|
|
701
|
+
example: 10
|
|
702
|
+
}),
|
|
703
|
+
"Actual Rows": z$1.number().optional().meta({
|
|
704
|
+
description: "The rows seen.",
|
|
705
|
+
example: 10
|
|
706
|
+
}),
|
|
707
|
+
Filter: z$1.string().optional().meta({
|
|
708
|
+
description: "The filter.",
|
|
709
|
+
example: "(id = 1)"
|
|
710
|
+
}),
|
|
711
|
+
"Join Filter": z$1.string().optional().meta({
|
|
712
|
+
description: "The join filter.",
|
|
713
|
+
example: ""
|
|
714
|
+
}),
|
|
715
|
+
"Hash Cond": z$1.string().optional().meta({
|
|
716
|
+
description: "The hash condition.",
|
|
717
|
+
example: ""
|
|
718
|
+
}),
|
|
719
|
+
"Merge Cond": z$1.string().optional().meta({
|
|
720
|
+
description: "The merge condition.",
|
|
721
|
+
example: ""
|
|
722
|
+
}),
|
|
723
|
+
"Index Cond": z$1.string().optional().meta({
|
|
724
|
+
description: "The index condition.",
|
|
725
|
+
example: ""
|
|
726
|
+
}),
|
|
727
|
+
"Sort Key": z$1.array(z$1.string()).optional().meta({ description: "The sort keys." }),
|
|
728
|
+
"Group Key": z$1.array(z$1.string()).optional().meta({ description: "The group keys." }),
|
|
729
|
+
"CTE Name": z$1.string().optional().meta({
|
|
730
|
+
description: "The CTE.",
|
|
731
|
+
example: "c"
|
|
732
|
+
}),
|
|
733
|
+
"Subplan Name": z$1.string().optional().meta({
|
|
734
|
+
description: "The subplan.",
|
|
735
|
+
example: ""
|
|
736
|
+
}),
|
|
737
|
+
Plans: z$1.array(z$1.unknown()).optional().meta({ description: "The child plans." })
|
|
738
|
+
}).meta({ description: "One node of PostgreSQL EXPLAIN (FORMAT JSON)" });
|
|
739
|
+
const PostgresRoot = z$1.array(z$1.object({ Plan: z$1.unknown().meta({ description: "The root plan." }) })).meta({ description: "The document EXPLAIN (FORMAT JSON) returns" });
|
|
740
|
+
function postgresDetail(plan) {
|
|
741
|
+
const parts = [
|
|
742
|
+
plan["Index Name"] === void 0 ? null : `using ${plan["Index Name"]}`,
|
|
743
|
+
plan["Index Cond"] === void 0 ? null : `Index Cond: ${plan["Index Cond"]}`,
|
|
744
|
+
plan["Hash Cond"] === void 0 ? null : `Hash Cond: ${plan["Hash Cond"]}`,
|
|
745
|
+
plan["Merge Cond"] === void 0 ? null : `Merge Cond: ${plan["Merge Cond"]}`,
|
|
746
|
+
plan["Join Filter"] === void 0 ? null : `Join Filter: ${plan["Join Filter"]}`,
|
|
747
|
+
plan.Filter === void 0 ? null : `Filter: ${plan.Filter}`,
|
|
748
|
+
plan["Sort Key"] === void 0 ? null : `Sort Key: ${plan["Sort Key"].join(", ")}`,
|
|
749
|
+
plan["Group Key"] === void 0 ? null : `Group Key: ${plan["Group Key"].join(", ")}`
|
|
750
|
+
].filter((part) => part !== null);
|
|
751
|
+
return parts.length === 0 ? null : parts.join(" · ");
|
|
752
|
+
}
|
|
753
|
+
function flattenPostgres(value, parent, id) {
|
|
754
|
+
const parsed = PostgresPlan.safeParse(value);
|
|
755
|
+
if (!parsed.success) return [];
|
|
756
|
+
const plan = parsed.data;
|
|
757
|
+
const target = plan["Relation Name"] ?? plan["CTE Name"];
|
|
758
|
+
const alias = plan.Alias !== void 0 && plan.Alias !== target ? ` ${plan.Alias}` : "";
|
|
759
|
+
const join = plan["Join Type"] === void 0 ? "" : ` (${plan["Join Type"]})`;
|
|
760
|
+
const label = `${plan["Node Type"]}${target === void 0 ? "" : ` on ${target}${alias}`}${join}`;
|
|
761
|
+
return [{
|
|
762
|
+
id,
|
|
763
|
+
parent,
|
|
764
|
+
label: plan["Subplan Name"] === void 0 ? label : `${plan["Subplan Name"]}: ${label}`,
|
|
765
|
+
detail: postgresDetail(plan),
|
|
766
|
+
cost: plan["Total Cost"] ?? null,
|
|
767
|
+
rows: plan["Actual Rows"] ?? plan["Plan Rows"] ?? null
|
|
768
|
+
}, ...(plan.Plans ?? []).flatMap((child, index) => flattenPostgres(child, id, `${id}.${index + 1}`))];
|
|
769
|
+
}
|
|
770
|
+
z$1.object({ document: z$1.unknown().meta({ description: "The JSON document of the QUERY PLAN column." }) }).readonly().meta({ description: "The output of PostgreSQL EXPLAIN (FORMAT JSON)" });
|
|
771
|
+
/** PostgreSQL's `EXPLAIN (FORMAT JSON)`: a tree of `Plan` objects, flattened parents-first. */
|
|
772
|
+
function makePostgresPlan(input) {
|
|
773
|
+
const document = typeof input.document === "string" ? parseJson(input.document) : input.document;
|
|
774
|
+
const root = PostgresRoot.safeParse(document);
|
|
775
|
+
return {
|
|
776
|
+
nodes: root.success ? root.data.flatMap((entry, index) => flattenPostgres(entry.Plan, null, String(index + 1))) : [],
|
|
777
|
+
raw: JSON.stringify(document, null, 2)
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
function parseJson(text) {
|
|
781
|
+
try {
|
|
782
|
+
return JSON.parse(text);
|
|
783
|
+
} catch {
|
|
784
|
+
return null;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
const MysqlTable = z$1.object({
|
|
788
|
+
table_name: z$1.string().meta({
|
|
789
|
+
description: "The table.",
|
|
790
|
+
example: "users"
|
|
791
|
+
}),
|
|
792
|
+
access_type: z$1.string().optional().meta({
|
|
793
|
+
description: "The access type.",
|
|
794
|
+
example: "ALL"
|
|
795
|
+
}),
|
|
796
|
+
key: z$1.string().optional().meta({
|
|
797
|
+
description: "The index used.",
|
|
798
|
+
example: "PRIMARY"
|
|
799
|
+
}),
|
|
800
|
+
rows_examined_per_scan: z$1.number().optional().meta({
|
|
801
|
+
description: "Rows per scan.",
|
|
802
|
+
example: 3
|
|
803
|
+
}),
|
|
804
|
+
rows_produced_per_join: z$1.number().optional().meta({
|
|
805
|
+
description: "Rows produced.",
|
|
806
|
+
example: 3
|
|
807
|
+
}),
|
|
808
|
+
attached_condition: z$1.string().optional().meta({
|
|
809
|
+
description: "The condition.",
|
|
810
|
+
example: ""
|
|
811
|
+
}),
|
|
812
|
+
cost_info: z$1.object({
|
|
813
|
+
read_cost: z$1.string().optional().meta({
|
|
814
|
+
description: "Read cost.",
|
|
815
|
+
example: "1"
|
|
816
|
+
}),
|
|
817
|
+
prefix_cost: z$1.string().optional().meta({
|
|
818
|
+
description: "Prefix cost.",
|
|
819
|
+
example: "1"
|
|
820
|
+
})
|
|
821
|
+
}).optional().meta({ description: "The cost figures." })
|
|
822
|
+
}).meta({ description: "A `table` entry of MySQL EXPLAIN FORMAT=JSON" });
|
|
823
|
+
const MysqlBlock = z$1.object({
|
|
824
|
+
select_id: z$1.number().optional().meta({
|
|
825
|
+
description: "The select id.",
|
|
826
|
+
example: 1
|
|
827
|
+
}),
|
|
828
|
+
cost_info: z$1.object({ query_cost: z$1.string().optional().meta({
|
|
829
|
+
description: "The query cost.",
|
|
830
|
+
example: "1"
|
|
831
|
+
}) }).optional().meta({ description: "The cost figures." }),
|
|
832
|
+
message: z$1.string().optional().meta({
|
|
833
|
+
description: "A note instead of a plan.",
|
|
834
|
+
example: ""
|
|
835
|
+
})
|
|
836
|
+
}).meta({ description: "A `query_block` entry of MySQL EXPLAIN FORMAT=JSON" });
|
|
837
|
+
const MYSQL_OPERATIONS = /* @__PURE__ */ new Set([
|
|
838
|
+
"ordering_operation",
|
|
839
|
+
"grouping_operation",
|
|
840
|
+
"duplicates_removal",
|
|
841
|
+
"windowing",
|
|
842
|
+
"nested_loop",
|
|
843
|
+
"table",
|
|
844
|
+
"query_block",
|
|
845
|
+
"materialized_from_subquery",
|
|
846
|
+
"union_result",
|
|
847
|
+
"query_specifications",
|
|
848
|
+
"subqueries",
|
|
849
|
+
"optimized_away_subqueries",
|
|
850
|
+
"attached_subqueries",
|
|
851
|
+
"buffer_result"
|
|
852
|
+
]);
|
|
853
|
+
function flattenMysql(value, parent, id, key) {
|
|
854
|
+
if (Array.isArray(value)) return [{
|
|
855
|
+
id,
|
|
856
|
+
parent,
|
|
857
|
+
label: key.replaceAll("_", " "),
|
|
858
|
+
detail: null,
|
|
859
|
+
cost: null,
|
|
860
|
+
rows: null
|
|
861
|
+
}, ...value.flatMap((item, index) => childrenOfMysql(item, id, `${id}.${index + 1}`))];
|
|
862
|
+
if (typeof value !== "object" || value === null) return [];
|
|
863
|
+
const record = z$1.record(z$1.string(), z$1.unknown()).parse(value);
|
|
864
|
+
if (key === "table") {
|
|
865
|
+
const table = MysqlTable.safeParse(record);
|
|
866
|
+
if (!table.success) return [];
|
|
867
|
+
const parts = [table.data.key === void 0 ? null : `key ${table.data.key}`, table.data.attached_condition ?? null].filter((part) => part !== null);
|
|
868
|
+
return [{
|
|
869
|
+
id,
|
|
870
|
+
parent,
|
|
871
|
+
label: `${table.data.access_type ?? "scan"} ${table.data.table_name}`,
|
|
872
|
+
detail: parts.length === 0 ? null : parts.join(" · "),
|
|
873
|
+
cost: Number(table.data.cost_info?.prefix_cost ?? table.data.cost_info?.read_cost ?? NaN) || null,
|
|
874
|
+
rows: table.data.rows_produced_per_join ?? table.data.rows_examined_per_scan ?? null
|
|
875
|
+
}, ...childrenOfMysql(record, id, id)];
|
|
876
|
+
}
|
|
877
|
+
if (key === "query_block") {
|
|
878
|
+
const block = MysqlBlock.safeParse(record);
|
|
879
|
+
return [{
|
|
880
|
+
id,
|
|
881
|
+
parent,
|
|
882
|
+
label: block.success && block.data.select_id !== void 0 ? `query block #${block.data.select_id}` : "query block",
|
|
883
|
+
detail: block.success ? block.data.message ?? null : null,
|
|
884
|
+
cost: block.success ? Number(block.data.cost_info?.query_cost ?? NaN) || null : null,
|
|
885
|
+
rows: null
|
|
886
|
+
}, ...childrenOfMysql(record, id, id)];
|
|
887
|
+
}
|
|
888
|
+
if (MYSQL_OPERATIONS.has(key)) return [{
|
|
889
|
+
id,
|
|
890
|
+
parent,
|
|
891
|
+
label: key.replaceAll("_", " "),
|
|
892
|
+
detail: null,
|
|
893
|
+
cost: null,
|
|
894
|
+
rows: null
|
|
895
|
+
}, ...childrenOfMysql(record, id, id)];
|
|
896
|
+
return childrenOfMysql(record, parent, id);
|
|
897
|
+
}
|
|
898
|
+
/** The operations nested in an object, numbered under `base` (`1.2` → `1.2.1`, `1.2.2`, ...). */
|
|
899
|
+
function childrenOfMysql(value, parent, base) {
|
|
900
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return [];
|
|
901
|
+
const record = z$1.record(z$1.string(), z$1.unknown()).parse(value);
|
|
902
|
+
return Object.entries(record).filter(([key, child]) => typeof child === "object" && child !== null && MYSQL_OPERATIONS.has(key)).flatMap(([key, child], index) => flattenMysql(child, parent, base === "" ? String(index + 1) : `${base}.${index + 1}`, key));
|
|
903
|
+
}
|
|
904
|
+
z$1.object({ document: z$1.unknown().meta({ description: "The JSON document of the EXPLAIN column." }) }).readonly().meta({ description: "The output of MySQL EXPLAIN FORMAT=JSON" });
|
|
905
|
+
/** MySQL's `EXPLAIN FORMAT=JSON`: nested operation objects, flattened parents-first. */
|
|
906
|
+
function makeMysqlPlan(input) {
|
|
907
|
+
const document = typeof input.document === "string" ? parseJson(input.document) : input.document;
|
|
908
|
+
return {
|
|
909
|
+
nodes: childrenOfMysql(document, null, ""),
|
|
910
|
+
raw: JSON.stringify(document, null, 2)
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
//#endregion
|
|
914
|
+
//#region src/sql/tokenize.ts
|
|
915
|
+
const OPERATORS = [
|
|
916
|
+
"->>",
|
|
917
|
+
"#>>",
|
|
918
|
+
"!~*",
|
|
919
|
+
"<=>",
|
|
920
|
+
"||",
|
|
921
|
+
"::",
|
|
922
|
+
"->",
|
|
923
|
+
"#>",
|
|
924
|
+
"@>",
|
|
925
|
+
"<@",
|
|
926
|
+
"<>",
|
|
927
|
+
"!=",
|
|
928
|
+
"<=",
|
|
929
|
+
">=",
|
|
930
|
+
"~*",
|
|
931
|
+
"!~",
|
|
932
|
+
"<<",
|
|
933
|
+
">>",
|
|
934
|
+
"**",
|
|
935
|
+
"+",
|
|
936
|
+
"-",
|
|
937
|
+
"*",
|
|
938
|
+
"/",
|
|
939
|
+
"%",
|
|
940
|
+
"<",
|
|
941
|
+
">",
|
|
942
|
+
"=",
|
|
943
|
+
"~",
|
|
944
|
+
"^",
|
|
945
|
+
"&",
|
|
946
|
+
"|",
|
|
947
|
+
"!",
|
|
948
|
+
"#"
|
|
949
|
+
];
|
|
950
|
+
const PUNCTUATION = /* @__PURE__ */ new Set([
|
|
951
|
+
"(",
|
|
952
|
+
")",
|
|
953
|
+
",",
|
|
954
|
+
";",
|
|
955
|
+
".",
|
|
956
|
+
"[",
|
|
957
|
+
"]"
|
|
958
|
+
]);
|
|
959
|
+
const WORD_START = /[A-Za-z_À-]/u;
|
|
960
|
+
const WORD_CHAR = /[A-Za-z0-9_$À-]/u;
|
|
961
|
+
const NUMBER = /^(?:0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)/u;
|
|
962
|
+
const DOLLAR_TAG = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/u;
|
|
963
|
+
function isWordStart(char) {
|
|
964
|
+
return WORD_START.test(char);
|
|
965
|
+
}
|
|
966
|
+
function isWordChar(char) {
|
|
967
|
+
return WORD_CHAR.test(char);
|
|
968
|
+
}
|
|
969
|
+
function isDigit(char) {
|
|
970
|
+
return char >= "0" && char <= "9";
|
|
971
|
+
}
|
|
972
|
+
function isSpace(char) {
|
|
973
|
+
return char === " " || char === "\n" || char === " " || char === "\r" || char === "\f";
|
|
974
|
+
}
|
|
975
|
+
/** The end of a delimited run (`'...'` with `''` escapes, `"..."`, backticks, `[...]`); null when unterminated. */
|
|
976
|
+
function readDelimited(text, from, close, doubled) {
|
|
977
|
+
for (let at = from + 1; at < text.length; at += 1) if (text[at] === close) {
|
|
978
|
+
if (doubled && text[at + 1] === close) at += 1;
|
|
979
|
+
else return at + 1;
|
|
980
|
+
}
|
|
981
|
+
return null;
|
|
982
|
+
}
|
|
983
|
+
function readNumber(text, from) {
|
|
984
|
+
return from + (NUMBER.exec(text.slice(from))?.[0] ?? "").length;
|
|
985
|
+
}
|
|
986
|
+
function readWord(text, from) {
|
|
987
|
+
let at = from;
|
|
988
|
+
while (at < text.length && isWordChar(text[at] ?? "")) at += 1;
|
|
989
|
+
return at;
|
|
990
|
+
}
|
|
991
|
+
/** `$$...$$` or `$tag$...$tag$`: PostgreSQL's dollar quoting. Null when this `$` is not one. */
|
|
992
|
+
function readDollarQuoted(text, from) {
|
|
993
|
+
const tag = DOLLAR_TAG.exec(text.slice(from))?.[0];
|
|
994
|
+
if (tag === void 0) return null;
|
|
995
|
+
const close = text.indexOf(tag, from + tag.length);
|
|
996
|
+
return close === -1 ? null : {
|
|
997
|
+
end: close + tag.length,
|
|
998
|
+
tag
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
1001
|
+
function unquote(raw, close, doubled) {
|
|
1002
|
+
const inner = raw.slice(1, -1);
|
|
1003
|
+
return doubled ? inner.replaceAll(close + close, close) : inner;
|
|
1004
|
+
}
|
|
1005
|
+
/** Whether a `[` opens a quoted identifier (`[name]`) rather than subscripting the expression before it. */
|
|
1006
|
+
function isBracketIdentifier(previous) {
|
|
1007
|
+
if (previous === null) return true;
|
|
1008
|
+
if (previous.kind === "word" || previous.kind === "quoted" || previous.kind === "param") return false;
|
|
1009
|
+
return previous.raw !== ")" && previous.raw !== "]";
|
|
1010
|
+
}
|
|
1011
|
+
function token(kind, raw, text, start, end) {
|
|
1012
|
+
return {
|
|
1013
|
+
token: {
|
|
1014
|
+
kind,
|
|
1015
|
+
raw,
|
|
1016
|
+
text,
|
|
1017
|
+
start,
|
|
1018
|
+
end
|
|
1019
|
+
},
|
|
1020
|
+
next: end
|
|
1021
|
+
};
|
|
1022
|
+
}
|
|
1023
|
+
function step(text, at, previous) {
|
|
1024
|
+
const char = text[at] ?? "";
|
|
1025
|
+
if (isSpace(char)) return { skip: at + 1 };
|
|
1026
|
+
if (char === "-" && text[at + 1] === "-") {
|
|
1027
|
+
const end = text.indexOf("\n", at);
|
|
1028
|
+
return { skip: end === -1 ? text.length : end + 1 };
|
|
1029
|
+
}
|
|
1030
|
+
if (char === "/" && text[at + 1] === "*") {
|
|
1031
|
+
const end = text.indexOf("*/", at + 2);
|
|
1032
|
+
if (end === -1) return { error: {
|
|
1033
|
+
message: "Unterminated block comment",
|
|
1034
|
+
offset: at
|
|
1035
|
+
} };
|
|
1036
|
+
return { skip: end + 2 };
|
|
1037
|
+
}
|
|
1038
|
+
if (char === "'") {
|
|
1039
|
+
const end = readDelimited(text, at, "'", true);
|
|
1040
|
+
if (end === null) return { error: {
|
|
1041
|
+
message: "Unterminated string literal",
|
|
1042
|
+
offset: at
|
|
1043
|
+
} };
|
|
1044
|
+
const raw = text.slice(at, end);
|
|
1045
|
+
return token("string", raw, unquote(raw, "'", true), at, end);
|
|
1046
|
+
}
|
|
1047
|
+
if (char === "\"" || char === "`") {
|
|
1048
|
+
const end = readDelimited(text, at, char, true);
|
|
1049
|
+
if (end === null) return { error: {
|
|
1050
|
+
message: "Unterminated quoted identifier",
|
|
1051
|
+
offset: at
|
|
1052
|
+
} };
|
|
1053
|
+
const raw = text.slice(at, end);
|
|
1054
|
+
return token("quoted", raw, unquote(raw, char, true), at, end);
|
|
1055
|
+
}
|
|
1056
|
+
if (char === "[" && isBracketIdentifier(previous)) {
|
|
1057
|
+
const end = readDelimited(text, at, "]", false);
|
|
1058
|
+
if (end === null) return { error: {
|
|
1059
|
+
message: "Unterminated quoted identifier",
|
|
1060
|
+
offset: at
|
|
1061
|
+
} };
|
|
1062
|
+
const raw = text.slice(at, end);
|
|
1063
|
+
return token("quoted", raw, unquote(raw, "]", false), at, end);
|
|
1064
|
+
}
|
|
1065
|
+
if (char === "$") {
|
|
1066
|
+
const dollar = readDollarQuoted(text, at);
|
|
1067
|
+
if (dollar !== null) {
|
|
1068
|
+
const raw = text.slice(at, dollar.end);
|
|
1069
|
+
return token("string", raw, raw.slice(dollar.tag.length, -dollar.tag.length), at, dollar.end);
|
|
1070
|
+
}
|
|
1071
|
+
const end = readWord(text, at + 1);
|
|
1072
|
+
if (end > at + 1) return token("param", text.slice(at, end), text.slice(at, end), at, end);
|
|
1073
|
+
}
|
|
1074
|
+
if (char === "?") {
|
|
1075
|
+
const end = readWord(text, at + 1);
|
|
1076
|
+
return token("param", text.slice(at, end), text.slice(at, end), at, end);
|
|
1077
|
+
}
|
|
1078
|
+
if ((char === ":" || char === "@") && previous?.raw !== ":" && text[at + 1] !== ":" && isWordStart(text[at + 1] ?? "")) {
|
|
1079
|
+
const end = readWord(text, at + 1);
|
|
1080
|
+
return token("param", text.slice(at, end), text.slice(at, end), at, end);
|
|
1081
|
+
}
|
|
1082
|
+
if (isDigit(char) || char === "." && isDigit(text[at + 1] ?? "")) {
|
|
1083
|
+
const end = readNumber(text, at);
|
|
1084
|
+
return token("number", text.slice(at, end), text.slice(at, end), at, end);
|
|
1085
|
+
}
|
|
1086
|
+
if (isWordStart(char)) {
|
|
1087
|
+
const end = readWord(text, at);
|
|
1088
|
+
const raw = text.slice(at, end);
|
|
1089
|
+
return token("word", raw, raw.toUpperCase(), at, end);
|
|
1090
|
+
}
|
|
1091
|
+
if (PUNCTUATION.has(char)) return token("punct", char, char, at, at + 1);
|
|
1092
|
+
const operator = OPERATORS.find((candidate) => text.startsWith(candidate, at));
|
|
1093
|
+
if (operator !== void 0) return token("op", operator, operator, at, at + operator.length);
|
|
1094
|
+
return { error: {
|
|
1095
|
+
message: `Unexpected character "${char}"`,
|
|
1096
|
+
offset: at
|
|
1097
|
+
} };
|
|
1098
|
+
}
|
|
1099
|
+
/** Splits SQL text into tokens; comments and whitespace are dropped, offsets are kept. */
|
|
1100
|
+
function tokenize(text) {
|
|
1101
|
+
const tokens = [];
|
|
1102
|
+
let at = 0;
|
|
1103
|
+
while (at < text.length) {
|
|
1104
|
+
const result = step(text, at, tokens.at(-1) ?? null);
|
|
1105
|
+
if ("error" in result) return {
|
|
1106
|
+
ok: false,
|
|
1107
|
+
error: result.error
|
|
1108
|
+
};
|
|
1109
|
+
if ("skip" in result) at = result.skip;
|
|
1110
|
+
else {
|
|
1111
|
+
tokens.push(result.token);
|
|
1112
|
+
at = result.next;
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
tokens.push({
|
|
1116
|
+
kind: "eof",
|
|
1117
|
+
raw: "",
|
|
1118
|
+
text: "",
|
|
1119
|
+
start: text.length,
|
|
1120
|
+
end: text.length
|
|
1121
|
+
});
|
|
1122
|
+
return {
|
|
1123
|
+
ok: true,
|
|
1124
|
+
tokens
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1127
|
+
//#endregion
|
|
1128
|
+
//#region src/sql/parse.ts
|
|
1129
|
+
var ParseFailure = class extends Error {
|
|
1130
|
+
offset;
|
|
1131
|
+
constructor(message, offset) {
|
|
1132
|
+
super(message);
|
|
1133
|
+
this.offset = offset;
|
|
1134
|
+
}
|
|
1135
|
+
};
|
|
1136
|
+
/** Words that never name a column or table, so they end an expression or an alias. */
|
|
1137
|
+
const RESERVED = /* @__PURE__ */ new Set([
|
|
1138
|
+
"SELECT",
|
|
1139
|
+
"FROM",
|
|
1140
|
+
"WHERE",
|
|
1141
|
+
"GROUP",
|
|
1142
|
+
"HAVING",
|
|
1143
|
+
"ORDER",
|
|
1144
|
+
"LIMIT",
|
|
1145
|
+
"OFFSET",
|
|
1146
|
+
"JOIN",
|
|
1147
|
+
"ON",
|
|
1148
|
+
"USING",
|
|
1149
|
+
"AND",
|
|
1150
|
+
"OR",
|
|
1151
|
+
"NOT",
|
|
1152
|
+
"IN",
|
|
1153
|
+
"IS",
|
|
1154
|
+
"NULL",
|
|
1155
|
+
"BETWEEN",
|
|
1156
|
+
"CASE",
|
|
1157
|
+
"WHEN",
|
|
1158
|
+
"THEN",
|
|
1159
|
+
"ELSE",
|
|
1160
|
+
"END",
|
|
1161
|
+
"DISTINCT",
|
|
1162
|
+
"UNION",
|
|
1163
|
+
"INTERSECT",
|
|
1164
|
+
"EXCEPT",
|
|
1165
|
+
"WITH",
|
|
1166
|
+
"INSERT",
|
|
1167
|
+
"INTO",
|
|
1168
|
+
"VALUES",
|
|
1169
|
+
"UPDATE",
|
|
1170
|
+
"SET",
|
|
1171
|
+
"DELETE",
|
|
1172
|
+
"RETURNING",
|
|
1173
|
+
"LEFT",
|
|
1174
|
+
"RIGHT",
|
|
1175
|
+
"INNER",
|
|
1176
|
+
"OUTER",
|
|
1177
|
+
"CROSS",
|
|
1178
|
+
"FULL",
|
|
1179
|
+
"NATURAL",
|
|
1180
|
+
"EXISTS",
|
|
1181
|
+
"AS",
|
|
1182
|
+
"LIKE",
|
|
1183
|
+
"ILIKE",
|
|
1184
|
+
"FETCH",
|
|
1185
|
+
"WINDOW",
|
|
1186
|
+
"COLLATE"
|
|
1187
|
+
]);
|
|
1188
|
+
const COMPARISON = /* @__PURE__ */ new Set([
|
|
1189
|
+
"=",
|
|
1190
|
+
"<>",
|
|
1191
|
+
"!=",
|
|
1192
|
+
"<",
|
|
1193
|
+
">",
|
|
1194
|
+
"<=",
|
|
1195
|
+
">=",
|
|
1196
|
+
"<=>",
|
|
1197
|
+
"~",
|
|
1198
|
+
"!~",
|
|
1199
|
+
"~*",
|
|
1200
|
+
"!~*"
|
|
1201
|
+
]);
|
|
1202
|
+
const OTHER_OPERATORS = /* @__PURE__ */ new Set([
|
|
1203
|
+
"||",
|
|
1204
|
+
"->",
|
|
1205
|
+
"->>",
|
|
1206
|
+
"#>",
|
|
1207
|
+
"#>>",
|
|
1208
|
+
"@>",
|
|
1209
|
+
"<@",
|
|
1210
|
+
"<<",
|
|
1211
|
+
">>",
|
|
1212
|
+
"&",
|
|
1213
|
+
"|",
|
|
1214
|
+
"#"
|
|
1215
|
+
]);
|
|
1216
|
+
const LIKE_WORDS = /* @__PURE__ */ new Set([
|
|
1217
|
+
"LIKE",
|
|
1218
|
+
"ILIKE",
|
|
1219
|
+
"GLOB",
|
|
1220
|
+
"REGEXP",
|
|
1221
|
+
"MATCH",
|
|
1222
|
+
"RLIKE",
|
|
1223
|
+
"SIMILAR"
|
|
1224
|
+
]);
|
|
1225
|
+
const SET_OPERATORS = /* @__PURE__ */ new Set([
|
|
1226
|
+
"UNION",
|
|
1227
|
+
"INTERSECT",
|
|
1228
|
+
"EXCEPT"
|
|
1229
|
+
]);
|
|
1230
|
+
const JOIN_WORDS = /* @__PURE__ */ new Set([
|
|
1231
|
+
"JOIN",
|
|
1232
|
+
"LEFT",
|
|
1233
|
+
"RIGHT",
|
|
1234
|
+
"INNER",
|
|
1235
|
+
"CROSS",
|
|
1236
|
+
"FULL",
|
|
1237
|
+
"NATURAL"
|
|
1238
|
+
]);
|
|
1239
|
+
function peek(p, ahead = 0) {
|
|
1240
|
+
return p.tokens[p.pos + ahead] ?? p.tokens.at(-1) ?? {
|
|
1241
|
+
kind: "eof",
|
|
1242
|
+
raw: "",
|
|
1243
|
+
text: "",
|
|
1244
|
+
start: 0,
|
|
1245
|
+
end: 0
|
|
1246
|
+
};
|
|
1247
|
+
}
|
|
1248
|
+
function advance(p) {
|
|
1249
|
+
const token = peek(p);
|
|
1250
|
+
if (token.kind !== "eof") p.pos += 1;
|
|
1251
|
+
return token;
|
|
1252
|
+
}
|
|
1253
|
+
function fail(p, message) {
|
|
1254
|
+
throw new ParseFailure(message, peek(p).start);
|
|
1255
|
+
}
|
|
1256
|
+
function isWord(token, word) {
|
|
1257
|
+
return token.kind === "word" && token.text === word;
|
|
1258
|
+
}
|
|
1259
|
+
function atWord(p, word, ahead = 0) {
|
|
1260
|
+
return isWord(peek(p, ahead), word);
|
|
1261
|
+
}
|
|
1262
|
+
function atPunct(p, punct, ahead = 0) {
|
|
1263
|
+
const token = peek(p, ahead);
|
|
1264
|
+
return token.kind === "punct" && token.text === punct;
|
|
1265
|
+
}
|
|
1266
|
+
function atOp(p, op) {
|
|
1267
|
+
const token = peek(p);
|
|
1268
|
+
return token.kind === "op" && token.text === op;
|
|
1269
|
+
}
|
|
1270
|
+
function acceptWord(p, word) {
|
|
1271
|
+
if (!atWord(p, word)) return false;
|
|
1272
|
+
advance(p);
|
|
1273
|
+
return true;
|
|
1274
|
+
}
|
|
1275
|
+
function acceptPunct(p, punct) {
|
|
1276
|
+
if (!atPunct(p, punct)) return false;
|
|
1277
|
+
advance(p);
|
|
1278
|
+
return true;
|
|
1279
|
+
}
|
|
1280
|
+
function expectWord(p, word) {
|
|
1281
|
+
if (!acceptWord(p, word)) fail(p, `Expected ${word}`);
|
|
1282
|
+
}
|
|
1283
|
+
function expectPunct(p, punct) {
|
|
1284
|
+
if (!acceptPunct(p, punct)) fail(p, `Expected "${punct}"`);
|
|
1285
|
+
}
|
|
1286
|
+
/** `A B C` in a row, each accepted only when the whole phrase is there. */
|
|
1287
|
+
function acceptWords(p, ...words) {
|
|
1288
|
+
if (!words.every((word, index) => atWord(p, word, index))) return false;
|
|
1289
|
+
for (const _ of words) advance(p);
|
|
1290
|
+
return true;
|
|
1291
|
+
}
|
|
1292
|
+
function previousEnd(p) {
|
|
1293
|
+
return p.tokens[p.pos - 1]?.end ?? 0;
|
|
1294
|
+
}
|
|
1295
|
+
function rangeFrom(p, start) {
|
|
1296
|
+
return {
|
|
1297
|
+
start,
|
|
1298
|
+
end: previousEnd(p)
|
|
1299
|
+
};
|
|
1300
|
+
}
|
|
1301
|
+
/** Whether the token can name something: an identifier, or a word that is not reserved. */
|
|
1302
|
+
function isNameToken(token) {
|
|
1303
|
+
return token.kind === "quoted" || token.kind === "word" && !RESERVED.has(token.text);
|
|
1304
|
+
}
|
|
1305
|
+
function nameOf(token) {
|
|
1306
|
+
return token.kind === "quoted" ? token.text : token.raw;
|
|
1307
|
+
}
|
|
1308
|
+
function expectName(p, what) {
|
|
1309
|
+
const token = peek(p);
|
|
1310
|
+
if (!isNameToken(token)) fail(p, `Expected ${what}`);
|
|
1311
|
+
advance(p);
|
|
1312
|
+
return nameOf(token);
|
|
1313
|
+
}
|
|
1314
|
+
/** `[AS] alias`, where a bare alias must not be a reserved word. */
|
|
1315
|
+
function parseAlias(p) {
|
|
1316
|
+
if (acceptWord(p, "AS")) return expectName(p, "an alias");
|
|
1317
|
+
const token = peek(p);
|
|
1318
|
+
if (isNameToken(token)) {
|
|
1319
|
+
advance(p);
|
|
1320
|
+
return nameOf(token);
|
|
1321
|
+
}
|
|
1322
|
+
return null;
|
|
1323
|
+
}
|
|
1324
|
+
function parseExpr(p) {
|
|
1325
|
+
return parseOr(p);
|
|
1326
|
+
}
|
|
1327
|
+
function parseOr(p) {
|
|
1328
|
+
const start = peek(p).start;
|
|
1329
|
+
return fold(p, start, parseAnd(p), () => acceptWord(p, "OR") ? "OR" : null, parseAnd);
|
|
1330
|
+
}
|
|
1331
|
+
function parseAnd(p) {
|
|
1332
|
+
const start = peek(p).start;
|
|
1333
|
+
return fold(p, start, parseNot(p), () => acceptWord(p, "AND") ? "AND" : null, parseNot);
|
|
1334
|
+
}
|
|
1335
|
+
/** Left-associative binary chain: `first (op next)*`. */
|
|
1336
|
+
function fold(p, start, first, operator, parseNext) {
|
|
1337
|
+
const op = operator();
|
|
1338
|
+
if (op === null) return first;
|
|
1339
|
+
return fold(p, start, {
|
|
1340
|
+
type: "binary",
|
|
1341
|
+
op,
|
|
1342
|
+
left: first,
|
|
1343
|
+
right: parseNext(p),
|
|
1344
|
+
range: rangeFrom(p, start)
|
|
1345
|
+
}, operator, parseNext);
|
|
1346
|
+
}
|
|
1347
|
+
function parseNot(p) {
|
|
1348
|
+
const start = peek(p).start;
|
|
1349
|
+
if (acceptWord(p, "NOT")) return {
|
|
1350
|
+
type: "unary",
|
|
1351
|
+
op: "NOT",
|
|
1352
|
+
operand: parseNot(p),
|
|
1353
|
+
range: rangeFrom(p, start)
|
|
1354
|
+
};
|
|
1355
|
+
return parseComparison(p);
|
|
1356
|
+
}
|
|
1357
|
+
function parseComparison(p) {
|
|
1358
|
+
const start = peek(p).start;
|
|
1359
|
+
return parsePredicate(p, start, parseConcat(p));
|
|
1360
|
+
}
|
|
1361
|
+
/** The predicates that follow a value: comparison operators, IS, IN, BETWEEN, LIKE and friends. */
|
|
1362
|
+
function parsePredicate(p, start, left) {
|
|
1363
|
+
const token = peek(p);
|
|
1364
|
+
if (token.kind === "op" && COMPARISON.has(token.text)) {
|
|
1365
|
+
advance(p);
|
|
1366
|
+
if (atWord(p, "ANY") || atWord(p, "ALL") || atWord(p, "SOME")) advance(p);
|
|
1367
|
+
const right = parseConcat(p);
|
|
1368
|
+
return parsePredicate(p, start, {
|
|
1369
|
+
type: "binary",
|
|
1370
|
+
op: token.text,
|
|
1371
|
+
left,
|
|
1372
|
+
right,
|
|
1373
|
+
range: rangeFrom(p, start)
|
|
1374
|
+
});
|
|
1375
|
+
}
|
|
1376
|
+
if (atWord(p, "IS")) {
|
|
1377
|
+
advance(p);
|
|
1378
|
+
const not = acceptWord(p, "NOT");
|
|
1379
|
+
if (acceptWords(p, "DISTINCT", "FROM")) {
|
|
1380
|
+
const right = parseConcat(p);
|
|
1381
|
+
return parsePredicate(p, start, {
|
|
1382
|
+
type: "binary",
|
|
1383
|
+
op: not ? "IS NOT DISTINCT FROM" : "IS DISTINCT FROM",
|
|
1384
|
+
left,
|
|
1385
|
+
right,
|
|
1386
|
+
range: rangeFrom(p, start)
|
|
1387
|
+
});
|
|
1388
|
+
}
|
|
1389
|
+
const value = advance(p);
|
|
1390
|
+
if (![
|
|
1391
|
+
"NULL",
|
|
1392
|
+
"TRUE",
|
|
1393
|
+
"FALSE",
|
|
1394
|
+
"UNKNOWN"
|
|
1395
|
+
].includes(value.text) || value.kind !== "word") fail(p, "Expected NULL, TRUE, FALSE or UNKNOWN after IS");
|
|
1396
|
+
return parsePredicate(p, start, {
|
|
1397
|
+
type: "is",
|
|
1398
|
+
expr: left,
|
|
1399
|
+
not,
|
|
1400
|
+
value: value.text === "NULL" ? "NULL" : value.text === "TRUE" ? "TRUE" : value.text === "FALSE" ? "FALSE" : "UNKNOWN",
|
|
1401
|
+
range: rangeFrom(p, start)
|
|
1402
|
+
});
|
|
1403
|
+
}
|
|
1404
|
+
if (atWord(p, "ISNULL") || atWord(p, "NOTNULL")) return parsePredicate(p, start, {
|
|
1405
|
+
type: "is",
|
|
1406
|
+
expr: left,
|
|
1407
|
+
not: advance(p).text === "NOTNULL",
|
|
1408
|
+
value: "NULL",
|
|
1409
|
+
range: rangeFrom(p, start)
|
|
1410
|
+
});
|
|
1411
|
+
const negated = atWord(p, "NOT") && (atWord(p, "IN", 1) || atWord(p, "BETWEEN", 1) || LIKE_WORDS.has(peek(p, 1).text));
|
|
1412
|
+
if (negated) advance(p);
|
|
1413
|
+
if (atWord(p, "IN")) {
|
|
1414
|
+
advance(p);
|
|
1415
|
+
if (acceptPunct(p, "(")) {
|
|
1416
|
+
if (atQueryStart(p)) {
|
|
1417
|
+
const query = parseQuery(p);
|
|
1418
|
+
expectPunct(p, ")");
|
|
1419
|
+
return parsePredicate(p, start, {
|
|
1420
|
+
type: "in",
|
|
1421
|
+
expr: left,
|
|
1422
|
+
not: negated,
|
|
1423
|
+
list: null,
|
|
1424
|
+
subquery: query,
|
|
1425
|
+
range: rangeFrom(p, start)
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
const list = atPunct(p, ")") ? [] : parseExprList(p);
|
|
1429
|
+
expectPunct(p, ")");
|
|
1430
|
+
return parsePredicate(p, start, {
|
|
1431
|
+
type: "in",
|
|
1432
|
+
expr: left,
|
|
1433
|
+
not: negated,
|
|
1434
|
+
list,
|
|
1435
|
+
subquery: null,
|
|
1436
|
+
range: rangeFrom(p, start)
|
|
1437
|
+
});
|
|
1438
|
+
}
|
|
1439
|
+
return parsePredicate(p, start, {
|
|
1440
|
+
type: "in",
|
|
1441
|
+
expr: left,
|
|
1442
|
+
not: negated,
|
|
1443
|
+
list: [parseConcat(p)],
|
|
1444
|
+
subquery: null,
|
|
1445
|
+
range: rangeFrom(p, start)
|
|
1446
|
+
});
|
|
1447
|
+
}
|
|
1448
|
+
if (atWord(p, "BETWEEN")) {
|
|
1449
|
+
advance(p);
|
|
1450
|
+
acceptWord(p, "SYMMETRIC");
|
|
1451
|
+
const low = parseConcat(p);
|
|
1452
|
+
expectWord(p, "AND");
|
|
1453
|
+
return parsePredicate(p, start, {
|
|
1454
|
+
type: "between",
|
|
1455
|
+
expr: left,
|
|
1456
|
+
not: negated,
|
|
1457
|
+
low,
|
|
1458
|
+
high: parseConcat(p),
|
|
1459
|
+
range: rangeFrom(p, start)
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
const like = peek(p);
|
|
1463
|
+
if (LIKE_WORDS.has(like.text) && like.kind === "word") {
|
|
1464
|
+
advance(p);
|
|
1465
|
+
if (like.text === "SIMILAR") expectWord(p, "TO");
|
|
1466
|
+
const pattern = parseConcat(p);
|
|
1467
|
+
if (acceptWord(p, "ESCAPE")) parseConcat(p);
|
|
1468
|
+
return parsePredicate(p, start, {
|
|
1469
|
+
type: "like",
|
|
1470
|
+
op: like.text,
|
|
1471
|
+
expr: left,
|
|
1472
|
+
not: negated,
|
|
1473
|
+
pattern,
|
|
1474
|
+
range: rangeFrom(p, start)
|
|
1475
|
+
});
|
|
1476
|
+
}
|
|
1477
|
+
if (negated) fail(p, "Expected IN, BETWEEN or LIKE after NOT");
|
|
1478
|
+
return left;
|
|
1479
|
+
}
|
|
1480
|
+
function parseConcat(p) {
|
|
1481
|
+
const start = peek(p).start;
|
|
1482
|
+
return fold(p, start, parseAdditive(p), () => {
|
|
1483
|
+
const token = peek(p);
|
|
1484
|
+
if (token.kind === "op" && OTHER_OPERATORS.has(token.text)) {
|
|
1485
|
+
advance(p);
|
|
1486
|
+
return token.text;
|
|
1487
|
+
}
|
|
1488
|
+
return null;
|
|
1489
|
+
}, parseAdditive);
|
|
1490
|
+
}
|
|
1491
|
+
function parseAdditive(p) {
|
|
1492
|
+
const start = peek(p).start;
|
|
1493
|
+
return fold(p, start, parseMultiplicative(p), () => atOp(p, "+") || atOp(p, "-") ? advance(p).text : null, parseMultiplicative);
|
|
1494
|
+
}
|
|
1495
|
+
function parseMultiplicative(p) {
|
|
1496
|
+
const start = peek(p).start;
|
|
1497
|
+
return fold(p, start, parseUnary(p), () => atOp(p, "*") || atOp(p, "/") || atOp(p, "%") || atOp(p, "^") || atOp(p, "**") ? advance(p).text : null, parseUnary);
|
|
1498
|
+
}
|
|
1499
|
+
function parseUnary(p) {
|
|
1500
|
+
const start = peek(p).start;
|
|
1501
|
+
if (atOp(p, "-") || atOp(p, "+") || atOp(p, "~") || atOp(p, "!")) return {
|
|
1502
|
+
type: "unary",
|
|
1503
|
+
op: advance(p).text,
|
|
1504
|
+
operand: parseUnary(p),
|
|
1505
|
+
range: rangeFrom(p, start)
|
|
1506
|
+
};
|
|
1507
|
+
return parsePostfix(p, start, parsePrimary(p));
|
|
1508
|
+
}
|
|
1509
|
+
/** `::type` casts, `[subscript]`s and `COLLATE` after a primary. */
|
|
1510
|
+
function parsePostfix(p, start, expr) {
|
|
1511
|
+
if (atOp(p, "::")) {
|
|
1512
|
+
advance(p);
|
|
1513
|
+
return parsePostfix(p, start, {
|
|
1514
|
+
type: "cast",
|
|
1515
|
+
expr,
|
|
1516
|
+
to: parseTypeName(p),
|
|
1517
|
+
range: rangeFrom(p, start)
|
|
1518
|
+
});
|
|
1519
|
+
}
|
|
1520
|
+
if (atPunct(p, "[")) {
|
|
1521
|
+
advance(p);
|
|
1522
|
+
const index = parseExpr(p);
|
|
1523
|
+
if (acceptPunct(p, ":")) parseExpr(p);
|
|
1524
|
+
expectPunct(p, "]");
|
|
1525
|
+
return parsePostfix(p, start, {
|
|
1526
|
+
type: "binary",
|
|
1527
|
+
op: "[]",
|
|
1528
|
+
left: expr,
|
|
1529
|
+
right: index,
|
|
1530
|
+
range: rangeFrom(p, start)
|
|
1531
|
+
});
|
|
1532
|
+
}
|
|
1533
|
+
if (atWord(p, "COLLATE")) {
|
|
1534
|
+
advance(p);
|
|
1535
|
+
expectName(p, "a collation");
|
|
1536
|
+
return parsePostfix(p, start, expr);
|
|
1537
|
+
}
|
|
1538
|
+
return expr;
|
|
1539
|
+
}
|
|
1540
|
+
/** A type name as written after CAST ... AS or `::`: words, an optional `(n[, m])` and `[]`. */
|
|
1541
|
+
function parseTypeName(p) {
|
|
1542
|
+
const start = peek(p).start;
|
|
1543
|
+
const first = advance(p);
|
|
1544
|
+
if (first.kind !== "word" && first.kind !== "quoted") fail(p, "Expected a type name");
|
|
1545
|
+
while (peek(p).kind === "word" && !RESERVED.has(peek(p).text) && !atPunct(p, ")")) advance(p);
|
|
1546
|
+
if (atPunct(p, "(")) {
|
|
1547
|
+
advance(p);
|
|
1548
|
+
while (!atPunct(p, ")") && peek(p).kind !== "eof") advance(p);
|
|
1549
|
+
expectPunct(p, ")");
|
|
1550
|
+
}
|
|
1551
|
+
while (atPunct(p, "[") && atPunct(p, "]", 1)) {
|
|
1552
|
+
advance(p);
|
|
1553
|
+
advance(p);
|
|
1554
|
+
}
|
|
1555
|
+
return p.text.slice(start, previousEnd(p)).replaceAll(/\s+/gu, " ");
|
|
1556
|
+
}
|
|
1557
|
+
function parseExprList(p) {
|
|
1558
|
+
const items = [parseExpr(p)];
|
|
1559
|
+
while (acceptPunct(p, ",")) items.push(parseExpr(p));
|
|
1560
|
+
return items;
|
|
1561
|
+
}
|
|
1562
|
+
function atQueryStart(p) {
|
|
1563
|
+
return atWord(p, "SELECT") || atWord(p, "WITH") || atWord(p, "VALUES") || atPunct(p, "(") && atQueryStartAt(p, 1);
|
|
1564
|
+
}
|
|
1565
|
+
function atQueryStartAt(p, ahead) {
|
|
1566
|
+
if (atWord(p, "SELECT", ahead) || atWord(p, "WITH", ahead) || atWord(p, "VALUES", ahead)) return true;
|
|
1567
|
+
return atPunct(p, "(", ahead) ? atQueryStartAt(p, ahead + 1) : false;
|
|
1568
|
+
}
|
|
1569
|
+
function parsePrimary(p) {
|
|
1570
|
+
const token = peek(p);
|
|
1571
|
+
const start = token.start;
|
|
1572
|
+
if (token.kind === "string") {
|
|
1573
|
+
advance(p);
|
|
1574
|
+
return {
|
|
1575
|
+
type: "literal",
|
|
1576
|
+
kind: "string",
|
|
1577
|
+
value: token.text,
|
|
1578
|
+
range: rangeFrom(p, start)
|
|
1579
|
+
};
|
|
1580
|
+
}
|
|
1581
|
+
if (token.kind === "number") {
|
|
1582
|
+
advance(p);
|
|
1583
|
+
return {
|
|
1584
|
+
type: "literal",
|
|
1585
|
+
kind: "number",
|
|
1586
|
+
value: token.text,
|
|
1587
|
+
range: rangeFrom(p, start)
|
|
1588
|
+
};
|
|
1589
|
+
}
|
|
1590
|
+
if (token.kind === "param") {
|
|
1591
|
+
advance(p);
|
|
1592
|
+
return {
|
|
1593
|
+
type: "param",
|
|
1594
|
+
placeholder: token.text,
|
|
1595
|
+
range: rangeFrom(p, start)
|
|
1596
|
+
};
|
|
1597
|
+
}
|
|
1598
|
+
if (token.kind === "punct" && token.text === "(") {
|
|
1599
|
+
advance(p);
|
|
1600
|
+
if (atQueryStart(p)) {
|
|
1601
|
+
const query = parseQuery(p);
|
|
1602
|
+
expectPunct(p, ")");
|
|
1603
|
+
return {
|
|
1604
|
+
type: "subquery",
|
|
1605
|
+
query,
|
|
1606
|
+
range: rangeFrom(p, start)
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1609
|
+
const items = parseExprList(p);
|
|
1610
|
+
expectPunct(p, ")");
|
|
1611
|
+
const single = items[0];
|
|
1612
|
+
return items.length === 1 && single !== void 0 ? single : {
|
|
1613
|
+
type: "list",
|
|
1614
|
+
items,
|
|
1615
|
+
range: rangeFrom(p, start)
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1618
|
+
if (token.kind === "op" && token.text === "*") {
|
|
1619
|
+
advance(p);
|
|
1620
|
+
return {
|
|
1621
|
+
type: "star",
|
|
1622
|
+
table: null,
|
|
1623
|
+
range: rangeFrom(p, start)
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1626
|
+
if (token.kind === "word") switch (token.text) {
|
|
1627
|
+
case "NULL":
|
|
1628
|
+
advance(p);
|
|
1629
|
+
return {
|
|
1630
|
+
type: "literal",
|
|
1631
|
+
kind: "null",
|
|
1632
|
+
value: "NULL",
|
|
1633
|
+
range: rangeFrom(p, start)
|
|
1634
|
+
};
|
|
1635
|
+
case "TRUE":
|
|
1636
|
+
case "FALSE":
|
|
1637
|
+
advance(p);
|
|
1638
|
+
return {
|
|
1639
|
+
type: "literal",
|
|
1640
|
+
kind: "boolean",
|
|
1641
|
+
value: token.text.toLowerCase(),
|
|
1642
|
+
range: rangeFrom(p, start)
|
|
1643
|
+
};
|
|
1644
|
+
case "CASE": return parseCase(p);
|
|
1645
|
+
case "CAST": return parseCast(p);
|
|
1646
|
+
case "EXISTS": {
|
|
1647
|
+
advance(p);
|
|
1648
|
+
expectPunct(p, "(");
|
|
1649
|
+
const query = parseQuery(p);
|
|
1650
|
+
expectPunct(p, ")");
|
|
1651
|
+
return {
|
|
1652
|
+
type: "exists",
|
|
1653
|
+
not: false,
|
|
1654
|
+
query,
|
|
1655
|
+
range: rangeFrom(p, start)
|
|
1656
|
+
};
|
|
1657
|
+
}
|
|
1658
|
+
case "NOT":
|
|
1659
|
+
advance(p);
|
|
1660
|
+
return {
|
|
1661
|
+
type: "unary",
|
|
1662
|
+
op: "NOT",
|
|
1663
|
+
operand: parseUnary(p),
|
|
1664
|
+
range: rangeFrom(p, start)
|
|
1665
|
+
};
|
|
1666
|
+
case "INTERVAL":
|
|
1667
|
+
case "DATE":
|
|
1668
|
+
case "TIME":
|
|
1669
|
+
case "TIMESTAMP":
|
|
1670
|
+
if (peek(p, 1).kind === "string") {
|
|
1671
|
+
advance(p);
|
|
1672
|
+
const literal = advance(p);
|
|
1673
|
+
return {
|
|
1674
|
+
type: "cast",
|
|
1675
|
+
expr: {
|
|
1676
|
+
type: "literal",
|
|
1677
|
+
kind: "string",
|
|
1678
|
+
value: literal.text,
|
|
1679
|
+
range: {
|
|
1680
|
+
start: literal.start,
|
|
1681
|
+
end: literal.end
|
|
1682
|
+
}
|
|
1683
|
+
},
|
|
1684
|
+
to: token.raw,
|
|
1685
|
+
range: rangeFrom(p, start)
|
|
1686
|
+
};
|
|
1687
|
+
}
|
|
1688
|
+
break;
|
|
1689
|
+
case "ARRAY": if (atPunct(p, "[", 1)) {
|
|
1690
|
+
advance(p);
|
|
1691
|
+
advance(p);
|
|
1692
|
+
const items = atPunct(p, "]") ? [] : parseExprList(p);
|
|
1693
|
+
expectPunct(p, "]");
|
|
1694
|
+
return {
|
|
1695
|
+
type: "call",
|
|
1696
|
+
name: "array",
|
|
1697
|
+
args: items,
|
|
1698
|
+
distinct: false,
|
|
1699
|
+
over: null,
|
|
1700
|
+
range: rangeFrom(p, start)
|
|
1701
|
+
};
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
if (isNameToken(token) || token.kind === "word" && !RESERVED.has(token.text)) return parseNameExpr(p);
|
|
1705
|
+
return fail(p, `Unexpected ${token.kind === "eof" ? "end of statement" : `"${token.raw}"`}`);
|
|
1706
|
+
}
|
|
1707
|
+
/** `a`, `a.b`, `a.b.c`, `a.*` or a function call `f(...)`. */
|
|
1708
|
+
function parseNameExpr(p) {
|
|
1709
|
+
const start = peek(p).start;
|
|
1710
|
+
const parts = [nameOf(advance(p))];
|
|
1711
|
+
while (atPunct(p, ".")) {
|
|
1712
|
+
advance(p);
|
|
1713
|
+
if (atOp(p, "*")) {
|
|
1714
|
+
advance(p);
|
|
1715
|
+
return {
|
|
1716
|
+
type: "star",
|
|
1717
|
+
table: parts.join("."),
|
|
1718
|
+
range: rangeFrom(p, start)
|
|
1719
|
+
};
|
|
1720
|
+
}
|
|
1721
|
+
const next = advance(p);
|
|
1722
|
+
if (next.kind !== "word" && next.kind !== "quoted") fail(p, "Expected a name after \".\"");
|
|
1723
|
+
parts.push(nameOf(next));
|
|
1724
|
+
}
|
|
1725
|
+
if (atPunct(p, "(")) return parseCall(p, start, parts.join("."));
|
|
1726
|
+
const name = parts.at(-1) ?? "";
|
|
1727
|
+
return {
|
|
1728
|
+
type: "column",
|
|
1729
|
+
table: parts.length > 1 ? parts.slice(0, -1).join(".") : null,
|
|
1730
|
+
name,
|
|
1731
|
+
range: rangeFrom(p, start)
|
|
1732
|
+
};
|
|
1733
|
+
}
|
|
1734
|
+
function parseCall(p, start, name) {
|
|
1735
|
+
expectPunct(p, "(");
|
|
1736
|
+
const distinct = acceptWord(p, "DISTINCT");
|
|
1737
|
+
if (!distinct) acceptWord(p, "ALL");
|
|
1738
|
+
const args = [];
|
|
1739
|
+
if (!atPunct(p, ")")) {
|
|
1740
|
+
if (atOp(p, "*")) {
|
|
1741
|
+
advance(p);
|
|
1742
|
+
args.push({
|
|
1743
|
+
type: "star",
|
|
1744
|
+
table: null,
|
|
1745
|
+
range: rangeFrom(p, start)
|
|
1746
|
+
});
|
|
1747
|
+
} else {
|
|
1748
|
+
args.push(parseExpr(p));
|
|
1749
|
+
while (acceptPunct(p, ",") || atWord(p, "FROM") || atWord(p, "FOR")) {
|
|
1750
|
+
if (atWord(p, "FROM") || atWord(p, "FOR")) advance(p);
|
|
1751
|
+
args.push(parseExpr(p));
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
if (acceptWords(p, "ORDER", "BY")) parseOrderItems(p);
|
|
1755
|
+
if (acceptWord(p, "SEPARATOR")) parseExpr(p);
|
|
1756
|
+
}
|
|
1757
|
+
expectPunct(p, ")");
|
|
1758
|
+
if (acceptWord(p, "FILTER")) {
|
|
1759
|
+
expectPunct(p, "(");
|
|
1760
|
+
expectWord(p, "WHERE");
|
|
1761
|
+
parseExpr(p);
|
|
1762
|
+
expectPunct(p, ")");
|
|
1763
|
+
}
|
|
1764
|
+
if (acceptWord(p, "WITHIN")) {
|
|
1765
|
+
expectWord(p, "GROUP");
|
|
1766
|
+
expectPunct(p, "(");
|
|
1767
|
+
expectWord(p, "ORDER");
|
|
1768
|
+
expectWord(p, "BY");
|
|
1769
|
+
parseOrderItems(p);
|
|
1770
|
+
expectPunct(p, ")");
|
|
1771
|
+
}
|
|
1772
|
+
return {
|
|
1773
|
+
type: "call",
|
|
1774
|
+
name,
|
|
1775
|
+
args,
|
|
1776
|
+
distinct,
|
|
1777
|
+
over: acceptWord(p, "OVER") ? parseWindow(p) : null,
|
|
1778
|
+
range: rangeFrom(p, start)
|
|
1779
|
+
};
|
|
1780
|
+
}
|
|
1781
|
+
/** `OVER (PARTITION BY ... ORDER BY ... [frame])` or `OVER name`. */
|
|
1782
|
+
function parseWindow(p) {
|
|
1783
|
+
const start = peek(p).start;
|
|
1784
|
+
if (!atPunct(p, "(")) {
|
|
1785
|
+
expectName(p, "a window name");
|
|
1786
|
+
return {
|
|
1787
|
+
partitionBy: [],
|
|
1788
|
+
orderBy: [],
|
|
1789
|
+
range: rangeFrom(p, start)
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
advance(p);
|
|
1793
|
+
if (isNameToken(peek(p)) && !atWord(p, "PARTITION") && !atWord(p, "ORDER") && !atWord(p, "ROWS") && !atWord(p, "RANGE") && !atWord(p, "GROUPS")) advance(p);
|
|
1794
|
+
const partitionBy = acceptWords(p, "PARTITION", "BY") ? parseExprList(p) : [];
|
|
1795
|
+
const orderBy = acceptWords(p, "ORDER", "BY") ? parseOrderItems(p) : [];
|
|
1796
|
+
let depth = 0;
|
|
1797
|
+
while (!(depth === 0 && atPunct(p, ")")) && peek(p).kind !== "eof") {
|
|
1798
|
+
if (atPunct(p, "(")) depth += 1;
|
|
1799
|
+
if (atPunct(p, ")")) depth -= 1;
|
|
1800
|
+
advance(p);
|
|
1801
|
+
}
|
|
1802
|
+
expectPunct(p, ")");
|
|
1803
|
+
return {
|
|
1804
|
+
partitionBy,
|
|
1805
|
+
orderBy,
|
|
1806
|
+
range: rangeFrom(p, start)
|
|
1807
|
+
};
|
|
1808
|
+
}
|
|
1809
|
+
function parseCase(p) {
|
|
1810
|
+
const start = peek(p).start;
|
|
1811
|
+
expectWord(p, "CASE");
|
|
1812
|
+
const operand = atWord(p, "WHEN") ? null : parseExpr(p);
|
|
1813
|
+
const whens = [];
|
|
1814
|
+
while (acceptWord(p, "WHEN")) {
|
|
1815
|
+
const when = parseExpr(p);
|
|
1816
|
+
expectWord(p, "THEN");
|
|
1817
|
+
const result = parseExpr(p);
|
|
1818
|
+
whens.push({
|
|
1819
|
+
when,
|
|
1820
|
+
result
|
|
1821
|
+
});
|
|
1822
|
+
}
|
|
1823
|
+
if (whens.length === 0) fail(p, "Expected WHEN");
|
|
1824
|
+
const otherwise = acceptWord(p, "ELSE") ? parseExpr(p) : null;
|
|
1825
|
+
expectWord(p, "END");
|
|
1826
|
+
return {
|
|
1827
|
+
type: "case",
|
|
1828
|
+
operand,
|
|
1829
|
+
whens,
|
|
1830
|
+
otherwise,
|
|
1831
|
+
range: rangeFrom(p, start)
|
|
1832
|
+
};
|
|
1833
|
+
}
|
|
1834
|
+
function parseCast(p) {
|
|
1835
|
+
const start = peek(p).start;
|
|
1836
|
+
expectWord(p, "CAST");
|
|
1837
|
+
expectPunct(p, "(");
|
|
1838
|
+
const expr = parseExpr(p);
|
|
1839
|
+
expectWord(p, "AS");
|
|
1840
|
+
const to = parseTypeName(p);
|
|
1841
|
+
expectPunct(p, ")");
|
|
1842
|
+
return {
|
|
1843
|
+
type: "cast",
|
|
1844
|
+
expr,
|
|
1845
|
+
to,
|
|
1846
|
+
range: rangeFrom(p, start)
|
|
1847
|
+
};
|
|
1848
|
+
}
|
|
1849
|
+
function parseOrderItems(p) {
|
|
1850
|
+
const items = [];
|
|
1851
|
+
do {
|
|
1852
|
+
const start = peek(p).start;
|
|
1853
|
+
const expr = parseExpr(p);
|
|
1854
|
+
const direction = acceptWord(p, "ASC") ? "ASC" : acceptWord(p, "DESC") ? "DESC" : null;
|
|
1855
|
+
if (acceptWord(p, "NULLS") && !acceptWord(p, "FIRST") && !acceptWord(p, "LAST")) fail(p, "Expected FIRST or LAST");
|
|
1856
|
+
items.push({
|
|
1857
|
+
expr,
|
|
1858
|
+
direction,
|
|
1859
|
+
range: rangeFrom(p, start)
|
|
1860
|
+
});
|
|
1861
|
+
} while (acceptPunct(p, ","));
|
|
1862
|
+
return items;
|
|
1863
|
+
}
|
|
1864
|
+
function parseQuery(p) {
|
|
1865
|
+
const start = peek(p).start;
|
|
1866
|
+
const { ctes, recursive } = parseWith(p);
|
|
1867
|
+
const body = parseSetOperation(p);
|
|
1868
|
+
const orderBy = acceptWords(p, "ORDER", "BY") ? parseOrderItems(p) : [];
|
|
1869
|
+
const { limit, offset } = parseLimit(p);
|
|
1870
|
+
return {
|
|
1871
|
+
type: "query",
|
|
1872
|
+
ctes,
|
|
1873
|
+
recursive,
|
|
1874
|
+
body,
|
|
1875
|
+
orderBy,
|
|
1876
|
+
limit,
|
|
1877
|
+
offset,
|
|
1878
|
+
range: rangeFrom(p, start)
|
|
1879
|
+
};
|
|
1880
|
+
}
|
|
1881
|
+
function parseWith(p) {
|
|
1882
|
+
if (!acceptWord(p, "WITH")) return {
|
|
1883
|
+
ctes: [],
|
|
1884
|
+
recursive: false
|
|
1885
|
+
};
|
|
1886
|
+
const recursive = acceptWord(p, "RECURSIVE");
|
|
1887
|
+
const ctes = [];
|
|
1888
|
+
do {
|
|
1889
|
+
const start = peek(p).start;
|
|
1890
|
+
const name = expectName(p, "a CTE name");
|
|
1891
|
+
const columns = atPunct(p, "(") ? parseNameList(p) : null;
|
|
1892
|
+
expectWord(p, "AS");
|
|
1893
|
+
if (acceptWord(p, "NOT")) expectWord(p, "MATERIALIZED");
|
|
1894
|
+
else acceptWord(p, "MATERIALIZED");
|
|
1895
|
+
expectPunct(p, "(");
|
|
1896
|
+
const query = parseQuery(p);
|
|
1897
|
+
expectPunct(p, ")");
|
|
1898
|
+
ctes.push({
|
|
1899
|
+
name,
|
|
1900
|
+
columns,
|
|
1901
|
+
query,
|
|
1902
|
+
range: rangeFrom(p, start)
|
|
1903
|
+
});
|
|
1904
|
+
} while (acceptPunct(p, ","));
|
|
1905
|
+
return {
|
|
1906
|
+
ctes,
|
|
1907
|
+
recursive
|
|
1908
|
+
};
|
|
1909
|
+
}
|
|
1910
|
+
function parseNameList(p) {
|
|
1911
|
+
expectPunct(p, "(");
|
|
1912
|
+
const names = [expectName(p, "a column name")];
|
|
1913
|
+
while (acceptPunct(p, ",")) names.push(expectName(p, "a column name"));
|
|
1914
|
+
expectPunct(p, ")");
|
|
1915
|
+
return names;
|
|
1916
|
+
}
|
|
1917
|
+
function parseLimit(p) {
|
|
1918
|
+
if (acceptWord(p, "LIMIT")) {
|
|
1919
|
+
const first = acceptWord(p, "ALL") ? null : parseExpr(p);
|
|
1920
|
+
if (acceptPunct(p, ",")) return {
|
|
1921
|
+
limit: parseExpr(p),
|
|
1922
|
+
offset: first
|
|
1923
|
+
};
|
|
1924
|
+
return {
|
|
1925
|
+
limit: first,
|
|
1926
|
+
offset: acceptWord(p, "OFFSET") ? parseOffsetValue(p) : null
|
|
1927
|
+
};
|
|
1928
|
+
}
|
|
1929
|
+
if (acceptWord(p, "OFFSET")) {
|
|
1930
|
+
const offset = parseOffsetValue(p);
|
|
1931
|
+
if (acceptWord(p, "FETCH")) {
|
|
1932
|
+
if (!acceptWord(p, "FIRST") && !acceptWord(p, "NEXT")) fail(p, "Expected FIRST or NEXT");
|
|
1933
|
+
const limit = atWord(p, "ROW") || atWord(p, "ROWS") ? null : parseExpr(p);
|
|
1934
|
+
if (!acceptWord(p, "ROWS") && !acceptWord(p, "ROW")) fail(p, "Expected ROWS");
|
|
1935
|
+
expectWord(p, "ONLY");
|
|
1936
|
+
return {
|
|
1937
|
+
limit,
|
|
1938
|
+
offset
|
|
1939
|
+
};
|
|
1940
|
+
}
|
|
1941
|
+
return {
|
|
1942
|
+
limit: acceptWord(p, "LIMIT") ? parseExpr(p) : null,
|
|
1943
|
+
offset
|
|
1944
|
+
};
|
|
1945
|
+
}
|
|
1946
|
+
if (acceptWord(p, "FETCH")) {
|
|
1947
|
+
if (!acceptWord(p, "FIRST") && !acceptWord(p, "NEXT")) fail(p, "Expected FIRST or NEXT");
|
|
1948
|
+
const limit = atWord(p, "ROW") || atWord(p, "ROWS") ? null : parseExpr(p);
|
|
1949
|
+
if (!acceptWord(p, "ROWS") && !acceptWord(p, "ROW")) fail(p, "Expected ROWS");
|
|
1950
|
+
expectWord(p, "ONLY");
|
|
1951
|
+
return {
|
|
1952
|
+
limit,
|
|
1953
|
+
offset: null
|
|
1954
|
+
};
|
|
1955
|
+
}
|
|
1956
|
+
return {
|
|
1957
|
+
limit: null,
|
|
1958
|
+
offset: null
|
|
1959
|
+
};
|
|
1960
|
+
}
|
|
1961
|
+
function parseOffsetValue(p) {
|
|
1962
|
+
const value = parseExpr(p);
|
|
1963
|
+
if (!acceptWord(p, "ROWS")) acceptWord(p, "ROW");
|
|
1964
|
+
return value;
|
|
1965
|
+
}
|
|
1966
|
+
function parseSetOperation(p) {
|
|
1967
|
+
const start = peek(p).start;
|
|
1968
|
+
const left = parseQueryTerm(p);
|
|
1969
|
+
const token = peek(p);
|
|
1970
|
+
if (token.kind !== "word" || !SET_OPERATORS.has(token.text)) return left;
|
|
1971
|
+
advance(p);
|
|
1972
|
+
const all = acceptWord(p, "ALL");
|
|
1973
|
+
if (!all) acceptWord(p, "DISTINCT");
|
|
1974
|
+
return {
|
|
1975
|
+
type: "setop",
|
|
1976
|
+
op: token.text === "UNION" ? "UNION" : token.text === "INTERSECT" ? "INTERSECT" : "EXCEPT",
|
|
1977
|
+
all,
|
|
1978
|
+
left,
|
|
1979
|
+
right: parseSetOperation(p),
|
|
1980
|
+
range: rangeFrom(p, start)
|
|
1981
|
+
};
|
|
1982
|
+
}
|
|
1983
|
+
function parseQueryTerm(p) {
|
|
1984
|
+
const start = peek(p).start;
|
|
1985
|
+
if (atPunct(p, "(")) {
|
|
1986
|
+
advance(p);
|
|
1987
|
+
const body = parseSetOperation(p);
|
|
1988
|
+
expectPunct(p, ")");
|
|
1989
|
+
return body;
|
|
1990
|
+
}
|
|
1991
|
+
if (atWord(p, "VALUES")) {
|
|
1992
|
+
advance(p);
|
|
1993
|
+
const rows = [];
|
|
1994
|
+
do {
|
|
1995
|
+
expectPunct(p, "(");
|
|
1996
|
+
rows.push(parseExprList(p));
|
|
1997
|
+
expectPunct(p, ")");
|
|
1998
|
+
} while (acceptPunct(p, ","));
|
|
1999
|
+
return {
|
|
2000
|
+
type: "values",
|
|
2001
|
+
rows,
|
|
2002
|
+
range: rangeFrom(p, start)
|
|
2003
|
+
};
|
|
2004
|
+
}
|
|
2005
|
+
return parseSelectCore(p);
|
|
2006
|
+
}
|
|
2007
|
+
function parseSelectCore(p) {
|
|
2008
|
+
const start = peek(p).start;
|
|
2009
|
+
expectWord(p, "SELECT");
|
|
2010
|
+
const distinct = acceptWord(p, "DISTINCT");
|
|
2011
|
+
if (!distinct) acceptWord(p, "ALL");
|
|
2012
|
+
if (distinct && acceptWord(p, "ON")) {
|
|
2013
|
+
expectPunct(p, "(");
|
|
2014
|
+
parseExprList(p);
|
|
2015
|
+
expectPunct(p, ")");
|
|
2016
|
+
}
|
|
2017
|
+
const columns = parseSelectItems(p);
|
|
2018
|
+
const from = acceptWord(p, "FROM") ? parseFromList(p) : [];
|
|
2019
|
+
const where = acceptWord(p, "WHERE") ? parseExpr(p) : null;
|
|
2020
|
+
const groupBy = acceptWords(p, "GROUP", "BY") ? parseGroupBy(p) : [];
|
|
2021
|
+
const having = acceptWord(p, "HAVING") ? parseExpr(p) : null;
|
|
2022
|
+
if (acceptWord(p, "WINDOW")) do {
|
|
2023
|
+
expectName(p, "a window name");
|
|
2024
|
+
expectWord(p, "AS");
|
|
2025
|
+
parseWindow(p);
|
|
2026
|
+
} while (acceptPunct(p, ","));
|
|
2027
|
+
return {
|
|
2028
|
+
type: "select",
|
|
2029
|
+
distinct,
|
|
2030
|
+
columns,
|
|
2031
|
+
from,
|
|
2032
|
+
where,
|
|
2033
|
+
groupBy,
|
|
2034
|
+
having,
|
|
2035
|
+
range: rangeFrom(p, start)
|
|
2036
|
+
};
|
|
2037
|
+
}
|
|
2038
|
+
function parseGroupBy(p) {
|
|
2039
|
+
if (acceptWord(p, "ALL")) return [];
|
|
2040
|
+
const items = [];
|
|
2041
|
+
do
|
|
2042
|
+
if (atWord(p, "ROLLUP") || atWord(p, "CUBE") || atWords(p, "GROUPING", "SETS")) {
|
|
2043
|
+
const start = peek(p).start;
|
|
2044
|
+
while (!atPunct(p, "(")) advance(p);
|
|
2045
|
+
advance(p);
|
|
2046
|
+
items.push(...parseExprList(p));
|
|
2047
|
+
expectPunct(p, ")");
|
|
2048
|
+
if (items.length === 0) items.push({
|
|
2049
|
+
type: "raw",
|
|
2050
|
+
text: p.text.slice(start, previousEnd(p)),
|
|
2051
|
+
range: rangeFrom(p, start)
|
|
2052
|
+
});
|
|
2053
|
+
} else items.push(parseExpr(p));
|
|
2054
|
+
while (acceptPunct(p, ","));
|
|
2055
|
+
if (acceptWord(p, "WITH")) expectWord(p, "ROLLUP");
|
|
2056
|
+
return items;
|
|
2057
|
+
}
|
|
2058
|
+
function atWords(p, ...words) {
|
|
2059
|
+
return words.every((word, index) => atWord(p, word, index));
|
|
2060
|
+
}
|
|
2061
|
+
function parseSelectItems(p) {
|
|
2062
|
+
const items = [];
|
|
2063
|
+
do {
|
|
2064
|
+
const start = peek(p).start;
|
|
2065
|
+
const expr = parseExpr(p);
|
|
2066
|
+
const alias = expr.type === "star" ? null : parseAlias(p);
|
|
2067
|
+
items.push({
|
|
2068
|
+
expr,
|
|
2069
|
+
alias,
|
|
2070
|
+
range: rangeFrom(p, start)
|
|
2071
|
+
});
|
|
2072
|
+
} while (acceptPunct(p, ","));
|
|
2073
|
+
return items;
|
|
2074
|
+
}
|
|
2075
|
+
function parseFromList(p) {
|
|
2076
|
+
const items = [parseJoins(p)];
|
|
2077
|
+
while (acceptPunct(p, ",")) items.push(parseJoins(p));
|
|
2078
|
+
return items;
|
|
2079
|
+
}
|
|
2080
|
+
function parseJoins(p) {
|
|
2081
|
+
const start = peek(p).start;
|
|
2082
|
+
return parseJoinTail(p, start, parseFromItem(p));
|
|
2083
|
+
}
|
|
2084
|
+
function parseJoinTail(p, start, left) {
|
|
2085
|
+
const token = peek(p);
|
|
2086
|
+
if (token.kind !== "word" || !JOIN_WORDS.has(token.text)) return left;
|
|
2087
|
+
const natural = acceptWord(p, "NATURAL");
|
|
2088
|
+
const joinType = parseJoinType(p);
|
|
2089
|
+
const right = parseFromItem(p);
|
|
2090
|
+
const on = acceptWord(p, "ON") ? parseExpr(p) : null;
|
|
2091
|
+
return parseJoinTail(p, start, {
|
|
2092
|
+
type: "join",
|
|
2093
|
+
joinType,
|
|
2094
|
+
natural,
|
|
2095
|
+
left,
|
|
2096
|
+
right,
|
|
2097
|
+
on,
|
|
2098
|
+
using: on === null && acceptWord(p, "USING") ? parseNameList(p) : null,
|
|
2099
|
+
range: rangeFrom(p, start)
|
|
2100
|
+
});
|
|
2101
|
+
}
|
|
2102
|
+
function parseJoinType(p) {
|
|
2103
|
+
if (acceptWord(p, "JOIN")) return "INNER";
|
|
2104
|
+
const word = advance(p);
|
|
2105
|
+
const type = word.text === "LEFT" ? "LEFT" : word.text === "RIGHT" ? "RIGHT" : word.text === "FULL" ? "FULL" : word.text === "CROSS" ? "CROSS" : "INNER";
|
|
2106
|
+
if (word.text !== "INNER" && word.text !== "CROSS" && word.text !== "LEFT" && word.text !== "RIGHT" && word.text !== "FULL") fail(p, "Expected JOIN");
|
|
2107
|
+
acceptWord(p, "OUTER");
|
|
2108
|
+
expectWord(p, "JOIN");
|
|
2109
|
+
return type;
|
|
2110
|
+
}
|
|
2111
|
+
function parseFromItem(p) {
|
|
2112
|
+
const start = peek(p).start;
|
|
2113
|
+
const lateral = acceptWord(p, "LATERAL");
|
|
2114
|
+
if (atPunct(p, "(")) {
|
|
2115
|
+
if (atQueryStartAt(p, 1)) {
|
|
2116
|
+
advance(p);
|
|
2117
|
+
const query = parseQuery(p);
|
|
2118
|
+
expectPunct(p, ")");
|
|
2119
|
+
const alias = parseAlias(p);
|
|
2120
|
+
if (alias !== null && atPunct(p, "(")) parseNameList(p);
|
|
2121
|
+
return {
|
|
2122
|
+
type: "subquery",
|
|
2123
|
+
query,
|
|
2124
|
+
alias,
|
|
2125
|
+
lateral,
|
|
2126
|
+
range: rangeFrom(p, start)
|
|
2127
|
+
};
|
|
2128
|
+
}
|
|
2129
|
+
advance(p);
|
|
2130
|
+
const inner = parseJoins(p);
|
|
2131
|
+
expectPunct(p, ")");
|
|
2132
|
+
return inner;
|
|
2133
|
+
}
|
|
2134
|
+
if (atWord(p, "ONLY")) advance(p);
|
|
2135
|
+
if (!isNameToken(peek(p))) fail(p, "Expected a table name");
|
|
2136
|
+
if (atPunct(p, "(", 1) || atPunct(p, ".", 1) && atPunct(p, "(", 3)) {
|
|
2137
|
+
const call = parseNameExpr(p);
|
|
2138
|
+
const alias = parseAlias(p);
|
|
2139
|
+
if (alias !== null && atPunct(p, "(")) parseNameList(p);
|
|
2140
|
+
return {
|
|
2141
|
+
type: "function",
|
|
2142
|
+
call,
|
|
2143
|
+
alias,
|
|
2144
|
+
range: rangeFrom(p, start)
|
|
2145
|
+
};
|
|
2146
|
+
}
|
|
2147
|
+
const table = parseTableName(p);
|
|
2148
|
+
const alias = parseAlias(p);
|
|
2149
|
+
if (alias !== null && atPunct(p, "(")) parseNameList(p);
|
|
2150
|
+
return {
|
|
2151
|
+
type: "table",
|
|
2152
|
+
table,
|
|
2153
|
+
alias,
|
|
2154
|
+
range: rangeFrom(p, start)
|
|
2155
|
+
};
|
|
2156
|
+
}
|
|
2157
|
+
function parseTableName(p) {
|
|
2158
|
+
const start = peek(p).start;
|
|
2159
|
+
const parts = [expectName(p, "a table name")];
|
|
2160
|
+
while (atPunct(p, ".")) {
|
|
2161
|
+
advance(p);
|
|
2162
|
+
parts.push(expectName(p, "a table name"));
|
|
2163
|
+
}
|
|
2164
|
+
const name = parts.at(-1) ?? "";
|
|
2165
|
+
return {
|
|
2166
|
+
schema: parts.length > 1 ? parts.slice(0, -1).join(".") : null,
|
|
2167
|
+
name,
|
|
2168
|
+
range: rangeFrom(p, start)
|
|
2169
|
+
};
|
|
2170
|
+
}
|
|
2171
|
+
function parseReturning(p) {
|
|
2172
|
+
return acceptWord(p, "RETURNING") ? parseSelectItems(p) : null;
|
|
2173
|
+
}
|
|
2174
|
+
function parseInsert(p, start, ctes) {
|
|
2175
|
+
advance(p);
|
|
2176
|
+
if (acceptWord(p, "OR")) advance(p);
|
|
2177
|
+
acceptWord(p, "IGNORE");
|
|
2178
|
+
acceptWord(p, "INTO");
|
|
2179
|
+
const table = parseTableName(p);
|
|
2180
|
+
const alias = atWord(p, "AS") || isNameToken(peek(p)) && !atWord(p, "VALUES") && !atWord(p, "SELECT") && !atWord(p, "DEFAULT") && !atPunct(p, "(") ? parseAlias(p) : null;
|
|
2181
|
+
const columns = atPunct(p, "(") && !atQueryStartAt(p, 1) ? parseNameList(p) : null;
|
|
2182
|
+
const sourceStart = peek(p).start;
|
|
2183
|
+
const source = (() => {
|
|
2184
|
+
if (acceptWords(p, "DEFAULT", "VALUES")) return {
|
|
2185
|
+
type: "default",
|
|
2186
|
+
range: rangeFrom(p, sourceStart)
|
|
2187
|
+
};
|
|
2188
|
+
if (atWord(p, "VALUES")) {
|
|
2189
|
+
advance(p);
|
|
2190
|
+
const rows = [];
|
|
2191
|
+
do {
|
|
2192
|
+
expectPunct(p, "(");
|
|
2193
|
+
rows.push(atPunct(p, ")") ? [] : parseExprList(p));
|
|
2194
|
+
expectPunct(p, ")");
|
|
2195
|
+
} while (acceptPunct(p, ","));
|
|
2196
|
+
return {
|
|
2197
|
+
type: "values",
|
|
2198
|
+
rows,
|
|
2199
|
+
range: rangeFrom(p, sourceStart)
|
|
2200
|
+
};
|
|
2201
|
+
}
|
|
2202
|
+
if (atQueryStart(p)) return {
|
|
2203
|
+
type: "query",
|
|
2204
|
+
query: parseQuery(p),
|
|
2205
|
+
range: rangeFrom(p, sourceStart)
|
|
2206
|
+
};
|
|
2207
|
+
return fail(p, "Expected VALUES, SELECT or DEFAULT VALUES");
|
|
2208
|
+
})();
|
|
2209
|
+
const conflictStart = peek(p).start;
|
|
2210
|
+
return {
|
|
2211
|
+
type: "insert",
|
|
2212
|
+
ctes,
|
|
2213
|
+
table,
|
|
2214
|
+
alias,
|
|
2215
|
+
columns,
|
|
2216
|
+
source,
|
|
2217
|
+
onConflict: atWord(p, "ON") ? skipConflictClause(p, conflictStart) : null,
|
|
2218
|
+
returning: parseReturning(p),
|
|
2219
|
+
range: rangeFrom(p, start)
|
|
2220
|
+
};
|
|
2221
|
+
}
|
|
2222
|
+
/** `ON CONFLICT ... DO NOTHING | DO UPDATE SET ...` and MySQL's `ON DUPLICATE KEY UPDATE ...`, kept as a range. */
|
|
2223
|
+
function skipConflictClause(p, start) {
|
|
2224
|
+
while (!atWord(p, "RETURNING") && !atPunct(p, ";") && peek(p).kind !== "eof") if (atPunct(p, "(")) {
|
|
2225
|
+
advance(p);
|
|
2226
|
+
let depth = 1;
|
|
2227
|
+
while (depth > 0 && peek(p).kind !== "eof") {
|
|
2228
|
+
if (atPunct(p, "(")) depth += 1;
|
|
2229
|
+
if (atPunct(p, ")")) depth -= 1;
|
|
2230
|
+
advance(p);
|
|
2231
|
+
}
|
|
2232
|
+
} else advance(p);
|
|
2233
|
+
return rangeFrom(p, start);
|
|
2234
|
+
}
|
|
2235
|
+
function parseUpdate(p, start, ctes) {
|
|
2236
|
+
advance(p);
|
|
2237
|
+
if (acceptWord(p, "OR")) advance(p);
|
|
2238
|
+
acceptWord(p, "ONLY");
|
|
2239
|
+
const table = parseTableName(p);
|
|
2240
|
+
const alias = atWord(p, "SET") ? null : parseAlias(p);
|
|
2241
|
+
expectWord(p, "SET");
|
|
2242
|
+
const set = [];
|
|
2243
|
+
do {
|
|
2244
|
+
const itemStart = peek(p).start;
|
|
2245
|
+
const column = expectName(p, "a column name");
|
|
2246
|
+
while (atPunct(p, ".")) {
|
|
2247
|
+
advance(p);
|
|
2248
|
+
expectName(p, "a column name");
|
|
2249
|
+
}
|
|
2250
|
+
if (!atOp(p, "=")) fail(p, "Expected \"=\"");
|
|
2251
|
+
advance(p);
|
|
2252
|
+
const value = acceptWord(p, "DEFAULT") ? {
|
|
2253
|
+
type: "raw",
|
|
2254
|
+
text: "DEFAULT",
|
|
2255
|
+
range: rangeFrom(p, itemStart)
|
|
2256
|
+
} : parseExpr(p);
|
|
2257
|
+
set.push({
|
|
2258
|
+
column,
|
|
2259
|
+
value,
|
|
2260
|
+
range: rangeFrom(p, itemStart)
|
|
2261
|
+
});
|
|
2262
|
+
} while (acceptPunct(p, ","));
|
|
2263
|
+
const from = acceptWord(p, "FROM") ? parseFromList(p) : [];
|
|
2264
|
+
const where = acceptWord(p, "WHERE") ? parseExpr(p) : null;
|
|
2265
|
+
if (acceptWords(p, "ORDER", "BY")) parseOrderItems(p);
|
|
2266
|
+
if (acceptWord(p, "LIMIT")) parseExpr(p);
|
|
2267
|
+
return {
|
|
2268
|
+
type: "update",
|
|
2269
|
+
ctes,
|
|
2270
|
+
table,
|
|
2271
|
+
alias,
|
|
2272
|
+
set,
|
|
2273
|
+
from,
|
|
2274
|
+
where,
|
|
2275
|
+
returning: parseReturning(p),
|
|
2276
|
+
range: rangeFrom(p, start)
|
|
2277
|
+
};
|
|
2278
|
+
}
|
|
2279
|
+
function parseDelete(p, start, ctes) {
|
|
2280
|
+
advance(p);
|
|
2281
|
+
expectWord(p, "FROM");
|
|
2282
|
+
acceptWord(p, "ONLY");
|
|
2283
|
+
const table = parseTableName(p);
|
|
2284
|
+
const alias = atWord(p, "USING") || atWord(p, "WHERE") || atWord(p, "RETURNING") ? null : parseAlias(p);
|
|
2285
|
+
const using = acceptWord(p, "USING") ? parseFromList(p) : [];
|
|
2286
|
+
const where = acceptWord(p, "WHERE") ? parseExpr(p) : null;
|
|
2287
|
+
if (acceptWords(p, "ORDER", "BY")) parseOrderItems(p);
|
|
2288
|
+
if (acceptWord(p, "LIMIT")) parseExpr(p);
|
|
2289
|
+
return {
|
|
2290
|
+
type: "delete",
|
|
2291
|
+
ctes,
|
|
2292
|
+
table,
|
|
2293
|
+
alias,
|
|
2294
|
+
using,
|
|
2295
|
+
where,
|
|
2296
|
+
returning: parseReturning(p),
|
|
2297
|
+
range: rangeFrom(p, start)
|
|
2298
|
+
};
|
|
2299
|
+
}
|
|
2300
|
+
function parseStatement(p) {
|
|
2301
|
+
const start = peek(p).start;
|
|
2302
|
+
const first = peek(p);
|
|
2303
|
+
if (isWord(first, "WITH") || isWord(first, "SELECT") || isWord(first, "VALUES") || atPunct(p, "(")) {
|
|
2304
|
+
const { ctes, recursive } = parseWith(p);
|
|
2305
|
+
if (ctes.length > 0 && (atWord(p, "INSERT") || atWord(p, "REPLACE"))) return parseInsert(p, start, ctes);
|
|
2306
|
+
if (ctes.length > 0 && atWord(p, "UPDATE")) return parseUpdate(p, start, ctes);
|
|
2307
|
+
if (ctes.length > 0 && atWord(p, "DELETE")) return parseDelete(p, start, ctes);
|
|
2308
|
+
const body = parseSetOperation(p);
|
|
2309
|
+
const orderBy = acceptWords(p, "ORDER", "BY") ? parseOrderItems(p) : [];
|
|
2310
|
+
const { limit, offset } = parseLimit(p);
|
|
2311
|
+
return {
|
|
2312
|
+
type: "select",
|
|
2313
|
+
query: {
|
|
2314
|
+
type: "query",
|
|
2315
|
+
ctes,
|
|
2316
|
+
recursive,
|
|
2317
|
+
body,
|
|
2318
|
+
orderBy,
|
|
2319
|
+
limit,
|
|
2320
|
+
offset,
|
|
2321
|
+
range: rangeFrom(p, start)
|
|
2322
|
+
},
|
|
2323
|
+
range: rangeFrom(p, start)
|
|
2324
|
+
};
|
|
2325
|
+
}
|
|
2326
|
+
if (isWord(first, "INSERT") || isWord(first, "REPLACE")) return parseInsert(p, start, []);
|
|
2327
|
+
if (isWord(first, "UPDATE")) return parseUpdate(p, start, []);
|
|
2328
|
+
if (isWord(first, "DELETE")) return parseDelete(p, start, []);
|
|
2329
|
+
const keyword = first.kind === "word" ? first.text : first.raw;
|
|
2330
|
+
skipToStatementEnd(p);
|
|
2331
|
+
return {
|
|
2332
|
+
type: "other",
|
|
2333
|
+
keyword,
|
|
2334
|
+
range: rangeFrom(p, start)
|
|
2335
|
+
};
|
|
2336
|
+
}
|
|
2337
|
+
function skipToStatementEnd(p) {
|
|
2338
|
+
let depth = 0;
|
|
2339
|
+
while (peek(p).kind !== "eof" && !(depth === 0 && atPunct(p, ";"))) {
|
|
2340
|
+
if (atPunct(p, "(")) depth += 1;
|
|
2341
|
+
if (atPunct(p, ")")) depth = Math.max(0, depth - 1);
|
|
2342
|
+
advance(p);
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
/** Every statement of the text, in order; a statement that fails to parse is `invalid` and parsing resumes at the next `;`. */
|
|
2346
|
+
function parseStatements(text) {
|
|
2347
|
+
const tokenized = tokenize(text);
|
|
2348
|
+
if (!tokenized.ok) return [{
|
|
2349
|
+
type: "invalid",
|
|
2350
|
+
message: tokenized.error.message,
|
|
2351
|
+
offset: tokenized.error.offset,
|
|
2352
|
+
range: {
|
|
2353
|
+
start: 0,
|
|
2354
|
+
end: text.length
|
|
2355
|
+
}
|
|
2356
|
+
}];
|
|
2357
|
+
const p = {
|
|
2358
|
+
text,
|
|
2359
|
+
tokens: tokenized.tokens,
|
|
2360
|
+
pos: 0
|
|
2361
|
+
};
|
|
2362
|
+
const statements = [];
|
|
2363
|
+
while (peek(p).kind !== "eof") {
|
|
2364
|
+
if (acceptPunct(p, ";")) continue;
|
|
2365
|
+
const start = peek(p).start;
|
|
2366
|
+
try {
|
|
2367
|
+
const statement = parseStatement(p);
|
|
2368
|
+
if (!atPunct(p, ";") && peek(p).kind !== "eof") fail(p, `Unexpected "${peek(p).raw}"`);
|
|
2369
|
+
statements.push(statement);
|
|
2370
|
+
} catch (e) {
|
|
2371
|
+
if (!(e instanceof ParseFailure)) throw e;
|
|
2372
|
+
skipToStatementEnd(p);
|
|
2373
|
+
statements.push({
|
|
2374
|
+
type: "invalid",
|
|
2375
|
+
message: e.message,
|
|
2376
|
+
offset: e.offset,
|
|
2377
|
+
range: {
|
|
2378
|
+
start,
|
|
2379
|
+
end: Math.max(previousEnd(p), start)
|
|
2380
|
+
}
|
|
2381
|
+
});
|
|
2382
|
+
}
|
|
2383
|
+
acceptPunct(p, ";");
|
|
2384
|
+
}
|
|
2385
|
+
return statements;
|
|
2386
|
+
}
|
|
2387
|
+
//#endregion
|
|
2388
|
+
//#region src/sql/types.ts
|
|
2389
|
+
/** SQLite's type affinity rules (https://www.sqlite.org/datatype3.html#affname), plus the conventional date/time and JSON spellings that store text. */
|
|
2390
|
+
function sqliteTsType(dataType) {
|
|
2391
|
+
const upper = dataType.toUpperCase();
|
|
2392
|
+
if (upper === "") return "unknown";
|
|
2393
|
+
if (upper.includes("INT")) return "number";
|
|
2394
|
+
if (upper.includes("CHAR") || upper.includes("CLOB") || upper.includes("TEXT")) return "string";
|
|
2395
|
+
if (upper.includes("BLOB")) return "Uint8Array";
|
|
2396
|
+
if (upper.includes("REAL") || upper.includes("FLOA") || upper.includes("DOUB")) return "number";
|
|
2397
|
+
if (upper.includes("BOOL")) return "number";
|
|
2398
|
+
if (upper.includes("DATE") || upper.includes("TIME") || upper.includes("JSON")) return "string";
|
|
2399
|
+
if (upper.includes("DEC") || upper.includes("NUM")) return "number";
|
|
2400
|
+
return "number";
|
|
2401
|
+
}
|
|
2402
|
+
const POSTGRES_TYPES = {
|
|
2403
|
+
int2: "number",
|
|
2404
|
+
smallint: "number",
|
|
2405
|
+
int4: "number",
|
|
2406
|
+
int: "number",
|
|
2407
|
+
integer: "number",
|
|
2408
|
+
serial: "number",
|
|
2409
|
+
serial4: "number",
|
|
2410
|
+
smallserial: "number",
|
|
2411
|
+
float4: "number",
|
|
2412
|
+
real: "number",
|
|
2413
|
+
float8: "number",
|
|
2414
|
+
"double precision": "number",
|
|
2415
|
+
oid: "number",
|
|
2416
|
+
int8: "string",
|
|
2417
|
+
bigint: "string",
|
|
2418
|
+
bigserial: "string",
|
|
2419
|
+
serial8: "string",
|
|
2420
|
+
numeric: "string",
|
|
2421
|
+
decimal: "string",
|
|
2422
|
+
money: "string",
|
|
2423
|
+
text: "string",
|
|
2424
|
+
varchar: "string",
|
|
2425
|
+
"character varying": "string",
|
|
2426
|
+
bpchar: "string",
|
|
2427
|
+
char: "string",
|
|
2428
|
+
character: "string",
|
|
2429
|
+
name: "string",
|
|
2430
|
+
citext: "string",
|
|
2431
|
+
uuid: "string",
|
|
2432
|
+
time: "string",
|
|
2433
|
+
timetz: "string",
|
|
2434
|
+
"time without time zone": "string",
|
|
2435
|
+
"time with time zone": "string",
|
|
2436
|
+
interval: "string",
|
|
2437
|
+
inet: "string",
|
|
2438
|
+
cidr: "string",
|
|
2439
|
+
macaddr: "string",
|
|
2440
|
+
xml: "string",
|
|
2441
|
+
tsvector: "string",
|
|
2442
|
+
tsquery: "string",
|
|
2443
|
+
bit: "string",
|
|
2444
|
+
varbit: "string",
|
|
2445
|
+
bool: "boolean",
|
|
2446
|
+
boolean: "boolean",
|
|
2447
|
+
date: "Date",
|
|
2448
|
+
timestamp: "Date",
|
|
2449
|
+
timestamptz: "Date",
|
|
2450
|
+
"timestamp without time zone": "Date",
|
|
2451
|
+
"timestamp with time zone": "Date",
|
|
2452
|
+
bytea: "Uint8Array",
|
|
2453
|
+
json: "unknown",
|
|
2454
|
+
jsonb: "unknown"
|
|
2455
|
+
};
|
|
2456
|
+
function postgresTsType(dataType) {
|
|
2457
|
+
const lower = dataType.toLowerCase().trim();
|
|
2458
|
+
if (lower.endsWith("[]")) return `${postgresTsType(lower.slice(0, -2))}[]`;
|
|
2459
|
+
if (lower.startsWith("_")) return `${postgresTsType(lower.slice(1))}[]`;
|
|
2460
|
+
const base = lower.replace(/\(.*\)$/u, "").trim();
|
|
2461
|
+
return POSTGRES_TYPES[base] ?? "unknown";
|
|
2462
|
+
}
|
|
2463
|
+
const MYSQL_TYPES = {
|
|
2464
|
+
tinyint: "number",
|
|
2465
|
+
smallint: "number",
|
|
2466
|
+
mediumint: "number",
|
|
2467
|
+
int: "number",
|
|
2468
|
+
integer: "number",
|
|
2469
|
+
bigint: "number",
|
|
2470
|
+
year: "number",
|
|
2471
|
+
float: "number",
|
|
2472
|
+
double: "number",
|
|
2473
|
+
real: "number",
|
|
2474
|
+
decimal: "string",
|
|
2475
|
+
numeric: "string",
|
|
2476
|
+
varchar: "string",
|
|
2477
|
+
char: "string",
|
|
2478
|
+
text: "string",
|
|
2479
|
+
tinytext: "string",
|
|
2480
|
+
mediumtext: "string",
|
|
2481
|
+
longtext: "string",
|
|
2482
|
+
enum: "string",
|
|
2483
|
+
set: "string",
|
|
2484
|
+
time: "string",
|
|
2485
|
+
date: "Date",
|
|
2486
|
+
datetime: "Date",
|
|
2487
|
+
timestamp: "Date",
|
|
2488
|
+
bit: "Uint8Array",
|
|
2489
|
+
binary: "Uint8Array",
|
|
2490
|
+
varbinary: "Uint8Array",
|
|
2491
|
+
blob: "Uint8Array",
|
|
2492
|
+
tinyblob: "Uint8Array",
|
|
2493
|
+
mediumblob: "Uint8Array",
|
|
2494
|
+
longblob: "Uint8Array",
|
|
2495
|
+
geometry: "Uint8Array",
|
|
2496
|
+
json: "unknown",
|
|
2497
|
+
boolean: "number",
|
|
2498
|
+
bool: "number"
|
|
2499
|
+
};
|
|
2500
|
+
function mysqlTsType(dataType) {
|
|
2501
|
+
const base = dataType.toLowerCase().replace(/\(.*\)$/u, "").replace(/\s+unsigned$/u, "").trim();
|
|
2502
|
+
return MYSQL_TYPES[base] ?? "unknown";
|
|
2503
|
+
}
|
|
2504
|
+
/** The TypeScript type a driver hands back for a column of the declared type. */
|
|
2505
|
+
function toTsType(dialect, dataType) {
|
|
2506
|
+
switch (dialect) {
|
|
2507
|
+
case "sqlite": return sqliteTsType(dataType);
|
|
2508
|
+
case "postgresql": return postgresTsType(dataType);
|
|
2509
|
+
case "mysql": return mysqlTsType(dataType);
|
|
2510
|
+
default: return "unknown";
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
/** The declared type a literal of the expression kind would have in the dialect, for the type column of the picture. */
|
|
2514
|
+
function literalDataType(dialect, kind) {
|
|
2515
|
+
if (kind === "string") return dialect === "sqlite" ? "TEXT" : dialect === "mysql" ? "varchar" : "text";
|
|
2516
|
+
if (kind === "number") return dialect === "sqlite" ? "INTEGER" : dialect === "mysql" ? "int" : "int4";
|
|
2517
|
+
return dialect === "postgresql" ? "bool" : dialect === "mysql" ? "tinyint" : "INTEGER";
|
|
2518
|
+
}
|
|
2519
|
+
//#endregion
|
|
2520
|
+
//#region src/sql/analyze.ts
|
|
2521
|
+
const UNKNOWN = {
|
|
2522
|
+
dataType: null,
|
|
2523
|
+
tsType: "unknown",
|
|
2524
|
+
nullable: null,
|
|
2525
|
+
sources: []
|
|
2526
|
+
};
|
|
2527
|
+
function nextId(ctx) {
|
|
2528
|
+
ctx.counter += 1;
|
|
2529
|
+
return `n${ctx.counter}`;
|
|
2530
|
+
}
|
|
2531
|
+
function snippet(ctx, range, limit = 120) {
|
|
2532
|
+
if (range === null) return "";
|
|
2533
|
+
const text = ctx.text.slice(range.start, range.end).replaceAll(/\s+/gu, " ").trim();
|
|
2534
|
+
return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
|
|
2535
|
+
}
|
|
2536
|
+
function addNode(ctx, node) {
|
|
2537
|
+
const id = nextId(ctx);
|
|
2538
|
+
ctx.nodes.push({
|
|
2539
|
+
id,
|
|
2540
|
+
...node
|
|
2541
|
+
});
|
|
2542
|
+
return id;
|
|
2543
|
+
}
|
|
2544
|
+
function addEdge(ctx, source, target, label = null, kind = "flow") {
|
|
2545
|
+
ctx.edges.push({
|
|
2546
|
+
id: `${source}->${target}:${ctx.edges.length}`,
|
|
2547
|
+
source,
|
|
2548
|
+
target,
|
|
2549
|
+
label,
|
|
2550
|
+
kind
|
|
2551
|
+
});
|
|
2552
|
+
}
|
|
2553
|
+
function warn(ctx, message, range, severity = "warning") {
|
|
2554
|
+
ctx.diagnostics.push({
|
|
2555
|
+
severity,
|
|
2556
|
+
message,
|
|
2557
|
+
range
|
|
2558
|
+
});
|
|
2559
|
+
}
|
|
2560
|
+
function typeOfColumn(ctx, column) {
|
|
2561
|
+
return {
|
|
2562
|
+
dataType: column.dataType,
|
|
2563
|
+
tsType: toTsType(ctx.dialect, column.dataType),
|
|
2564
|
+
nullable: column.nullable,
|
|
2565
|
+
sources: []
|
|
2566
|
+
};
|
|
2567
|
+
}
|
|
2568
|
+
function nullableOr(...types) {
|
|
2569
|
+
if (types.some((type) => type.nullable === true)) return true;
|
|
2570
|
+
if (types.every((type) => type.nullable === false)) return false;
|
|
2571
|
+
return null;
|
|
2572
|
+
}
|
|
2573
|
+
function withNullable(type, nullable) {
|
|
2574
|
+
return {
|
|
2575
|
+
...type,
|
|
2576
|
+
nullable
|
|
2577
|
+
};
|
|
2578
|
+
}
|
|
2579
|
+
function booleanType(ctx, nullable, sources) {
|
|
2580
|
+
return {
|
|
2581
|
+
dataType: literalDataType(ctx.dialect, "boolean"),
|
|
2582
|
+
tsType: toTsType(ctx.dialect, literalDataType(ctx.dialect, "boolean")),
|
|
2583
|
+
nullable,
|
|
2584
|
+
sources
|
|
2585
|
+
};
|
|
2586
|
+
}
|
|
2587
|
+
function numberType(ctx, nullable, sources) {
|
|
2588
|
+
return {
|
|
2589
|
+
dataType: literalDataType(ctx.dialect, "number"),
|
|
2590
|
+
tsType: "number",
|
|
2591
|
+
nullable,
|
|
2592
|
+
sources
|
|
2593
|
+
};
|
|
2594
|
+
}
|
|
2595
|
+
function stringType(ctx, nullable, sources) {
|
|
2596
|
+
return {
|
|
2597
|
+
dataType: literalDataType(ctx.dialect, "string"),
|
|
2598
|
+
tsType: "string",
|
|
2599
|
+
nullable,
|
|
2600
|
+
sources
|
|
2601
|
+
};
|
|
2602
|
+
}
|
|
2603
|
+
function sourcesOf(...types) {
|
|
2604
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2605
|
+
return types.flatMap((type) => type.sources).filter((source) => {
|
|
2606
|
+
const key = `${source.table}.${source.column}`;
|
|
2607
|
+
if (seen.has(key)) return false;
|
|
2608
|
+
seen.add(key);
|
|
2609
|
+
return true;
|
|
2610
|
+
});
|
|
2611
|
+
}
|
|
2612
|
+
function findRelation(scope, qualifier) {
|
|
2613
|
+
if (scope === null) return null;
|
|
2614
|
+
const key = qualifier.toLowerCase();
|
|
2615
|
+
return scope.relations.find((relation) => relation.key === key) ?? findRelation(scope.outer, qualifier);
|
|
2616
|
+
}
|
|
2617
|
+
function columnOf(relation, name) {
|
|
2618
|
+
const lower = name.toLowerCase();
|
|
2619
|
+
return relation.columns.find((column) => column.name.toLowerCase() === lower) ?? null;
|
|
2620
|
+
}
|
|
2621
|
+
function fromRelation(relation, name) {
|
|
2622
|
+
relation.used.add(name);
|
|
2623
|
+
const column = columnOf(relation, name);
|
|
2624
|
+
if (column !== null) return {
|
|
2625
|
+
...column,
|
|
2626
|
+
nullable: relation.outerNullable ? true : column.nullable
|
|
2627
|
+
};
|
|
2628
|
+
return {
|
|
2629
|
+
...UNKNOWN,
|
|
2630
|
+
nullable: relation.outerNullable ? true : null,
|
|
2631
|
+
sources: relation.tableName === null ? [] : [{
|
|
2632
|
+
table: relation.tableName,
|
|
2633
|
+
column: name
|
|
2634
|
+
}]
|
|
2635
|
+
};
|
|
2636
|
+
}
|
|
2637
|
+
/** The column a reference names, found in the nearest scope that has it. */
|
|
2638
|
+
function resolveColumn(ctx, scope, qualifier, name, range, aliases) {
|
|
2639
|
+
if (qualifier !== null) {
|
|
2640
|
+
const relation = findRelation(scope, qualifier);
|
|
2641
|
+
if (relation === null) {
|
|
2642
|
+
warn(ctx, `"${qualifier}" is not a table or alias in scope`, range);
|
|
2643
|
+
return UNKNOWN;
|
|
2644
|
+
}
|
|
2645
|
+
if (relation.known && columnOf(relation, name) === null) warn(ctx, `"${relation.display}" has no column "${name}"`, range);
|
|
2646
|
+
return fromRelation(relation, name);
|
|
2647
|
+
}
|
|
2648
|
+
const aliased = aliases?.get(name.toLowerCase());
|
|
2649
|
+
if (aliased !== void 0) return aliased;
|
|
2650
|
+
const search = (current) => {
|
|
2651
|
+
if (current === null) return null;
|
|
2652
|
+
const lower = name.toLowerCase();
|
|
2653
|
+
const holders = current.relations.filter((relation) => columnOf(relation, lower) !== null);
|
|
2654
|
+
const first = holders[0];
|
|
2655
|
+
if (first !== void 0) {
|
|
2656
|
+
if (holders.length > 1) warn(ctx, `"${name}" is ambiguous: it is a column of ${holders.map((relation) => `"${relation.display}"`).join(" and ")}`, range);
|
|
2657
|
+
return fromRelation(first, name);
|
|
2658
|
+
}
|
|
2659
|
+
const unknowns = current.relations.filter((relation) => !relation.known);
|
|
2660
|
+
const only = unknowns[0];
|
|
2661
|
+
if (only !== void 0 && unknowns.length === 1 && current.relations.length === 1) return fromRelation(only, name);
|
|
2662
|
+
if (unknowns.length > 0) return { ...UNKNOWN };
|
|
2663
|
+
return search(current.outer);
|
|
2664
|
+
};
|
|
2665
|
+
const found = search(scope);
|
|
2666
|
+
if (found !== null) return found;
|
|
2667
|
+
if (scope.relations.length > 0 || scope.outer !== null) warn(ctx, `Unknown column "${name}"`, range);
|
|
2668
|
+
return UNKNOWN;
|
|
2669
|
+
}
|
|
2670
|
+
const AGGREGATES = /* @__PURE__ */ new Set([
|
|
2671
|
+
"count",
|
|
2672
|
+
"sum",
|
|
2673
|
+
"avg",
|
|
2674
|
+
"min",
|
|
2675
|
+
"max",
|
|
2676
|
+
"total",
|
|
2677
|
+
"group_concat",
|
|
2678
|
+
"string_agg",
|
|
2679
|
+
"array_agg",
|
|
2680
|
+
"json_agg",
|
|
2681
|
+
"jsonb_agg",
|
|
2682
|
+
"json_group_array",
|
|
2683
|
+
"json_group_object",
|
|
2684
|
+
"bool_and",
|
|
2685
|
+
"bool_or",
|
|
2686
|
+
"every",
|
|
2687
|
+
"json_arrayagg",
|
|
2688
|
+
"json_objectagg",
|
|
2689
|
+
"bit_and",
|
|
2690
|
+
"bit_or",
|
|
2691
|
+
"stddev",
|
|
2692
|
+
"variance",
|
|
2693
|
+
"percentile_cont",
|
|
2694
|
+
"percentile_disc"
|
|
2695
|
+
]);
|
|
2696
|
+
const NUMBER_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
2697
|
+
"count",
|
|
2698
|
+
"sum",
|
|
2699
|
+
"avg",
|
|
2700
|
+
"total",
|
|
2701
|
+
"abs",
|
|
2702
|
+
"round",
|
|
2703
|
+
"floor",
|
|
2704
|
+
"ceil",
|
|
2705
|
+
"ceiling",
|
|
2706
|
+
"random",
|
|
2707
|
+
"length",
|
|
2708
|
+
"char_length",
|
|
2709
|
+
"character_length",
|
|
2710
|
+
"octet_length",
|
|
2711
|
+
"instr",
|
|
2712
|
+
"position",
|
|
2713
|
+
"strpos",
|
|
2714
|
+
"row_number",
|
|
2715
|
+
"rank",
|
|
2716
|
+
"dense_rank",
|
|
2717
|
+
"ntile",
|
|
2718
|
+
"percent_rank",
|
|
2719
|
+
"cume_dist",
|
|
2720
|
+
"sign",
|
|
2721
|
+
"sqrt",
|
|
2722
|
+
"power",
|
|
2723
|
+
"pow",
|
|
2724
|
+
"exp",
|
|
2725
|
+
"ln",
|
|
2726
|
+
"log",
|
|
2727
|
+
"log10",
|
|
2728
|
+
"log2",
|
|
2729
|
+
"mod",
|
|
2730
|
+
"pi",
|
|
2731
|
+
"trunc",
|
|
2732
|
+
"truncate",
|
|
2733
|
+
"div",
|
|
2734
|
+
"width_bucket",
|
|
2735
|
+
"cardinality",
|
|
2736
|
+
"array_length",
|
|
2737
|
+
"json_array_length",
|
|
2738
|
+
"stddev",
|
|
2739
|
+
"variance",
|
|
2740
|
+
"extract",
|
|
2741
|
+
"date_part",
|
|
2742
|
+
"unixepoch",
|
|
2743
|
+
"julianday",
|
|
2744
|
+
"last_insert_rowid",
|
|
2745
|
+
"changes",
|
|
2746
|
+
"total_changes",
|
|
2747
|
+
"bit_length",
|
|
2748
|
+
"ascii",
|
|
2749
|
+
"unicode",
|
|
2750
|
+
"day",
|
|
2751
|
+
"month",
|
|
2752
|
+
"year",
|
|
2753
|
+
"hour",
|
|
2754
|
+
"minute",
|
|
2755
|
+
"second",
|
|
2756
|
+
"dayofweek",
|
|
2757
|
+
"dayofyear",
|
|
2758
|
+
"week",
|
|
2759
|
+
"quarter",
|
|
2760
|
+
"timestampdiff",
|
|
2761
|
+
"datediff",
|
|
2762
|
+
"found_rows",
|
|
2763
|
+
"row_count"
|
|
2764
|
+
]);
|
|
2765
|
+
const STRING_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
2766
|
+
"lower",
|
|
2767
|
+
"upper",
|
|
2768
|
+
"trim",
|
|
2769
|
+
"ltrim",
|
|
2770
|
+
"rtrim",
|
|
2771
|
+
"btrim",
|
|
2772
|
+
"substr",
|
|
2773
|
+
"substring",
|
|
2774
|
+
"replace",
|
|
2775
|
+
"concat",
|
|
2776
|
+
"concat_ws",
|
|
2777
|
+
"group_concat",
|
|
2778
|
+
"string_agg",
|
|
2779
|
+
"format",
|
|
2780
|
+
"to_char",
|
|
2781
|
+
"lpad",
|
|
2782
|
+
"rpad",
|
|
2783
|
+
"left",
|
|
2784
|
+
"right",
|
|
2785
|
+
"reverse",
|
|
2786
|
+
"repeat",
|
|
2787
|
+
"initcap",
|
|
2788
|
+
"md5",
|
|
2789
|
+
"sha1",
|
|
2790
|
+
"sha2",
|
|
2791
|
+
"hex",
|
|
2792
|
+
"quote",
|
|
2793
|
+
"typeof",
|
|
2794
|
+
"printf",
|
|
2795
|
+
"strftime",
|
|
2796
|
+
"date",
|
|
2797
|
+
"time",
|
|
2798
|
+
"datetime",
|
|
2799
|
+
"timediff",
|
|
2800
|
+
"char",
|
|
2801
|
+
"chr",
|
|
2802
|
+
"translate",
|
|
2803
|
+
"regexp_replace",
|
|
2804
|
+
"split_part",
|
|
2805
|
+
"to_hex",
|
|
2806
|
+
"encode",
|
|
2807
|
+
"decode",
|
|
2808
|
+
"uuid",
|
|
2809
|
+
"gen_random_uuid",
|
|
2810
|
+
"json_extract",
|
|
2811
|
+
"json_quote",
|
|
2812
|
+
"json_type",
|
|
2813
|
+
"json_group_array",
|
|
2814
|
+
"json_group_object",
|
|
2815
|
+
"json",
|
|
2816
|
+
"json_object",
|
|
2817
|
+
"json_array",
|
|
2818
|
+
"json_build_object",
|
|
2819
|
+
"json_build_array",
|
|
2820
|
+
"to_json",
|
|
2821
|
+
"row_to_json",
|
|
2822
|
+
"json_agg",
|
|
2823
|
+
"jsonb_agg",
|
|
2824
|
+
"jsonb_build_object",
|
|
2825
|
+
"jsonb_build_array",
|
|
2826
|
+
"to_jsonb",
|
|
2827
|
+
"json_arrayagg",
|
|
2828
|
+
"json_objectagg",
|
|
2829
|
+
"json_unquote",
|
|
2830
|
+
"json_set",
|
|
2831
|
+
"json_insert",
|
|
2832
|
+
"json_replace",
|
|
2833
|
+
"json_remove",
|
|
2834
|
+
"json_patch",
|
|
2835
|
+
"array_to_string",
|
|
2836
|
+
"nullif",
|
|
2837
|
+
"current_user",
|
|
2838
|
+
"session_user",
|
|
2839
|
+
"version",
|
|
2840
|
+
"database",
|
|
2841
|
+
"schema",
|
|
2842
|
+
"user",
|
|
2843
|
+
"sqlite_version",
|
|
2844
|
+
"date_format",
|
|
2845
|
+
"time_format",
|
|
2846
|
+
"inet_ntoa",
|
|
2847
|
+
"soundex",
|
|
2848
|
+
"space",
|
|
2849
|
+
"elt",
|
|
2850
|
+
"field",
|
|
2851
|
+
"mid",
|
|
2852
|
+
"substring_index",
|
|
2853
|
+
"ucase",
|
|
2854
|
+
"lcase",
|
|
2855
|
+
"bin",
|
|
2856
|
+
"oct",
|
|
2857
|
+
"conv",
|
|
2858
|
+
"unhex",
|
|
2859
|
+
"compress",
|
|
2860
|
+
"uncompress",
|
|
2861
|
+
"aes_encrypt",
|
|
2862
|
+
"aes_decrypt",
|
|
2863
|
+
"to_base64",
|
|
2864
|
+
"from_base64",
|
|
2865
|
+
"convert",
|
|
2866
|
+
"group_concat_ws"
|
|
2867
|
+
]);
|
|
2868
|
+
const BOOLEAN_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
2869
|
+
"bool_and",
|
|
2870
|
+
"bool_or",
|
|
2871
|
+
"every",
|
|
2872
|
+
"exists",
|
|
2873
|
+
"isnull",
|
|
2874
|
+
"is_valid_json",
|
|
2875
|
+
"json_valid",
|
|
2876
|
+
"starts_with",
|
|
2877
|
+
"jsonb_exists",
|
|
2878
|
+
"pg_is_in_recovery",
|
|
2879
|
+
"regexp_like",
|
|
2880
|
+
"like"
|
|
2881
|
+
]);
|
|
2882
|
+
const DATE_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
2883
|
+
"now",
|
|
2884
|
+
"current_timestamp",
|
|
2885
|
+
"current_date",
|
|
2886
|
+
"current_time",
|
|
2887
|
+
"localtimestamp",
|
|
2888
|
+
"localtime",
|
|
2889
|
+
"date_trunc",
|
|
2890
|
+
"to_timestamp",
|
|
2891
|
+
"to_date",
|
|
2892
|
+
"make_date",
|
|
2893
|
+
"make_timestamp",
|
|
2894
|
+
"age",
|
|
2895
|
+
"curdate",
|
|
2896
|
+
"curtime",
|
|
2897
|
+
"sysdate",
|
|
2898
|
+
"utc_timestamp",
|
|
2899
|
+
"utc_date",
|
|
2900
|
+
"from_unixtime",
|
|
2901
|
+
"date_add",
|
|
2902
|
+
"date_sub",
|
|
2903
|
+
"adddate",
|
|
2904
|
+
"subdate",
|
|
2905
|
+
"str_to_date",
|
|
2906
|
+
"timestamp",
|
|
2907
|
+
"last_day",
|
|
2908
|
+
"makedate"
|
|
2909
|
+
]);
|
|
2910
|
+
function dateType(ctx, nullable, sources) {
|
|
2911
|
+
const dataType = ctx.dialect === "sqlite" ? "TEXT" : ctx.dialect === "mysql" ? "datetime" : "timestamp";
|
|
2912
|
+
return {
|
|
2913
|
+
dataType,
|
|
2914
|
+
tsType: toTsType(ctx.dialect, dataType),
|
|
2915
|
+
nullable,
|
|
2916
|
+
sources
|
|
2917
|
+
};
|
|
2918
|
+
}
|
|
2919
|
+
function isAggregateCall(expr) {
|
|
2920
|
+
if (expr.type === "call") return expr.over === null && AGGREGATES.has(expr.name.toLowerCase());
|
|
2921
|
+
return false;
|
|
2922
|
+
}
|
|
2923
|
+
/** Whether an aggregate appears anywhere in the expression (outside subqueries). */
|
|
2924
|
+
function hasAggregate(expr) {
|
|
2925
|
+
if (isAggregateCall(expr)) return true;
|
|
2926
|
+
return childExpressions(expr).some(hasAggregate);
|
|
2927
|
+
}
|
|
2928
|
+
function childExpressions(expr) {
|
|
2929
|
+
switch (expr.type) {
|
|
2930
|
+
case "binary": return [expr.left, expr.right];
|
|
2931
|
+
case "unary": return [expr.operand];
|
|
2932
|
+
case "call": return [
|
|
2933
|
+
...expr.args,
|
|
2934
|
+
...expr.over?.partitionBy ?? [],
|
|
2935
|
+
...expr.over?.orderBy.map((item) => item.expr) ?? []
|
|
2936
|
+
];
|
|
2937
|
+
case "cast": return [expr.expr];
|
|
2938
|
+
case "case": return [
|
|
2939
|
+
...expr.operand === null ? [] : [expr.operand],
|
|
2940
|
+
...expr.whens.flatMap((branch) => [branch.when, branch.result]),
|
|
2941
|
+
...expr.otherwise === null ? [] : [expr.otherwise]
|
|
2942
|
+
];
|
|
2943
|
+
case "in": return [expr.expr, ...expr.list ?? []];
|
|
2944
|
+
case "between": return [
|
|
2945
|
+
expr.expr,
|
|
2946
|
+
expr.low,
|
|
2947
|
+
expr.high
|
|
2948
|
+
];
|
|
2949
|
+
case "like": return [expr.expr, expr.pattern];
|
|
2950
|
+
case "is": return [expr.expr];
|
|
2951
|
+
case "list": return expr.items;
|
|
2952
|
+
case "column":
|
|
2953
|
+
case "star":
|
|
2954
|
+
case "literal":
|
|
2955
|
+
case "param":
|
|
2956
|
+
case "exists":
|
|
2957
|
+
case "subquery":
|
|
2958
|
+
case "raw": return [];
|
|
2959
|
+
default: return [];
|
|
2960
|
+
}
|
|
2961
|
+
}
|
|
2962
|
+
/** The subqueries nested directly in an expression (not those inside deeper subqueries). */
|
|
2963
|
+
function subqueriesOf(expr) {
|
|
2964
|
+
switch (expr.type) {
|
|
2965
|
+
case "exists": return [expr.query];
|
|
2966
|
+
case "subquery": return [expr.query];
|
|
2967
|
+
case "in": return [
|
|
2968
|
+
...expr.subquery === null ? [] : [expr.subquery],
|
|
2969
|
+
...expr.expr.type === "column" ? [] : subqueriesOf(expr.expr),
|
|
2970
|
+
...(expr.list ?? []).flatMap(subqueriesOf)
|
|
2971
|
+
];
|
|
2972
|
+
case "column":
|
|
2973
|
+
case "star":
|
|
2974
|
+
case "literal":
|
|
2975
|
+
case "param":
|
|
2976
|
+
case "binary":
|
|
2977
|
+
case "unary":
|
|
2978
|
+
case "call":
|
|
2979
|
+
case "cast":
|
|
2980
|
+
case "case":
|
|
2981
|
+
case "between":
|
|
2982
|
+
case "like":
|
|
2983
|
+
case "is":
|
|
2984
|
+
case "list":
|
|
2985
|
+
case "raw": return childExpressions(expr).flatMap(subqueriesOf);
|
|
2986
|
+
default: return [];
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
function typeOf(t, expr) {
|
|
2990
|
+
const { ctx } = t;
|
|
2991
|
+
switch (expr.type) {
|
|
2992
|
+
case "column": return resolveColumn(ctx, t.scope, expr.table, expr.name, expr.range, t.aliases);
|
|
2993
|
+
case "star": return UNKNOWN;
|
|
2994
|
+
case "literal":
|
|
2995
|
+
if (expr.kind === "null") return {
|
|
2996
|
+
dataType: null,
|
|
2997
|
+
tsType: "null",
|
|
2998
|
+
nullable: true,
|
|
2999
|
+
sources: []
|
|
3000
|
+
};
|
|
3001
|
+
return {
|
|
3002
|
+
dataType: literalDataType(ctx.dialect, expr.kind),
|
|
3003
|
+
tsType: expr.kind === "boolean" ? toTsType(ctx.dialect, literalDataType(ctx.dialect, "boolean")) : expr.kind,
|
|
3004
|
+
nullable: false,
|
|
3005
|
+
sources: []
|
|
3006
|
+
};
|
|
3007
|
+
case "param": return UNKNOWN;
|
|
3008
|
+
case "binary": {
|
|
3009
|
+
const left = typeOf(t, expr.left);
|
|
3010
|
+
const right = typeOf(t, expr.right);
|
|
3011
|
+
const sources = sourcesOf(left, right);
|
|
3012
|
+
const nullable = nullableOr(left, right);
|
|
3013
|
+
if (expr.op === "AND" || expr.op === "OR" || expr.op.startsWith("IS ")) return booleanType(ctx, nullable, sources);
|
|
3014
|
+
if ([
|
|
3015
|
+
"=",
|
|
3016
|
+
"<>",
|
|
3017
|
+
"!=",
|
|
3018
|
+
"<",
|
|
3019
|
+
">",
|
|
3020
|
+
"<=",
|
|
3021
|
+
">=",
|
|
3022
|
+
"<=>",
|
|
3023
|
+
"~",
|
|
3024
|
+
"!~",
|
|
3025
|
+
"~*",
|
|
3026
|
+
"!~*",
|
|
3027
|
+
"@>",
|
|
3028
|
+
"<@"
|
|
3029
|
+
].includes(expr.op)) return booleanType(ctx, nullable, sources);
|
|
3030
|
+
if (expr.op === "||") return stringType(ctx, nullable, sources);
|
|
3031
|
+
if (expr.op === "->" || expr.op === "#>") return {
|
|
3032
|
+
...UNKNOWN,
|
|
3033
|
+
nullable: true,
|
|
3034
|
+
sources
|
|
3035
|
+
};
|
|
3036
|
+
if (expr.op === "->>" || expr.op === "#>>") return stringType(ctx, true, sources);
|
|
3037
|
+
if (expr.op === "[]") return {
|
|
3038
|
+
...UNKNOWN,
|
|
3039
|
+
nullable: true,
|
|
3040
|
+
sources
|
|
3041
|
+
};
|
|
3042
|
+
if ([
|
|
3043
|
+
"+",
|
|
3044
|
+
"-",
|
|
3045
|
+
"*",
|
|
3046
|
+
"/",
|
|
3047
|
+
"%",
|
|
3048
|
+
"^",
|
|
3049
|
+
"**"
|
|
3050
|
+
].includes(expr.op)) {
|
|
3051
|
+
const dated = [left, right].find((side) => side.tsType === "Date");
|
|
3052
|
+
return dated === void 0 ? numberType(ctx, nullable, sources) : {
|
|
3053
|
+
...dated,
|
|
3054
|
+
nullable,
|
|
3055
|
+
sources
|
|
3056
|
+
};
|
|
3057
|
+
}
|
|
3058
|
+
return {
|
|
3059
|
+
...UNKNOWN,
|
|
3060
|
+
nullable,
|
|
3061
|
+
sources
|
|
3062
|
+
};
|
|
3063
|
+
}
|
|
3064
|
+
case "unary": {
|
|
3065
|
+
const operand = typeOf(t, expr.operand);
|
|
3066
|
+
if (expr.op === "NOT" || expr.op === "!") return booleanType(ctx, operand.nullable, operand.sources);
|
|
3067
|
+
return {
|
|
3068
|
+
...operand,
|
|
3069
|
+
tsType: operand.tsType === "unknown" ? "number" : operand.tsType
|
|
3070
|
+
};
|
|
3071
|
+
}
|
|
3072
|
+
case "call": return typeOfCall(t, expr);
|
|
3073
|
+
case "cast": {
|
|
3074
|
+
const inner = typeOf(t, expr.expr);
|
|
3075
|
+
return {
|
|
3076
|
+
dataType: expr.to,
|
|
3077
|
+
tsType: toTsType(ctx.dialect, expr.to),
|
|
3078
|
+
nullable: inner.nullable,
|
|
3079
|
+
sources: inner.sources
|
|
3080
|
+
};
|
|
3081
|
+
}
|
|
3082
|
+
case "case": {
|
|
3083
|
+
const branches = expr.whens.map((branch) => typeOf(t, branch.result));
|
|
3084
|
+
const otherwise = expr.otherwise === null ? null : typeOf(t, expr.otherwise);
|
|
3085
|
+
const all = [...branches, ...otherwise === null ? [] : [otherwise]];
|
|
3086
|
+
const typed = all.find((branch) => branch.tsType !== "null" && branch.tsType !== "unknown") ?? all[0] ?? UNKNOWN;
|
|
3087
|
+
const conditions = [...expr.operand === null ? [] : [typeOf(t, expr.operand)], ...expr.whens.map((branch) => typeOf(t, branch.when))];
|
|
3088
|
+
return {
|
|
3089
|
+
...typed,
|
|
3090
|
+
nullable: otherwise === null ? true : nullableOr(...all),
|
|
3091
|
+
sources: sourcesOf(...all, ...conditions)
|
|
3092
|
+
};
|
|
3093
|
+
}
|
|
3094
|
+
case "in": {
|
|
3095
|
+
const left = typeOf(t, expr.expr);
|
|
3096
|
+
const items = (expr.list ?? []).map((item) => typeOf(t, item));
|
|
3097
|
+
return booleanType(ctx, nullableOr(left, ...items), sourcesOf(left, ...items));
|
|
3098
|
+
}
|
|
3099
|
+
case "between": {
|
|
3100
|
+
const parts = [
|
|
3101
|
+
typeOf(t, expr.expr),
|
|
3102
|
+
typeOf(t, expr.low),
|
|
3103
|
+
typeOf(t, expr.high)
|
|
3104
|
+
];
|
|
3105
|
+
return booleanType(ctx, nullableOr(...parts), sourcesOf(...parts));
|
|
3106
|
+
}
|
|
3107
|
+
case "like": {
|
|
3108
|
+
const parts = [typeOf(t, expr.expr), typeOf(t, expr.pattern)];
|
|
3109
|
+
return booleanType(ctx, nullableOr(...parts), sourcesOf(...parts));
|
|
3110
|
+
}
|
|
3111
|
+
case "is": return booleanType(ctx, false, typeOf(t, expr.expr).sources);
|
|
3112
|
+
case "exists": return booleanType(ctx, false, []);
|
|
3113
|
+
case "subquery": {
|
|
3114
|
+
const built = buildQuery(ctx, expr.query, t.scope, "subquery");
|
|
3115
|
+
const target = t.lookups.get(expr.query);
|
|
3116
|
+
if (target !== void 0) addEdge(ctx, built.nodeId, target, "scalar", "lookup");
|
|
3117
|
+
const first = built.columns[0];
|
|
3118
|
+
return first === void 0 ? UNKNOWN : {
|
|
3119
|
+
...first,
|
|
3120
|
+
nullable: true
|
|
3121
|
+
};
|
|
3122
|
+
}
|
|
3123
|
+
case "list": {
|
|
3124
|
+
const items = expr.items.map((item) => typeOf(t, item));
|
|
3125
|
+
return {
|
|
3126
|
+
...UNKNOWN,
|
|
3127
|
+
nullable: nullableOr(...items),
|
|
3128
|
+
sources: sourcesOf(...items)
|
|
3129
|
+
};
|
|
3130
|
+
}
|
|
3131
|
+
case "raw": return UNKNOWN;
|
|
3132
|
+
default: return UNKNOWN;
|
|
3133
|
+
}
|
|
3134
|
+
}
|
|
3135
|
+
function typeOfCall(t, expr) {
|
|
3136
|
+
const { ctx } = t;
|
|
3137
|
+
const name = expr.name.toLowerCase().split(".").at(-1) ?? "";
|
|
3138
|
+
const args = expr.args.filter((arg) => arg.type !== "star").map((arg) => typeOf(t, arg));
|
|
3139
|
+
const sources = sourcesOf(...args);
|
|
3140
|
+
const argNullable = nullableOr(...args);
|
|
3141
|
+
if (name === "count") return numberType(ctx, false, sources);
|
|
3142
|
+
if (name === "coalesce" || name === "ifnull" || name === "nvl" || name === "isnull" && args.length === 2) {
|
|
3143
|
+
const typed = args.find((arg) => arg.tsType !== "null" && arg.tsType !== "unknown") ?? args[0] ?? UNKNOWN;
|
|
3144
|
+
const nullable = args.length === 0 ? null : args.every((arg) => arg.nullable === true) ? true : args.some((arg) => arg.nullable === false) ? false : null;
|
|
3145
|
+
return {
|
|
3146
|
+
...typed,
|
|
3147
|
+
nullable,
|
|
3148
|
+
sources
|
|
3149
|
+
};
|
|
3150
|
+
}
|
|
3151
|
+
if (name === "nullif") return {
|
|
3152
|
+
...args[0] ?? UNKNOWN,
|
|
3153
|
+
nullable: true,
|
|
3154
|
+
sources
|
|
3155
|
+
};
|
|
3156
|
+
if (name === "iif" || name === "if") {
|
|
3157
|
+
const [, then, otherwise] = args;
|
|
3158
|
+
return {
|
|
3159
|
+
...[then, otherwise].find((arg) => arg !== void 0 && arg.tsType !== "null" && arg.tsType !== "unknown") ?? then ?? UNKNOWN,
|
|
3160
|
+
nullable: nullableOr(...[then, otherwise].filter((arg) => arg !== void 0)),
|
|
3161
|
+
sources
|
|
3162
|
+
};
|
|
3163
|
+
}
|
|
3164
|
+
if (name === "min" || name === "max" || name === "first_value" || name === "last_value" || name === "lag" || name === "lead" || name === "nth_value" || name === "any_value") {
|
|
3165
|
+
const first = args[0] ?? UNKNOWN;
|
|
3166
|
+
return {
|
|
3167
|
+
...first,
|
|
3168
|
+
nullable: expr.over === null || name === "lag" || name === "lead" ? true : first.nullable,
|
|
3169
|
+
sources
|
|
3170
|
+
};
|
|
3171
|
+
}
|
|
3172
|
+
if (name === "sum" || name === "avg" || name === "stddev" || name === "variance") {
|
|
3173
|
+
const first = args[0] ?? UNKNOWN;
|
|
3174
|
+
return {
|
|
3175
|
+
...first.tsType === "string" && ctx.dialect !== "sqlite" ? first : numberType(ctx, true, sources),
|
|
3176
|
+
nullable: true,
|
|
3177
|
+
sources
|
|
3178
|
+
};
|
|
3179
|
+
}
|
|
3180
|
+
if (name === "row_number" || name === "rank" || name === "dense_rank" || name === "ntile") return numberType(ctx, false, sources);
|
|
3181
|
+
if (name === "array_agg" || name === "array") {
|
|
3182
|
+
const first = args[0] ?? UNKNOWN;
|
|
3183
|
+
return {
|
|
3184
|
+
dataType: first.dataType === null ? null : `${first.dataType}[]`,
|
|
3185
|
+
tsType: `${first.tsType === "unknown" ? "unknown" : first.tsType}[]`,
|
|
3186
|
+
nullable: name === "array_agg",
|
|
3187
|
+
sources
|
|
3188
|
+
};
|
|
3189
|
+
}
|
|
3190
|
+
if (name === "json_agg" || name === "jsonb_agg" || name === "json_object" || name === "json_build_object" || name === "jsonb_build_object" || name === "to_json" || name === "to_jsonb" || name === "row_to_json" || name === "json_extract" || name === "json") return {
|
|
3191
|
+
dataType: ctx.dialect === "sqlite" ? "TEXT" : ctx.dialect === "mysql" ? "json" : "jsonb",
|
|
3192
|
+
tsType: ctx.dialect === "sqlite" ? "string" : "unknown",
|
|
3193
|
+
nullable: argNullable,
|
|
3194
|
+
sources
|
|
3195
|
+
};
|
|
3196
|
+
if (NUMBER_FUNCTIONS.has(name)) return numberType(ctx, argNullable, sources);
|
|
3197
|
+
if (BOOLEAN_FUNCTIONS.has(name)) return booleanType(ctx, argNullable, sources);
|
|
3198
|
+
if (DATE_FUNCTIONS.has(name)) return dateType(ctx, args.length === 0 ? false : argNullable, sources);
|
|
3199
|
+
if (STRING_FUNCTIONS.has(name)) return stringType(ctx, args.length === 0 ? false : argNullable, sources);
|
|
3200
|
+
return {
|
|
3201
|
+
...UNKNOWN,
|
|
3202
|
+
nullable: argNullable,
|
|
3203
|
+
sources
|
|
3204
|
+
};
|
|
3205
|
+
}
|
|
3206
|
+
/** Records every placeholder with the type of what it stands beside. */
|
|
3207
|
+
function collectParams(t, expr, expected, context) {
|
|
3208
|
+
const { ctx } = t;
|
|
3209
|
+
const quietTyping = {
|
|
3210
|
+
...t,
|
|
3211
|
+
ctx: {
|
|
3212
|
+
...ctx,
|
|
3213
|
+
diagnostics: [],
|
|
3214
|
+
nodes: [],
|
|
3215
|
+
edges: [],
|
|
3216
|
+
refs: []
|
|
3217
|
+
}
|
|
3218
|
+
};
|
|
3219
|
+
const typeQuietly = (candidate) => candidate.type === "param" || candidate.type === "subquery" || candidate.type === "exists" ? null : typeOf(quietTyping, candidate);
|
|
3220
|
+
switch (expr.type) {
|
|
3221
|
+
case "param":
|
|
3222
|
+
ctx.params.push({
|
|
3223
|
+
placeholder: expr.placeholder,
|
|
3224
|
+
type: expected ?? UNKNOWN,
|
|
3225
|
+
context,
|
|
3226
|
+
range: expr.range
|
|
3227
|
+
});
|
|
3228
|
+
return;
|
|
3229
|
+
case "binary": {
|
|
3230
|
+
const comparison = [
|
|
3231
|
+
"=",
|
|
3232
|
+
"<>",
|
|
3233
|
+
"!=",
|
|
3234
|
+
"<",
|
|
3235
|
+
">",
|
|
3236
|
+
"<=",
|
|
3237
|
+
">=",
|
|
3238
|
+
"<=>"
|
|
3239
|
+
].includes(expr.op);
|
|
3240
|
+
const arithmetic = [
|
|
3241
|
+
"+",
|
|
3242
|
+
"-",
|
|
3243
|
+
"*",
|
|
3244
|
+
"/",
|
|
3245
|
+
"%",
|
|
3246
|
+
"^",
|
|
3247
|
+
"**"
|
|
3248
|
+
].includes(expr.op);
|
|
3249
|
+
const leftType = expr.right.type === "param" || expr.left.type === "param" ? typeQuietly(expr.left) : null;
|
|
3250
|
+
const rightType = expr.left.type === "param" || expr.right.type === "param" ? typeQuietly(expr.right) : null;
|
|
3251
|
+
const text = snippet(ctx, expr.range);
|
|
3252
|
+
const sideType = (other) => {
|
|
3253
|
+
if (comparison) return other === null ? null : withNullable(other, expr.op === "<=>" ? other.nullable : false);
|
|
3254
|
+
if (arithmetic) return other === null || other.tsType === "unknown" ? numberType(ctx, false, []) : other;
|
|
3255
|
+
if (expr.op === "||") return stringType(ctx, false, []);
|
|
3256
|
+
return other;
|
|
3257
|
+
};
|
|
3258
|
+
collectParams(t, expr.left, sideType(rightType), text);
|
|
3259
|
+
collectParams(t, expr.right, sideType(leftType), text);
|
|
3260
|
+
return;
|
|
3261
|
+
}
|
|
3262
|
+
case "in": {
|
|
3263
|
+
const left = expr.expr.type === "param" ? null : typeQuietly(expr.expr);
|
|
3264
|
+
const text = snippet(ctx, expr.range);
|
|
3265
|
+
collectParams(t, expr.expr, null, text);
|
|
3266
|
+
for (const item of expr.list ?? []) collectParams(t, item, left === null ? null : withNullable(left, false), text);
|
|
3267
|
+
return;
|
|
3268
|
+
}
|
|
3269
|
+
case "between": {
|
|
3270
|
+
const left = typeQuietly(expr.expr);
|
|
3271
|
+
const text = snippet(ctx, expr.range);
|
|
3272
|
+
collectParams(t, expr.expr, null, text);
|
|
3273
|
+
collectParams(t, expr.low, left === null ? null : withNullable(left, false), text);
|
|
3274
|
+
collectParams(t, expr.high, left === null ? null : withNullable(left, false), text);
|
|
3275
|
+
return;
|
|
3276
|
+
}
|
|
3277
|
+
case "like": {
|
|
3278
|
+
const text = snippet(ctx, expr.range);
|
|
3279
|
+
collectParams(t, expr.expr, stringType(ctx, false, []), text);
|
|
3280
|
+
collectParams(t, expr.pattern, stringType(ctx, false, []), text);
|
|
3281
|
+
return;
|
|
3282
|
+
}
|
|
3283
|
+
case "call": {
|
|
3284
|
+
const text = snippet(ctx, expr.range);
|
|
3285
|
+
for (const arg of expr.args) collectParams(t, arg, null, text);
|
|
3286
|
+
return;
|
|
3287
|
+
}
|
|
3288
|
+
case "cast":
|
|
3289
|
+
collectParams(t, expr.expr, {
|
|
3290
|
+
dataType: expr.to,
|
|
3291
|
+
tsType: toTsType(ctx.dialect, expr.to),
|
|
3292
|
+
nullable: false,
|
|
3293
|
+
sources: []
|
|
3294
|
+
}, snippet(ctx, expr.range));
|
|
3295
|
+
return;
|
|
3296
|
+
case "case": {
|
|
3297
|
+
const text = snippet(ctx, expr.range, 60);
|
|
3298
|
+
const operand = expr.operand === null ? null : typeQuietly(expr.operand);
|
|
3299
|
+
if (expr.operand !== null) collectParams(t, expr.operand, null, text);
|
|
3300
|
+
for (const branch of expr.whens) {
|
|
3301
|
+
collectParams(t, branch.when, operand === null ? booleanType(ctx, false, []) : withNullable(operand, false), text);
|
|
3302
|
+
collectParams(t, branch.result, null, text);
|
|
3303
|
+
}
|
|
3304
|
+
if (expr.otherwise !== null) collectParams(t, expr.otherwise, null, text);
|
|
3305
|
+
return;
|
|
3306
|
+
}
|
|
3307
|
+
case "unary":
|
|
3308
|
+
collectParams(t, expr.operand, expr.op === "NOT" ? booleanType(ctx, false, []) : numberType(ctx, false, []), snippet(ctx, expr.range));
|
|
3309
|
+
return;
|
|
3310
|
+
case "is":
|
|
3311
|
+
collectParams(t, expr.expr, null, snippet(ctx, expr.range));
|
|
3312
|
+
return;
|
|
3313
|
+
case "list": for (const item of expr.items) collectParams(t, item, null, context);
|
|
3314
|
+
}
|
|
3315
|
+
}
|
|
3316
|
+
function lookupTable(ctx, name) {
|
|
3317
|
+
return ctx.tables.get(name.name.toLowerCase()) ?? null;
|
|
3318
|
+
}
|
|
3319
|
+
function tableRelation(ctx, item, scope, scopeName) {
|
|
3320
|
+
const cte = scope.ctes.get(item.table.name.toLowerCase()) ?? findCte(scope.outer, item.table.name);
|
|
3321
|
+
const alias = item.alias ?? item.table.name;
|
|
3322
|
+
if (cte !== null && cte !== void 0 && item.table.schema === null) {
|
|
3323
|
+
const relation = {
|
|
3324
|
+
key: alias.toLowerCase(),
|
|
3325
|
+
display: alias,
|
|
3326
|
+
nodeId: cte.nodeId,
|
|
3327
|
+
columns: cte.columns,
|
|
3328
|
+
known: cte.columns.length > 0,
|
|
3329
|
+
tableName: null,
|
|
3330
|
+
outerNullable: false,
|
|
3331
|
+
used: /* @__PURE__ */ new Set()
|
|
3332
|
+
};
|
|
3333
|
+
return {
|
|
3334
|
+
nodeId: cte.nodeId,
|
|
3335
|
+
relations: [relation]
|
|
3336
|
+
};
|
|
3337
|
+
}
|
|
3338
|
+
const table = lookupTable(ctx, item.table);
|
|
3339
|
+
const known = table !== null;
|
|
3340
|
+
const display = item.table.schema === null ? item.table.name : `${item.table.schema}.${item.table.name}`;
|
|
3341
|
+
if (!known) warn(ctx, `Unknown table "${display}"`, item.table.range, ctx.tables.size === 0 ? "info" : "warning");
|
|
3342
|
+
const columns = (table?.columns ?? []).map((column) => ({
|
|
3343
|
+
dataType: column.dataType,
|
|
3344
|
+
tsType: toTsType(ctx.dialect, column.dataType),
|
|
3345
|
+
nullable: column.nullable,
|
|
3346
|
+
name: column.name,
|
|
3347
|
+
expression: column.name,
|
|
3348
|
+
sources: [{
|
|
3349
|
+
table: table?.name ?? item.table.name,
|
|
3350
|
+
column: column.name
|
|
3351
|
+
}]
|
|
3352
|
+
}));
|
|
3353
|
+
const nodeId = addNode(ctx, {
|
|
3354
|
+
kind: "table",
|
|
3355
|
+
label: item.alias === null ? display : `${display} AS ${item.alias}`,
|
|
3356
|
+
details: known ? [] : ["not in the schema"],
|
|
3357
|
+
range: item.range,
|
|
3358
|
+
scope: scopeName,
|
|
3359
|
+
columns: columns.map((column) => ({
|
|
3360
|
+
name: column.name,
|
|
3361
|
+
dataType: column.dataType,
|
|
3362
|
+
used: false
|
|
3363
|
+
}))
|
|
3364
|
+
});
|
|
3365
|
+
const used = /* @__PURE__ */ new Set();
|
|
3366
|
+
ctx.refs.push({
|
|
3367
|
+
nodeId,
|
|
3368
|
+
name: table?.name ?? item.table.name,
|
|
3369
|
+
alias: item.alias,
|
|
3370
|
+
scope: scopeName,
|
|
3371
|
+
known,
|
|
3372
|
+
range: item.table.range,
|
|
3373
|
+
used,
|
|
3374
|
+
schemaColumns: table?.columns ?? []
|
|
3375
|
+
});
|
|
3376
|
+
return {
|
|
3377
|
+
nodeId,
|
|
3378
|
+
relations: [{
|
|
3379
|
+
key: alias.toLowerCase(),
|
|
3380
|
+
display: alias,
|
|
3381
|
+
nodeId,
|
|
3382
|
+
columns,
|
|
3383
|
+
known,
|
|
3384
|
+
tableName: table?.name ?? item.table.name,
|
|
3385
|
+
outerNullable: false,
|
|
3386
|
+
used
|
|
3387
|
+
}]
|
|
3388
|
+
};
|
|
3389
|
+
}
|
|
3390
|
+
function findCte(scope, name) {
|
|
3391
|
+
if (scope === null) return null;
|
|
3392
|
+
return scope.ctes.get(name.toLowerCase()) ?? findCte(scope.outer, name);
|
|
3393
|
+
}
|
|
3394
|
+
function buildFromItem(ctx, item, scope, scopeName) {
|
|
3395
|
+
switch (item.type) {
|
|
3396
|
+
case "table": return tableRelation(ctx, item, scope, scopeName);
|
|
3397
|
+
case "subquery": {
|
|
3398
|
+
const alias = item.alias ?? "subquery";
|
|
3399
|
+
const built = buildQuery(ctx, item.query, item.lateral ? scope : {
|
|
3400
|
+
relations: [],
|
|
3401
|
+
outer: scope,
|
|
3402
|
+
ctes: /* @__PURE__ */ new Map()
|
|
3403
|
+
}, alias);
|
|
3404
|
+
const nodeId = addNode(ctx, {
|
|
3405
|
+
kind: "subquery",
|
|
3406
|
+
label: alias,
|
|
3407
|
+
details: [],
|
|
3408
|
+
range: item.range,
|
|
3409
|
+
scope: scopeName,
|
|
3410
|
+
columns: built.columns.map((column) => ({
|
|
3411
|
+
name: column.name,
|
|
3412
|
+
dataType: column.dataType,
|
|
3413
|
+
used: false
|
|
3414
|
+
}))
|
|
3415
|
+
});
|
|
3416
|
+
addEdge(ctx, built.nodeId, nodeId);
|
|
3417
|
+
return {
|
|
3418
|
+
nodeId,
|
|
3419
|
+
relations: [{
|
|
3420
|
+
key: alias.toLowerCase(),
|
|
3421
|
+
display: alias,
|
|
3422
|
+
nodeId,
|
|
3423
|
+
columns: built.columns,
|
|
3424
|
+
known: built.known,
|
|
3425
|
+
tableName: null,
|
|
3426
|
+
outerNullable: false,
|
|
3427
|
+
used: /* @__PURE__ */ new Set()
|
|
3428
|
+
}]
|
|
3429
|
+
};
|
|
3430
|
+
}
|
|
3431
|
+
case "function": {
|
|
3432
|
+
const alias = item.alias ?? (item.call.type === "call" ? item.call.name : "function");
|
|
3433
|
+
const nodeId = addNode(ctx, {
|
|
3434
|
+
kind: "function",
|
|
3435
|
+
label: snippet(ctx, item.call.range, 60),
|
|
3436
|
+
details: [],
|
|
3437
|
+
range: item.range,
|
|
3438
|
+
scope: scopeName,
|
|
3439
|
+
columns: []
|
|
3440
|
+
});
|
|
3441
|
+
return {
|
|
3442
|
+
nodeId,
|
|
3443
|
+
relations: [{
|
|
3444
|
+
key: alias.toLowerCase(),
|
|
3445
|
+
display: alias,
|
|
3446
|
+
nodeId,
|
|
3447
|
+
columns: [],
|
|
3448
|
+
known: false,
|
|
3449
|
+
tableName: null,
|
|
3450
|
+
outerNullable: false,
|
|
3451
|
+
used: /* @__PURE__ */ new Set()
|
|
3452
|
+
}]
|
|
3453
|
+
};
|
|
3454
|
+
}
|
|
3455
|
+
case "join": {
|
|
3456
|
+
const left = buildFromItem(ctx, item.left, scope, scopeName);
|
|
3457
|
+
const right = buildFromItem(ctx, item.right, {
|
|
3458
|
+
relations: left.relations,
|
|
3459
|
+
outer: scope,
|
|
3460
|
+
ctes: /* @__PURE__ */ new Map()
|
|
3461
|
+
}, scopeName);
|
|
3462
|
+
const leftRelations = item.joinType === "RIGHT" || item.joinType === "FULL" ? left.relations.map((relation) => ({
|
|
3463
|
+
...relation,
|
|
3464
|
+
outerNullable: true
|
|
3465
|
+
})) : left.relations;
|
|
3466
|
+
const rightRelations = item.joinType === "LEFT" || item.joinType === "FULL" ? right.relations.map((relation) => ({
|
|
3467
|
+
...relation,
|
|
3468
|
+
outerNullable: true
|
|
3469
|
+
})) : right.relations;
|
|
3470
|
+
const relations = [...leftRelations, ...rightRelations];
|
|
3471
|
+
const typing = {
|
|
3472
|
+
ctx,
|
|
3473
|
+
scope: {
|
|
3474
|
+
relations,
|
|
3475
|
+
outer: scope,
|
|
3476
|
+
ctes: /* @__PURE__ */ new Map()
|
|
3477
|
+
},
|
|
3478
|
+
aliases: null,
|
|
3479
|
+
lookups: /* @__PURE__ */ new Map()
|
|
3480
|
+
};
|
|
3481
|
+
const label = `${item.natural ? "NATURAL " : ""}${item.joinType} JOIN`;
|
|
3482
|
+
const details = item.on !== null ? [`ON ${snippet(ctx, item.on.range)}`] : item.using !== null ? [`USING (${item.using.join(", ")})`] : [];
|
|
3483
|
+
if (item.on !== null) {
|
|
3484
|
+
typeOf(typing, item.on);
|
|
3485
|
+
collectParams(typing, item.on, null, snippet(ctx, item.on.range));
|
|
3486
|
+
}
|
|
3487
|
+
for (const name of item.using ?? []) for (const relation of [...left.relations, ...right.relations]) relation.used.add(name);
|
|
3488
|
+
const nodeId = addNode(ctx, {
|
|
3489
|
+
kind: "join",
|
|
3490
|
+
label,
|
|
3491
|
+
details,
|
|
3492
|
+
range: item.on?.range ?? item.range,
|
|
3493
|
+
scope: scopeName,
|
|
3494
|
+
columns: []
|
|
3495
|
+
});
|
|
3496
|
+
addEdge(ctx, left.nodeId, nodeId, item.joinType === "RIGHT" ? "optional" : null);
|
|
3497
|
+
addEdge(ctx, right.nodeId, nodeId, item.joinType === "LEFT" ? "optional" : null);
|
|
3498
|
+
return {
|
|
3499
|
+
nodeId,
|
|
3500
|
+
relations
|
|
3501
|
+
};
|
|
3502
|
+
}
|
|
3503
|
+
default: return {
|
|
3504
|
+
nodeId: "",
|
|
3505
|
+
relations: []
|
|
3506
|
+
};
|
|
3507
|
+
}
|
|
3508
|
+
}
|
|
3509
|
+
function buildFrom(ctx, items, scope, scopeName) {
|
|
3510
|
+
if (items[0] === void 0) return null;
|
|
3511
|
+
const results = items.map((item) => buildFromItem(ctx, item, scope, scopeName));
|
|
3512
|
+
const relations = results.flatMap((result) => result.relations);
|
|
3513
|
+
if (results.length === 1) return {
|
|
3514
|
+
nodeId: results[0]?.nodeId ?? "",
|
|
3515
|
+
relations
|
|
3516
|
+
};
|
|
3517
|
+
const nodeId = addNode(ctx, {
|
|
3518
|
+
kind: "join",
|
|
3519
|
+
label: "CROSS JOIN",
|
|
3520
|
+
details: [`${results.length} sources listed in FROM`],
|
|
3521
|
+
range: null,
|
|
3522
|
+
scope: scopeName,
|
|
3523
|
+
columns: []
|
|
3524
|
+
});
|
|
3525
|
+
for (const result of results) addEdge(ctx, result.nodeId, nodeId);
|
|
3526
|
+
return {
|
|
3527
|
+
nodeId,
|
|
3528
|
+
relations
|
|
3529
|
+
};
|
|
3530
|
+
}
|
|
3531
|
+
/** The name a driver gives an unaliased select item. */
|
|
3532
|
+
function outputName(ctx, item) {
|
|
3533
|
+
if (item.alias !== null) return item.alias;
|
|
3534
|
+
const { expr } = item;
|
|
3535
|
+
if (expr.type === "column") return expr.name;
|
|
3536
|
+
if (ctx.dialect === "postgresql") {
|
|
3537
|
+
if (expr.type === "call") return expr.name.toLowerCase().split(".").at(-1) ?? "column";
|
|
3538
|
+
if (expr.type === "cast") return expr.to.toLowerCase().replace(/\(.*\)/u, "").split(" ")[0] ?? "column";
|
|
3539
|
+
if (expr.type === "case") return "case";
|
|
3540
|
+
if (expr.type === "literal" && expr.kind === "boolean") return "bool";
|
|
3541
|
+
return "?column?";
|
|
3542
|
+
}
|
|
3543
|
+
return snippet(ctx, expr.range, 200);
|
|
3544
|
+
}
|
|
3545
|
+
function expandStar(ctx, scope, expr) {
|
|
3546
|
+
const relations = expr.table === null ? scope.relations : [findRelation(scope, expr.table)].filter((relation) => relation !== null);
|
|
3547
|
+
if (expr.table !== null && relations.length === 0) {
|
|
3548
|
+
warn(ctx, `"${expr.table}" is not a table or alias in scope`, expr.range);
|
|
3549
|
+
return {
|
|
3550
|
+
columns: [],
|
|
3551
|
+
known: false
|
|
3552
|
+
};
|
|
3553
|
+
}
|
|
3554
|
+
return {
|
|
3555
|
+
columns: relations.flatMap((relation) => relation.columns.map((column) => {
|
|
3556
|
+
relation.used.add(column.name);
|
|
3557
|
+
return {
|
|
3558
|
+
...column,
|
|
3559
|
+
nullable: relation.outerNullable ? true : column.nullable
|
|
3560
|
+
};
|
|
3561
|
+
})),
|
|
3562
|
+
known: relations.every((relation) => relation.known)
|
|
3563
|
+
};
|
|
3564
|
+
}
|
|
3565
|
+
/** The nodes in a query after the projection — DISTINCT, ORDER BY, LIMIT — are shared by SELECT and set operations. */
|
|
3566
|
+
function buildTail(ctx, query, from, scope, scopeName, aliases) {
|
|
3567
|
+
const orderNode = (previous) => {
|
|
3568
|
+
if (query.orderBy.length === 0) return previous;
|
|
3569
|
+
const typing = {
|
|
3570
|
+
ctx,
|
|
3571
|
+
scope,
|
|
3572
|
+
aliases,
|
|
3573
|
+
lookups: /* @__PURE__ */ new Map()
|
|
3574
|
+
};
|
|
3575
|
+
for (const item of query.orderBy) {
|
|
3576
|
+
typeOf(typing, item.expr);
|
|
3577
|
+
collectParams(typing, item.expr, null, snippet(ctx, item.range));
|
|
3578
|
+
}
|
|
3579
|
+
const range = orderRange(query.orderBy);
|
|
3580
|
+
const nodeId = addNode(ctx, {
|
|
3581
|
+
kind: "sort",
|
|
3582
|
+
label: "ORDER BY",
|
|
3583
|
+
details: query.orderBy.map((item) => `${snippet(ctx, item.expr.range, 60)}${item.direction === null ? "" : ` ${item.direction}`}`),
|
|
3584
|
+
range,
|
|
3585
|
+
scope: scopeName,
|
|
3586
|
+
columns: []
|
|
3587
|
+
});
|
|
3588
|
+
addEdge(ctx, previous, nodeId);
|
|
3589
|
+
return nodeId;
|
|
3590
|
+
};
|
|
3591
|
+
const limitNode = (previous) => {
|
|
3592
|
+
if (query.limit === null && query.offset === null) return previous;
|
|
3593
|
+
const typing = {
|
|
3594
|
+
ctx,
|
|
3595
|
+
scope,
|
|
3596
|
+
aliases,
|
|
3597
|
+
lookups: /* @__PURE__ */ new Map()
|
|
3598
|
+
};
|
|
3599
|
+
const details = [...query.limit === null ? [] : [`LIMIT ${snippet(ctx, query.limit.range)}`], ...query.offset === null ? [] : [`OFFSET ${snippet(ctx, query.offset.range)}`]];
|
|
3600
|
+
if (query.limit !== null) collectParams(typing, query.limit, numberType(ctx, false, []), `LIMIT ${snippet(ctx, query.limit.range)}`);
|
|
3601
|
+
if (query.offset !== null) collectParams(typing, query.offset, numberType(ctx, false, []), `OFFSET ${snippet(ctx, query.offset.range)}`);
|
|
3602
|
+
const range = query.limit?.range ?? query.offset?.range ?? null;
|
|
3603
|
+
const nodeId = addNode(ctx, {
|
|
3604
|
+
kind: "limit",
|
|
3605
|
+
label: query.limit === null ? "OFFSET" : "LIMIT",
|
|
3606
|
+
details,
|
|
3607
|
+
range,
|
|
3608
|
+
scope: scopeName,
|
|
3609
|
+
columns: []
|
|
3610
|
+
});
|
|
3611
|
+
addEdge(ctx, previous, nodeId);
|
|
3612
|
+
return nodeId;
|
|
3613
|
+
};
|
|
3614
|
+
return {
|
|
3615
|
+
...from,
|
|
3616
|
+
nodeId: limitNode(orderNode(from.nodeId))
|
|
3617
|
+
};
|
|
3618
|
+
}
|
|
3619
|
+
function orderRange(items) {
|
|
3620
|
+
const first = items[0];
|
|
3621
|
+
const last = items.at(-1);
|
|
3622
|
+
return first === void 0 || last === void 0 ? null : {
|
|
3623
|
+
start: first.range.start,
|
|
3624
|
+
end: last.range.end
|
|
3625
|
+
};
|
|
3626
|
+
}
|
|
3627
|
+
function selectRange(items) {
|
|
3628
|
+
const first = items[0];
|
|
3629
|
+
const last = items.at(-1);
|
|
3630
|
+
return first === void 0 || last === void 0 ? null : {
|
|
3631
|
+
start: first.range.start,
|
|
3632
|
+
end: last.range.end
|
|
3633
|
+
};
|
|
3634
|
+
}
|
|
3635
|
+
function buildSelect(ctx, core, outer, scopeName) {
|
|
3636
|
+
const from = buildFrom(ctx, core.from, outer, scopeName);
|
|
3637
|
+
const scope = {
|
|
3638
|
+
relations: from?.relations ?? [],
|
|
3639
|
+
outer: outer.outer === null && outer.relations.length === 0 ? outer.outer : outer,
|
|
3640
|
+
ctes: outer.ctes
|
|
3641
|
+
};
|
|
3642
|
+
const chain = { current: from?.nodeId ?? null };
|
|
3643
|
+
const link = (nodeId) => {
|
|
3644
|
+
if (chain.current !== null) addEdge(ctx, chain.current, nodeId);
|
|
3645
|
+
chain.current = nodeId;
|
|
3646
|
+
};
|
|
3647
|
+
if (core.where !== null) {
|
|
3648
|
+
const nodeId = nextIdReserved(ctx);
|
|
3649
|
+
const typing = {
|
|
3650
|
+
ctx,
|
|
3651
|
+
scope,
|
|
3652
|
+
aliases: null,
|
|
3653
|
+
lookups: new Map(subqueriesOf(core.where).map((query) => [query, nodeId]))
|
|
3654
|
+
};
|
|
3655
|
+
const condition = typeOf(typing, core.where);
|
|
3656
|
+
collectParams(typing, core.where, null, snippet(ctx, core.where.range));
|
|
3657
|
+
ctx.nodes.push({
|
|
3658
|
+
id: nodeId,
|
|
3659
|
+
kind: "filter",
|
|
3660
|
+
label: "WHERE",
|
|
3661
|
+
details: [snippet(ctx, core.where.range)],
|
|
3662
|
+
range: core.where.range,
|
|
3663
|
+
scope: scopeName,
|
|
3664
|
+
columns: []
|
|
3665
|
+
});
|
|
3666
|
+
if (condition.tsType !== "unknown" && condition.tsType !== "boolean" && condition.tsType !== "number" && ctx.dialect === "postgresql") warn(ctx, `WHERE expects a boolean, this condition is ${condition.tsType}`, core.where.range);
|
|
3667
|
+
link(nodeId);
|
|
3668
|
+
}
|
|
3669
|
+
if (core.groupBy.length > 0 || core.having !== null || core.columns.some((item) => hasAggregate(item.expr))) {
|
|
3670
|
+
const typing = {
|
|
3671
|
+
ctx,
|
|
3672
|
+
scope,
|
|
3673
|
+
aliases: null,
|
|
3674
|
+
lookups: /* @__PURE__ */ new Map()
|
|
3675
|
+
};
|
|
3676
|
+
for (const key of core.groupBy) {
|
|
3677
|
+
typeOf(typing, key);
|
|
3678
|
+
collectParams(typing, key, null, snippet(ctx, key.range));
|
|
3679
|
+
}
|
|
3680
|
+
const aggregates = core.columns.flatMap((item) => aggregateCalls(item.expr)).map((call) => snippet(ctx, call.range, 60));
|
|
3681
|
+
link(addNode(ctx, {
|
|
3682
|
+
kind: "aggregate",
|
|
3683
|
+
label: "GROUP BY",
|
|
3684
|
+
details: [...core.groupBy.length === 0 ? ["whole result as one group"] : [`BY ${core.groupBy.map((key) => snippet(ctx, key.range, 60)).join(", ")}`], ...aggregates],
|
|
3685
|
+
range: core.groupBy.length === 0 ? null : {
|
|
3686
|
+
start: core.groupBy[0]?.range.start ?? 0,
|
|
3687
|
+
end: core.groupBy.at(-1)?.range.end ?? 0
|
|
3688
|
+
},
|
|
3689
|
+
scope: scopeName,
|
|
3690
|
+
columns: []
|
|
3691
|
+
}));
|
|
3692
|
+
}
|
|
3693
|
+
const projectId = nextIdReserved(ctx);
|
|
3694
|
+
const typing = {
|
|
3695
|
+
ctx,
|
|
3696
|
+
scope,
|
|
3697
|
+
aliases: null,
|
|
3698
|
+
lookups: new Map(core.columns.flatMap((item) => subqueriesOf(item.expr).map((query) => [query, projectId])))
|
|
3699
|
+
};
|
|
3700
|
+
const expanded = core.columns.flatMap((item) => {
|
|
3701
|
+
if (item.expr.type === "star") {
|
|
3702
|
+
const star = expandStar(ctx, scope, item.expr);
|
|
3703
|
+
return star.columns.map((column) => ({
|
|
3704
|
+
resolved: column,
|
|
3705
|
+
known: star.known
|
|
3706
|
+
}));
|
|
3707
|
+
}
|
|
3708
|
+
const type = typeOf(typing, item.expr);
|
|
3709
|
+
collectParams(typing, item.expr, null, snippet(ctx, item.range, 60));
|
|
3710
|
+
return [{
|
|
3711
|
+
resolved: {
|
|
3712
|
+
...type,
|
|
3713
|
+
name: outputName(ctx, item),
|
|
3714
|
+
expression: snippet(ctx, item.expr.range, 200)
|
|
3715
|
+
},
|
|
3716
|
+
known: true
|
|
3717
|
+
}];
|
|
3718
|
+
});
|
|
3719
|
+
const columns = expanded.map((entry) => entry.resolved);
|
|
3720
|
+
const aliases = new Map(core.columns.flatMap((item, index) => item.alias === null ? [] : [[item.alias.toLowerCase(), columns[index] ?? UNKNOWN]]));
|
|
3721
|
+
if (core.having !== null) {
|
|
3722
|
+
const havingId = nextIdReserved(ctx);
|
|
3723
|
+
const havingTyping = {
|
|
3724
|
+
ctx,
|
|
3725
|
+
scope,
|
|
3726
|
+
aliases,
|
|
3727
|
+
lookups: new Map(subqueriesOf(core.having).map((query) => [query, havingId]))
|
|
3728
|
+
};
|
|
3729
|
+
typeOf(havingTyping, core.having);
|
|
3730
|
+
collectParams(havingTyping, core.having, null, snippet(ctx, core.having.range));
|
|
3731
|
+
ctx.nodes.push({
|
|
3732
|
+
id: havingId,
|
|
3733
|
+
kind: "having",
|
|
3734
|
+
label: "HAVING",
|
|
3735
|
+
details: [snippet(ctx, core.having.range)],
|
|
3736
|
+
range: core.having.range,
|
|
3737
|
+
scope: scopeName,
|
|
3738
|
+
columns: []
|
|
3739
|
+
});
|
|
3740
|
+
link(havingId);
|
|
3741
|
+
}
|
|
3742
|
+
ctx.nodes.push({
|
|
3743
|
+
id: projectId,
|
|
3744
|
+
kind: "project",
|
|
3745
|
+
label: core.distinct ? "SELECT DISTINCT" : "SELECT",
|
|
3746
|
+
details: columns.length > 12 ? [...columns.slice(0, 12).map((column) => column.name), `… ${columns.length - 12} more`] : columns.map((column) => column.name),
|
|
3747
|
+
range: selectRange(core.columns),
|
|
3748
|
+
scope: scopeName,
|
|
3749
|
+
columns: columns.map((column) => ({
|
|
3750
|
+
name: column.name,
|
|
3751
|
+
dataType: column.dataType,
|
|
3752
|
+
used: true
|
|
3753
|
+
}))
|
|
3754
|
+
});
|
|
3755
|
+
link(projectId);
|
|
3756
|
+
return {
|
|
3757
|
+
built: {
|
|
3758
|
+
nodeId: projectId,
|
|
3759
|
+
columns,
|
|
3760
|
+
known: expanded.every((entry) => entry.known)
|
|
3761
|
+
},
|
|
3762
|
+
scope,
|
|
3763
|
+
aliases
|
|
3764
|
+
};
|
|
3765
|
+
}
|
|
3766
|
+
/** Reserves an id for a node that is added after the expressions it holds have been typed (so lookups can point at it). */
|
|
3767
|
+
function nextIdReserved(ctx) {
|
|
3768
|
+
return nextId(ctx);
|
|
3769
|
+
}
|
|
3770
|
+
function aggregateCalls(expr) {
|
|
3771
|
+
if (expr.type === "call" && isAggregateCall(expr)) return [expr];
|
|
3772
|
+
return childExpressions(expr).flatMap(aggregateCalls);
|
|
3773
|
+
}
|
|
3774
|
+
function buildBody(ctx, body, scope, scopeName) {
|
|
3775
|
+
switch (body.type) {
|
|
3776
|
+
case "select": return buildSelect(ctx, body, scope, scopeName);
|
|
3777
|
+
case "setop": {
|
|
3778
|
+
const left = buildBody(ctx, body.left, scope, scopeName);
|
|
3779
|
+
const right = buildBody(ctx, body.right, scope, scopeName);
|
|
3780
|
+
const columns = left.built.columns.map((column, index) => {
|
|
3781
|
+
const other = right.built.columns[index];
|
|
3782
|
+
return other === void 0 ? column : {
|
|
3783
|
+
...column,
|
|
3784
|
+
nullable: nullableOr(column, other),
|
|
3785
|
+
sources: sourcesOf(column, other)
|
|
3786
|
+
};
|
|
3787
|
+
});
|
|
3788
|
+
if (left.built.known && right.built.known && left.built.columns.length !== right.built.columns.length) warn(ctx, `${body.op}: the left side has ${left.built.columns.length} columns, the right side ${right.built.columns.length}`, body.range);
|
|
3789
|
+
const nodeId = addNode(ctx, {
|
|
3790
|
+
kind: "union",
|
|
3791
|
+
label: `${body.op}${body.all ? " ALL" : ""}`,
|
|
3792
|
+
details: [],
|
|
3793
|
+
range: null,
|
|
3794
|
+
scope: scopeName,
|
|
3795
|
+
columns: columns.map((column) => ({
|
|
3796
|
+
name: column.name,
|
|
3797
|
+
dataType: column.dataType,
|
|
3798
|
+
used: true
|
|
3799
|
+
}))
|
|
3800
|
+
});
|
|
3801
|
+
addEdge(ctx, left.built.nodeId, nodeId);
|
|
3802
|
+
addEdge(ctx, right.built.nodeId, nodeId);
|
|
3803
|
+
return {
|
|
3804
|
+
built: {
|
|
3805
|
+
nodeId,
|
|
3806
|
+
columns,
|
|
3807
|
+
known: left.built.known && right.built.known
|
|
3808
|
+
},
|
|
3809
|
+
scope: left.scope,
|
|
3810
|
+
aliases: left.aliases
|
|
3811
|
+
};
|
|
3812
|
+
}
|
|
3813
|
+
case "values": {
|
|
3814
|
+
const typing = {
|
|
3815
|
+
ctx,
|
|
3816
|
+
scope,
|
|
3817
|
+
aliases: null,
|
|
3818
|
+
lookups: /* @__PURE__ */ new Map()
|
|
3819
|
+
};
|
|
3820
|
+
const columns = (body.rows[0] ?? []).map((expr, index) => {
|
|
3821
|
+
const types = body.rows.map((row) => row[index]).filter((cell) => cell !== void 0).map((cell) => typeOf(typing, cell));
|
|
3822
|
+
const typed = types.find((type) => type.tsType !== "null" && type.tsType !== "unknown") ?? types[0] ?? UNKNOWN;
|
|
3823
|
+
return {
|
|
3824
|
+
dataType: typed.dataType,
|
|
3825
|
+
tsType: typed.tsType,
|
|
3826
|
+
sources: typed.sources,
|
|
3827
|
+
nullable: nullableOr(...types),
|
|
3828
|
+
name: `column${index + 1}`,
|
|
3829
|
+
expression: snippet(ctx, expr.range, 60)
|
|
3830
|
+
};
|
|
3831
|
+
});
|
|
3832
|
+
for (const row of body.rows) for (const cell of row) collectParams(typing, cell, null, "VALUES");
|
|
3833
|
+
return {
|
|
3834
|
+
built: {
|
|
3835
|
+
nodeId: addNode(ctx, {
|
|
3836
|
+
kind: "values",
|
|
3837
|
+
label: "VALUES",
|
|
3838
|
+
details: [`${body.rows.length} ${body.rows.length === 1 ? "row" : "rows"}`],
|
|
3839
|
+
range: body.range,
|
|
3840
|
+
scope: scopeName,
|
|
3841
|
+
columns: columns.map((column) => ({
|
|
3842
|
+
name: column.name,
|
|
3843
|
+
dataType: column.dataType,
|
|
3844
|
+
used: true
|
|
3845
|
+
}))
|
|
3846
|
+
}),
|
|
3847
|
+
columns,
|
|
3848
|
+
known: true
|
|
3849
|
+
},
|
|
3850
|
+
scope,
|
|
3851
|
+
aliases: /* @__PURE__ */ new Map()
|
|
3852
|
+
};
|
|
3853
|
+
}
|
|
3854
|
+
default: return {
|
|
3855
|
+
built: {
|
|
3856
|
+
nodeId: "",
|
|
3857
|
+
columns: [],
|
|
3858
|
+
known: false
|
|
3859
|
+
},
|
|
3860
|
+
scope,
|
|
3861
|
+
aliases: /* @__PURE__ */ new Map()
|
|
3862
|
+
};
|
|
3863
|
+
}
|
|
3864
|
+
}
|
|
3865
|
+
function buildCtes(ctx, ctes, recursive, scope) {
|
|
3866
|
+
const registered = new Map(scope.ctes);
|
|
3867
|
+
for (const cte of ctes) {
|
|
3868
|
+
const scopeName = cte.name;
|
|
3869
|
+
const inner = {
|
|
3870
|
+
relations: [],
|
|
3871
|
+
outer: scope.outer,
|
|
3872
|
+
ctes: registered
|
|
3873
|
+
};
|
|
3874
|
+
if (recursive) registered.set(cte.name.toLowerCase(), {
|
|
3875
|
+
nodeId: "",
|
|
3876
|
+
columns: []
|
|
3877
|
+
});
|
|
3878
|
+
const placeholder = recursive ? nextIdReserved(ctx) : null;
|
|
3879
|
+
if (placeholder !== null) registered.set(cte.name.toLowerCase(), {
|
|
3880
|
+
nodeId: placeholder,
|
|
3881
|
+
columns: []
|
|
3882
|
+
});
|
|
3883
|
+
const built = buildQuery(ctx, cte.query, inner, scopeName);
|
|
3884
|
+
const columns = cte.columns === null ? built.columns : built.columns.map((column, index) => ({
|
|
3885
|
+
...column,
|
|
3886
|
+
name: cte.columns?.[index] ?? column.name
|
|
3887
|
+
}));
|
|
3888
|
+
const node = {
|
|
3889
|
+
kind: "cte",
|
|
3890
|
+
label: `WITH ${cte.name}`,
|
|
3891
|
+
details: [],
|
|
3892
|
+
range: cte.range,
|
|
3893
|
+
scope: scopeName,
|
|
3894
|
+
columns: columns.map((column) => ({
|
|
3895
|
+
name: column.name,
|
|
3896
|
+
dataType: column.dataType,
|
|
3897
|
+
used: false
|
|
3898
|
+
}))
|
|
3899
|
+
};
|
|
3900
|
+
const nodeId = placeholder ?? addNode(ctx, node);
|
|
3901
|
+
if (placeholder !== null) ctx.nodes.push({
|
|
3902
|
+
id: placeholder,
|
|
3903
|
+
...node
|
|
3904
|
+
});
|
|
3905
|
+
addEdge(ctx, built.nodeId, nodeId);
|
|
3906
|
+
registered.set(cte.name.toLowerCase(), {
|
|
3907
|
+
nodeId,
|
|
3908
|
+
columns
|
|
3909
|
+
});
|
|
3910
|
+
}
|
|
3911
|
+
return {
|
|
3912
|
+
...scope,
|
|
3913
|
+
ctes: registered
|
|
3914
|
+
};
|
|
3915
|
+
}
|
|
3916
|
+
/** A whole query: its CTEs, its body and the sort / limit tail; returns the node the result comes out of. */
|
|
3917
|
+
function buildQuery(ctx, query, scope, scopeName) {
|
|
3918
|
+
const withCtes = query.ctes.length === 0 ? scope : buildCtes(ctx, query.ctes, query.recursive, scope);
|
|
3919
|
+
const { built, scope: bodyScope, aliases } = buildBody(ctx, query.body, withCtes, scopeName);
|
|
3920
|
+
return buildTail(ctx, query, built, bodyScope, scopeName, aliases);
|
|
3921
|
+
}
|
|
3922
|
+
function targetRelation(ctx, table, alias, range, scope, scopeName) {
|
|
3923
|
+
return tableRelation(ctx, {
|
|
3924
|
+
type: "table",
|
|
3925
|
+
table,
|
|
3926
|
+
alias,
|
|
3927
|
+
range
|
|
3928
|
+
}, scope, scopeName);
|
|
3929
|
+
}
|
|
3930
|
+
function buildReturning(ctx, items, previous, scope, scopeName) {
|
|
3931
|
+
if (items === null) return [];
|
|
3932
|
+
const nodeId = nextIdReserved(ctx);
|
|
3933
|
+
const typing = {
|
|
3934
|
+
ctx,
|
|
3935
|
+
scope,
|
|
3936
|
+
aliases: null,
|
|
3937
|
+
lookups: /* @__PURE__ */ new Map()
|
|
3938
|
+
};
|
|
3939
|
+
const columns = items.flatMap((item) => {
|
|
3940
|
+
if (item.expr.type === "star") return [...expandStar(ctx, scope, item.expr).columns];
|
|
3941
|
+
return [{
|
|
3942
|
+
...typeOf(typing, item.expr),
|
|
3943
|
+
name: outputName(ctx, item),
|
|
3944
|
+
expression: snippet(ctx, item.expr.range, 200)
|
|
3945
|
+
}];
|
|
3946
|
+
});
|
|
3947
|
+
ctx.nodes.push({
|
|
3948
|
+
id: nodeId,
|
|
3949
|
+
kind: "returning",
|
|
3950
|
+
label: "RETURNING",
|
|
3951
|
+
details: columns.map((column) => column.name),
|
|
3952
|
+
range: selectRange(items),
|
|
3953
|
+
scope: scopeName,
|
|
3954
|
+
columns: columns.map((column) => ({
|
|
3955
|
+
name: column.name,
|
|
3956
|
+
dataType: column.dataType,
|
|
3957
|
+
used: true
|
|
3958
|
+
}))
|
|
3959
|
+
});
|
|
3960
|
+
addEdge(ctx, previous, nodeId);
|
|
3961
|
+
return columns;
|
|
3962
|
+
}
|
|
3963
|
+
function buildInsert(ctx, statement) {
|
|
3964
|
+
const root = {
|
|
3965
|
+
relations: [],
|
|
3966
|
+
outer: null,
|
|
3967
|
+
ctes: /* @__PURE__ */ new Map()
|
|
3968
|
+
};
|
|
3969
|
+
const scope = statement.ctes.length === 0 ? root : buildCtes(ctx, statement.ctes, false, root);
|
|
3970
|
+
const table = lookupTable(ctx, statement.table);
|
|
3971
|
+
const targetColumns = statement.columns === null ? table?.columns ?? [] : statement.columns.map((name) => table?.columns.find((column) => column.name.toLowerCase() === name.toLowerCase()) ?? {
|
|
3972
|
+
name,
|
|
3973
|
+
dataType: "",
|
|
3974
|
+
nullable: true
|
|
3975
|
+
});
|
|
3976
|
+
if (table !== null && statement.columns !== null) {
|
|
3977
|
+
for (const name of statement.columns) if (!table.columns.some((column) => column.name.toLowerCase() === name.toLowerCase())) warn(ctx, `"${table.name}" has no column "${name}"`, statement.range);
|
|
3978
|
+
}
|
|
3979
|
+
const expectedTypes = targetColumns.map((column) => column.dataType === "" ? null : typeOfColumn(ctx, column));
|
|
3980
|
+
const insertScope = {
|
|
3981
|
+
relations: [],
|
|
3982
|
+
outer: null,
|
|
3983
|
+
ctes: scope.ctes
|
|
3984
|
+
};
|
|
3985
|
+
const typing = {
|
|
3986
|
+
ctx,
|
|
3987
|
+
scope: insertScope,
|
|
3988
|
+
aliases: null,
|
|
3989
|
+
lookups: /* @__PURE__ */ new Map()
|
|
3990
|
+
};
|
|
3991
|
+
const sourceId = (() => {
|
|
3992
|
+
if (statement.source.type === "values") {
|
|
3993
|
+
for (const row of statement.source.rows) {
|
|
3994
|
+
if (table !== null && row.length !== targetColumns.length && targetColumns.length > 0) warn(ctx, `${row.length} values for ${targetColumns.length} columns`, statement.source.range);
|
|
3995
|
+
for (const [index, cell] of row.entries()) {
|
|
3996
|
+
const column = targetColumns[index];
|
|
3997
|
+
collectParams(typing, cell, expectedTypes[index] ?? null, column === void 0 ? "VALUES" : `${statement.table.name}.${column.name}`);
|
|
3998
|
+
}
|
|
3999
|
+
}
|
|
4000
|
+
return addNode(ctx, {
|
|
4001
|
+
kind: "values",
|
|
4002
|
+
label: "VALUES",
|
|
4003
|
+
details: [`${statement.source.rows.length} ${statement.source.rows.length === 1 ? "row" : "rows"}`],
|
|
4004
|
+
range: statement.source.range,
|
|
4005
|
+
scope: "main",
|
|
4006
|
+
columns: targetColumns.map((column) => ({
|
|
4007
|
+
name: column.name,
|
|
4008
|
+
dataType: column.dataType === "" ? null : column.dataType,
|
|
4009
|
+
used: true
|
|
4010
|
+
}))
|
|
4011
|
+
});
|
|
409
4012
|
}
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
4013
|
+
if (statement.source.type === "query") {
|
|
4014
|
+
const built = buildQuery(ctx, statement.source.query, insertScope, "main");
|
|
4015
|
+
if (table !== null && built.known && built.columns.length !== targetColumns.length && targetColumns.length > 0) warn(ctx, `The query yields ${built.columns.length} columns for ${targetColumns.length} target columns`, statement.source.range);
|
|
4016
|
+
return built.nodeId;
|
|
4017
|
+
}
|
|
4018
|
+
return addNode(ctx, {
|
|
4019
|
+
kind: "values",
|
|
4020
|
+
label: "DEFAULT VALUES",
|
|
4021
|
+
details: [],
|
|
4022
|
+
range: statement.source.range,
|
|
4023
|
+
scope: "main",
|
|
4024
|
+
columns: []
|
|
4025
|
+
});
|
|
4026
|
+
})();
|
|
4027
|
+
const target = targetRelation(ctx, statement.table, statement.alias, statement.table.range, scope, "main");
|
|
4028
|
+
const insertId = addNode(ctx, {
|
|
4029
|
+
kind: "insert",
|
|
4030
|
+
label: `INSERT INTO ${statement.table.name}`,
|
|
4031
|
+
details: [...statement.columns === null ? [] : [`(${statement.columns.join(", ")})`], ...statement.onConflict === null ? [] : [snippet(ctx, statement.onConflict, 80)]],
|
|
4032
|
+
range: statement.range,
|
|
4033
|
+
scope: "main",
|
|
4034
|
+
columns: []
|
|
4035
|
+
});
|
|
4036
|
+
addEdge(ctx, sourceId, insertId);
|
|
4037
|
+
addEdge(ctx, target.nodeId, insertId, "target");
|
|
4038
|
+
for (const column of targetColumns) for (const relation of target.relations) relation.used.add(column.name);
|
|
4039
|
+
return buildReturning(ctx, statement.returning, insertId, {
|
|
4040
|
+
relations: target.relations,
|
|
4041
|
+
outer: null,
|
|
4042
|
+
ctes: scope.ctes
|
|
4043
|
+
}, "main");
|
|
4044
|
+
}
|
|
4045
|
+
function buildUpdate(ctx, statement) {
|
|
4046
|
+
const root = {
|
|
4047
|
+
relations: [],
|
|
4048
|
+
outer: null,
|
|
4049
|
+
ctes: /* @__PURE__ */ new Map()
|
|
4050
|
+
};
|
|
4051
|
+
const scope = statement.ctes.length === 0 ? root : buildCtes(ctx, statement.ctes, false, root);
|
|
4052
|
+
const target = targetRelation(ctx, statement.table, statement.alias, statement.table.range, scope, "main");
|
|
4053
|
+
const from = buildFrom(ctx, statement.from, {
|
|
4054
|
+
relations: target.relations,
|
|
4055
|
+
outer: null,
|
|
4056
|
+
ctes: scope.ctes
|
|
4057
|
+
}, "main");
|
|
4058
|
+
const rowScope = {
|
|
4059
|
+
relations: [...target.relations, ...from?.relations ?? []],
|
|
4060
|
+
outer: null,
|
|
4061
|
+
ctes: scope.ctes
|
|
4062
|
+
};
|
|
4063
|
+
const chain = { current: target.nodeId };
|
|
4064
|
+
if (from !== null) {
|
|
4065
|
+
const joinId = addNode(ctx, {
|
|
4066
|
+
kind: "join",
|
|
4067
|
+
label: "JOIN",
|
|
4068
|
+
details: ["FROM"],
|
|
4069
|
+
range: null,
|
|
4070
|
+
scope: "main",
|
|
4071
|
+
columns: []
|
|
4072
|
+
});
|
|
4073
|
+
addEdge(ctx, target.nodeId, joinId);
|
|
4074
|
+
addEdge(ctx, from.nodeId, joinId);
|
|
4075
|
+
chain.current = joinId;
|
|
4076
|
+
}
|
|
4077
|
+
if (statement.where !== null) {
|
|
4078
|
+
const nodeId = nextIdReserved(ctx);
|
|
4079
|
+
const typing = {
|
|
4080
|
+
ctx,
|
|
4081
|
+
scope: rowScope,
|
|
4082
|
+
aliases: null,
|
|
4083
|
+
lookups: new Map(subqueriesOf(statement.where).map((query) => [query, nodeId]))
|
|
4084
|
+
};
|
|
4085
|
+
typeOf(typing, statement.where);
|
|
4086
|
+
collectParams(typing, statement.where, null, snippet(ctx, statement.where.range));
|
|
4087
|
+
ctx.nodes.push({
|
|
4088
|
+
id: nodeId,
|
|
4089
|
+
kind: "filter",
|
|
4090
|
+
label: "WHERE",
|
|
4091
|
+
details: [snippet(ctx, statement.where.range)],
|
|
4092
|
+
range: statement.where.range,
|
|
4093
|
+
scope: "main",
|
|
4094
|
+
columns: []
|
|
4095
|
+
});
|
|
4096
|
+
addEdge(ctx, chain.current, nodeId);
|
|
4097
|
+
chain.current = nodeId;
|
|
4098
|
+
} else warn(ctx, "UPDATE without WHERE changes every row", statement.range);
|
|
4099
|
+
const updateId = nextIdReserved(ctx);
|
|
4100
|
+
const typing = {
|
|
4101
|
+
ctx,
|
|
4102
|
+
scope: rowScope,
|
|
4103
|
+
aliases: null,
|
|
4104
|
+
lookups: new Map(statement.set.flatMap((item) => subqueriesOf(item.value).map((query) => [query, updateId])))
|
|
4105
|
+
};
|
|
4106
|
+
const targetTable = target.relations[0];
|
|
4107
|
+
for (const item of statement.set) {
|
|
4108
|
+
const column = targetTable === void 0 ? null : columnOf(targetTable, item.column);
|
|
4109
|
+
if (targetTable?.known && column === null) warn(ctx, `"${targetTable.display}" has no column "${item.column}"`, item.range);
|
|
4110
|
+
targetTable?.used.add(item.column);
|
|
4111
|
+
if (item.value.type !== "raw") {
|
|
4112
|
+
typeOf(typing, item.value);
|
|
4113
|
+
collectParams(typing, item.value, column === null ? null : {
|
|
4114
|
+
...column,
|
|
4115
|
+
sources: []
|
|
4116
|
+
}, `SET ${snippet(ctx, item.range, 60)}`);
|
|
415
4117
|
}
|
|
416
|
-
case "DateTime": return dialect === "sqlite" ? String(value) : new Date(String(value));
|
|
417
|
-
case "Bytes": return Buffer.from(String(value), "base64");
|
|
418
|
-
default: return String(value);
|
|
419
4118
|
}
|
|
4119
|
+
ctx.nodes.push({
|
|
4120
|
+
id: updateId,
|
|
4121
|
+
kind: "update",
|
|
4122
|
+
label: `UPDATE ${statement.table.name}`,
|
|
4123
|
+
details: statement.set.map((item) => snippet(ctx, item.range, 60)),
|
|
4124
|
+
range: statement.range,
|
|
4125
|
+
scope: "main",
|
|
4126
|
+
columns: []
|
|
4127
|
+
});
|
|
4128
|
+
addEdge(ctx, chain.current, updateId);
|
|
4129
|
+
return buildReturning(ctx, statement.returning, updateId, rowScope, "main");
|
|
420
4130
|
}
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
4131
|
+
function buildDelete(ctx, statement) {
|
|
4132
|
+
const root = {
|
|
4133
|
+
relations: [],
|
|
4134
|
+
outer: null,
|
|
4135
|
+
ctes: /* @__PURE__ */ new Map()
|
|
4136
|
+
};
|
|
4137
|
+
const scope = statement.ctes.length === 0 ? root : buildCtes(ctx, statement.ctes, false, root);
|
|
4138
|
+
const target = targetRelation(ctx, statement.table, statement.alias, statement.table.range, scope, "main");
|
|
4139
|
+
const using = buildFrom(ctx, statement.using, {
|
|
4140
|
+
relations: target.relations,
|
|
4141
|
+
outer: null,
|
|
4142
|
+
ctes: scope.ctes
|
|
4143
|
+
}, "main");
|
|
4144
|
+
const rowScope = {
|
|
4145
|
+
relations: [...target.relations, ...using?.relations ?? []],
|
|
4146
|
+
outer: null,
|
|
4147
|
+
ctes: scope.ctes
|
|
4148
|
+
};
|
|
4149
|
+
const chain = { current: target.nodeId };
|
|
4150
|
+
if (using !== null) {
|
|
4151
|
+
const joinId = addNode(ctx, {
|
|
4152
|
+
kind: "join",
|
|
4153
|
+
label: "JOIN",
|
|
4154
|
+
details: ["USING"],
|
|
4155
|
+
range: null,
|
|
4156
|
+
scope: "main",
|
|
4157
|
+
columns: []
|
|
4158
|
+
});
|
|
4159
|
+
addEdge(ctx, target.nodeId, joinId);
|
|
4160
|
+
addEdge(ctx, using.nodeId, joinId);
|
|
4161
|
+
chain.current = joinId;
|
|
4162
|
+
}
|
|
4163
|
+
if (statement.where !== null) {
|
|
4164
|
+
const nodeId = nextIdReserved(ctx);
|
|
4165
|
+
const typing = {
|
|
4166
|
+
ctx,
|
|
4167
|
+
scope: rowScope,
|
|
4168
|
+
aliases: null,
|
|
4169
|
+
lookups: new Map(subqueriesOf(statement.where).map((query) => [query, nodeId]))
|
|
4170
|
+
};
|
|
4171
|
+
typeOf(typing, statement.where);
|
|
4172
|
+
collectParams(typing, statement.where, null, snippet(ctx, statement.where.range));
|
|
4173
|
+
ctx.nodes.push({
|
|
4174
|
+
id: nodeId,
|
|
4175
|
+
kind: "filter",
|
|
4176
|
+
label: "WHERE",
|
|
4177
|
+
details: [snippet(ctx, statement.where.range)],
|
|
4178
|
+
range: statement.where.range,
|
|
4179
|
+
scope: "main",
|
|
4180
|
+
columns: []
|
|
4181
|
+
});
|
|
4182
|
+
addEdge(ctx, chain.current, nodeId);
|
|
4183
|
+
chain.current = nodeId;
|
|
4184
|
+
} else warn(ctx, "DELETE without WHERE removes every row", statement.range);
|
|
4185
|
+
const deleteId = addNode(ctx, {
|
|
4186
|
+
kind: "delete",
|
|
4187
|
+
label: `DELETE FROM ${statement.table.name}`,
|
|
4188
|
+
details: [],
|
|
4189
|
+
range: statement.range,
|
|
4190
|
+
scope: "main",
|
|
4191
|
+
columns: []
|
|
4192
|
+
});
|
|
4193
|
+
addEdge(ctx, chain.current, deleteId);
|
|
4194
|
+
return buildReturning(ctx, statement.returning, deleteId, rowScope, "main");
|
|
4195
|
+
}
|
|
4196
|
+
function tsUnion(type) {
|
|
4197
|
+
const base = type.tsType === "null" ? "null" : type.tsType;
|
|
4198
|
+
if (type.nullable === true && base !== "null" && base !== "unknown") return `${base} | null`;
|
|
4199
|
+
return base;
|
|
4200
|
+
}
|
|
4201
|
+
function isPlainKey(name) {
|
|
4202
|
+
return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(name);
|
|
4203
|
+
}
|
|
4204
|
+
function rowTypeOf(columns, kind) {
|
|
4205
|
+
if (columns.length === 0) return kind === "select" ? "{}" : "never";
|
|
4206
|
+
return `{ ${columns.map((column) => `${isPlainKey(column.name) ? column.name : JSON.stringify(column.name)}: ${tsUnion(column)}`).join("; ")} }`;
|
|
4207
|
+
}
|
|
4208
|
+
/** Placeholders in the order a driver binds them: positional as written, `$n` by number, named by first appearance. */
|
|
4209
|
+
function orderParams(ctx) {
|
|
4210
|
+
const numbered = ctx.params.every((param) => /^\$\d+$/u.test(param.placeholder));
|
|
4211
|
+
const named = ctx.params.length > 0 && ctx.params.every((param) => /^[:@$][A-Za-z_]/u.test(param.placeholder));
|
|
4212
|
+
const sorted = [...ctx.params].toSorted((a, b) => a.range.start - b.range.start);
|
|
4213
|
+
if (numbered) {
|
|
4214
|
+
const byIndex = /* @__PURE__ */ new Map();
|
|
4215
|
+
for (const param of sorted) {
|
|
4216
|
+
const index = Number(param.placeholder.slice(1));
|
|
4217
|
+
const existing = byIndex.get(index);
|
|
4218
|
+
if (existing === void 0 || existing.type.tsType === "unknown" && param.type.tsType !== "unknown") byIndex.set(index, param);
|
|
4219
|
+
}
|
|
4220
|
+
return [...byIndex.entries()].toSorted((a, b) => a[0] - b[0]).map(([index, param]) => ({
|
|
4221
|
+
index,
|
|
4222
|
+
placeholder: param.placeholder,
|
|
4223
|
+
dataType: param.type.dataType,
|
|
4224
|
+
tsType: param.type.tsType,
|
|
4225
|
+
nullable: param.type.nullable,
|
|
4226
|
+
context: param.context
|
|
4227
|
+
}));
|
|
4228
|
+
}
|
|
4229
|
+
if (named) {
|
|
4230
|
+
const byName = /* @__PURE__ */ new Map();
|
|
4231
|
+
for (const param of sorted) {
|
|
4232
|
+
const existing = byName.get(param.placeholder);
|
|
4233
|
+
if (existing === void 0 || existing.type.tsType === "unknown" && param.type.tsType !== "unknown") byName.set(param.placeholder, param);
|
|
4234
|
+
}
|
|
4235
|
+
return [...byName.values()].map((param, index) => ({
|
|
4236
|
+
index: index + 1,
|
|
4237
|
+
placeholder: param.placeholder,
|
|
4238
|
+
dataType: param.type.dataType,
|
|
4239
|
+
tsType: param.type.tsType,
|
|
4240
|
+
nullable: param.type.nullable,
|
|
4241
|
+
context: param.context
|
|
4242
|
+
}));
|
|
4243
|
+
}
|
|
4244
|
+
return sorted.map((param, index) => ({
|
|
4245
|
+
index: index + 1,
|
|
4246
|
+
placeholder: param.placeholder,
|
|
4247
|
+
dataType: param.type.dataType,
|
|
4248
|
+
tsType: param.type.tsType,
|
|
4249
|
+
nullable: param.type.nullable,
|
|
4250
|
+
context: param.context
|
|
431
4251
|
}));
|
|
432
4252
|
}
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
const
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
primaryKey: z$1.array(z$1.string()).readonly().nullable().meta({ description: "The fields of a composite @@id, when the model has one." }),
|
|
445
|
-
fields: z$1.array(z$1.object({
|
|
446
|
-
name: z$1.string().meta({
|
|
447
|
-
description: "The Prisma field name.",
|
|
448
|
-
example: "createdAt"
|
|
449
|
-
}),
|
|
450
|
-
dbName: z$1.string().nullable().meta({
|
|
451
|
-
description: "The @map column name, when set.",
|
|
452
|
-
example: "created_at"
|
|
453
|
-
}),
|
|
454
|
-
kind: z$1.string().meta({
|
|
455
|
-
description: "scalar, object, enum or unsupported.",
|
|
456
|
-
example: "scalar"
|
|
457
|
-
}),
|
|
458
|
-
type: z$1.string().meta({
|
|
459
|
-
description: "The declared type.",
|
|
460
|
-
example: "DateTime"
|
|
461
|
-
}),
|
|
462
|
-
isList: z$1.boolean().meta({
|
|
463
|
-
description: "Whether the field is a list.",
|
|
464
|
-
example: false
|
|
465
|
-
}),
|
|
466
|
-
isId: z$1.boolean().meta({
|
|
467
|
-
description: "Whether the field is @id.",
|
|
468
|
-
example: false
|
|
469
|
-
}),
|
|
470
|
-
isUnique: z$1.boolean().meta({
|
|
471
|
-
description: "Whether the field is @unique.",
|
|
472
|
-
example: false
|
|
473
|
-
})
|
|
474
|
-
}).readonly()).readonly().meta({ description: "The fields of the model, relations included." })
|
|
475
|
-
}).readonly().meta({ description: "The part of a Studio model the SQL builders read" });
|
|
476
|
-
const Dialect$1 = z$1.enum([
|
|
477
|
-
"postgresql",
|
|
478
|
-
"mysql",
|
|
479
|
-
"sqlite"
|
|
480
|
-
]).meta({
|
|
481
|
-
description: "The SQL dialect of the connected database",
|
|
482
|
-
example: "postgresql"
|
|
483
|
-
});
|
|
484
|
-
const Row = z$1.record(z$1.string(), z$1.union([
|
|
485
|
-
z$1.string(),
|
|
486
|
-
z$1.number(),
|
|
487
|
-
z$1.boolean(),
|
|
488
|
-
z$1.null()
|
|
489
|
-
])).readonly().meta({ description: "A row keyed by Prisma field name" });
|
|
490
|
-
const Enums = z$1.array(z$1.object({
|
|
491
|
-
name: z$1.string().meta({
|
|
492
|
-
description: "The enum name as declared.",
|
|
493
|
-
example: "Role"
|
|
494
|
-
}),
|
|
495
|
-
values: z$1.array(z$1.object({
|
|
496
|
-
name: z$1.string().meta({
|
|
497
|
-
description: "The member name as declared.",
|
|
498
|
-
example: "ADMIN"
|
|
499
|
-
}),
|
|
500
|
-
dbName: z$1.string().nullable().meta({
|
|
501
|
-
description: "The @map stored value, when set.",
|
|
502
|
-
example: "admin"
|
|
503
|
-
})
|
|
504
|
-
}).readonly()).readonly().meta({ description: "The members of the enum." })
|
|
505
|
-
}).readonly()).readonly().meta({ description: "The schema enums, whose members may be `@map`ped to other names" });
|
|
506
|
-
z$1.object({ model: Model }).readonly().meta({ description: "A studio model" });
|
|
507
|
-
/** The scalar and enum fields, i.e. the table columns. */
|
|
508
|
-
function tableColumns(input) {
|
|
509
|
-
return input.model.fields.filter((f) => f.kind !== "object");
|
|
4253
|
+
function paramsTypeOf(params) {
|
|
4254
|
+
if (params.length === 0) return "[]";
|
|
4255
|
+
const named = params.every((param) => /^[:@$][A-Za-z_]/u.test(param.placeholder));
|
|
4256
|
+
const entry = (param) => tsUnion({
|
|
4257
|
+
dataType: param.dataType,
|
|
4258
|
+
tsType: param.tsType,
|
|
4259
|
+
nullable: param.nullable,
|
|
4260
|
+
sources: []
|
|
4261
|
+
});
|
|
4262
|
+
if (named) return `{ ${params.map((param) => `${param.placeholder.slice(1)}: ${entry(param)}`).join("; ")} }`;
|
|
4263
|
+
return `[${params.map(entry).join(", ")}]`;
|
|
510
4264
|
}
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
4265
|
+
function finish(ctx, kind, range, columns) {
|
|
4266
|
+
const parameters = orderParams(ctx);
|
|
4267
|
+
const nodes = ctx.nodes.map((node) => {
|
|
4268
|
+
const ref = ctx.refs.find((candidate) => candidate.nodeId === node.id);
|
|
4269
|
+
if (ref === void 0) return node;
|
|
4270
|
+
const used = new Set([...ref.used].map((name) => name.toLowerCase()));
|
|
4271
|
+
return {
|
|
4272
|
+
...node,
|
|
4273
|
+
columns: node.columns.map((column) => ({
|
|
4274
|
+
...column,
|
|
4275
|
+
used: used.has(column.name.toLowerCase())
|
|
4276
|
+
}))
|
|
4277
|
+
};
|
|
4278
|
+
});
|
|
4279
|
+
return {
|
|
4280
|
+
kind,
|
|
4281
|
+
text: ctx.text.slice(range.start, range.end),
|
|
4282
|
+
range,
|
|
4283
|
+
nodes,
|
|
4284
|
+
edges: ctx.edges,
|
|
4285
|
+
tables: ctx.refs.map((ref) => ({
|
|
4286
|
+
nodeId: ref.nodeId,
|
|
4287
|
+
name: ref.name,
|
|
4288
|
+
alias: ref.alias,
|
|
4289
|
+
scope: ref.scope,
|
|
4290
|
+
known: ref.known,
|
|
4291
|
+
columnsUsed: [...ref.used].filter((name, index, all) => all.findIndex((other) => other.toLowerCase() === name.toLowerCase()) === index),
|
|
4292
|
+
range: ref.range
|
|
4293
|
+
})),
|
|
4294
|
+
columns: columns.map((column) => ({
|
|
4295
|
+
name: column.name,
|
|
4296
|
+
expression: column.expression,
|
|
4297
|
+
dataType: column.dataType,
|
|
4298
|
+
tsType: column.tsType,
|
|
4299
|
+
nullable: column.nullable,
|
|
4300
|
+
sources: column.sources
|
|
4301
|
+
})),
|
|
4302
|
+
parameters,
|
|
4303
|
+
diagnostics: ctx.diagnostics,
|
|
4304
|
+
rowType: rowTypeOf(columns, kind),
|
|
4305
|
+
paramsType: paramsTypeOf(parameters)
|
|
4306
|
+
};
|
|
524
4307
|
}
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
4308
|
+
function makeContext(text, schema) {
|
|
4309
|
+
return {
|
|
4310
|
+
dialect: schema.dialect,
|
|
4311
|
+
text,
|
|
4312
|
+
tables: new Map(schema.tables.map((table) => [table.name.toLowerCase(), table])),
|
|
4313
|
+
nodes: [],
|
|
4314
|
+
edges: [],
|
|
4315
|
+
refs: [],
|
|
4316
|
+
diagnostics: [],
|
|
4317
|
+
params: [],
|
|
4318
|
+
counter: 0
|
|
4319
|
+
};
|
|
535
4320
|
}
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
4321
|
+
function analyzeStatement(text, statement, schema) {
|
|
4322
|
+
const ctx = makeContext(text, schema);
|
|
4323
|
+
switch (statement.type) {
|
|
4324
|
+
case "select": {
|
|
4325
|
+
const built = buildQuery(ctx, statement.query, {
|
|
4326
|
+
relations: [],
|
|
4327
|
+
outer: null,
|
|
4328
|
+
ctes: /* @__PURE__ */ new Map()
|
|
4329
|
+
}, "main");
|
|
4330
|
+
return finish(ctx, "select", statement.range, built.columns);
|
|
4331
|
+
}
|
|
4332
|
+
case "insert": return finish(ctx, "insert", statement.range, buildInsert(ctx, statement));
|
|
4333
|
+
case "update": return finish(ctx, "update", statement.range, buildUpdate(ctx, statement));
|
|
4334
|
+
case "delete": return finish(ctx, "delete", statement.range, buildDelete(ctx, statement));
|
|
4335
|
+
case "other":
|
|
4336
|
+
warn(ctx, `${statement.keyword} statements are run as written; only SELECT, INSERT, UPDATE and DELETE are drawn`, statement.range, "info");
|
|
4337
|
+
return finish(ctx, "other", statement.range, []);
|
|
4338
|
+
case "invalid":
|
|
4339
|
+
warn(ctx, statement.message, {
|
|
4340
|
+
start: statement.offset,
|
|
4341
|
+
end: Math.min(statement.offset + 1, text.length)
|
|
4342
|
+
}, "error");
|
|
4343
|
+
return finish(ctx, "invalid", statement.range, []);
|
|
4344
|
+
default: return finish(ctx, "other", {
|
|
4345
|
+
start: 0,
|
|
4346
|
+
end: text.length
|
|
4347
|
+
}, []);
|
|
4348
|
+
}
|
|
540
4349
|
}
|
|
541
|
-
/**
|
|
542
|
-
function
|
|
543
|
-
return (
|
|
544
|
-
name: value.name,
|
|
545
|
-
dbName: value.dbName ?? value.name
|
|
546
|
-
}));
|
|
4350
|
+
/** Every statement of the text, analyzed against the schema. */
|
|
4351
|
+
function analyze(text, schema) {
|
|
4352
|
+
return { statements: parseStatements(text).map((statement) => analyzeStatement(text, statement, schema)) };
|
|
547
4353
|
}
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
enums: Enums
|
|
551
|
-
}).readonly().meta({ description: "A model and the schema enums its fields may refer to" });
|
|
4354
|
+
//#endregion
|
|
4355
|
+
//#region src/sql/split.ts
|
|
552
4356
|
/**
|
|
553
|
-
*
|
|
554
|
-
*
|
|
555
|
-
* PostgreSQL and a silent truncation in MySQL, so the value is translated on its way in.
|
|
4357
|
+
* Splits SQL text into statements at the `;` that sit outside quotes and comments. A driver runs
|
|
4358
|
+
* one statement per call, and the result a console shows belongs to the last one.
|
|
556
4359
|
*/
|
|
557
|
-
function
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
value: stored
|
|
589
|
-
})]];
|
|
590
|
-
}));
|
|
4360
|
+
function splitStatements$1(text) {
|
|
4361
|
+
const ends = [];
|
|
4362
|
+
let mode = "code";
|
|
4363
|
+
let quote = "";
|
|
4364
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
4365
|
+
const char = text[index] ?? "";
|
|
4366
|
+
const next = text[index + 1] ?? "";
|
|
4367
|
+
if (mode === "line-comment") {
|
|
4368
|
+
if (char === "\n") mode = "code";
|
|
4369
|
+
} else if (mode === "block-comment") {
|
|
4370
|
+
if (char === "*" && next === "/") {
|
|
4371
|
+
mode = "code";
|
|
4372
|
+
index += 1;
|
|
4373
|
+
}
|
|
4374
|
+
} else if (mode === "quoted") {
|
|
4375
|
+
if (char === quote) {
|
|
4376
|
+
if (next === quote) index += 1;
|
|
4377
|
+
else {
|
|
4378
|
+
mode = "code";
|
|
4379
|
+
quote = "";
|
|
4380
|
+
}
|
|
4381
|
+
}
|
|
4382
|
+
} else if (char === "-" && next === "-") mode = "line-comment";
|
|
4383
|
+
else if (char === "/" && next === "*") mode = "block-comment";
|
|
4384
|
+
else if (char === "'" || char === "\"" || char === "`") {
|
|
4385
|
+
mode = "quoted";
|
|
4386
|
+
quote = char;
|
|
4387
|
+
} else if (char === ";") ends.push(index);
|
|
4388
|
+
}
|
|
4389
|
+
const bounds = [...ends, text.length];
|
|
4390
|
+
return bounds.map((end, index) => text.slice(index === 0 ? 0 : (bounds[index - 1] ?? 0) + 1, end).trim()).filter((statement) => statement !== "");
|
|
591
4391
|
}
|
|
592
4392
|
//#endregion
|
|
593
4393
|
//#region src/studio/server/domain/sql.ts
|
|
@@ -845,6 +4645,43 @@ function makeDeleteStatement(input) {
|
|
|
845
4645
|
params: where.params
|
|
846
4646
|
};
|
|
847
4647
|
}
|
|
4648
|
+
z$1.object({ sql: z$1.string().meta({
|
|
4649
|
+
description: "SQL text.",
|
|
4650
|
+
example: "SELECT 1; SELECT 2"
|
|
4651
|
+
}) }).readonly().meta({
|
|
4652
|
+
description: "Text that may hold several statements",
|
|
4653
|
+
example: { sql: "SELECT 1" }
|
|
4654
|
+
});
|
|
4655
|
+
/**
|
|
4656
|
+
* The statements of the text, split at `;` outside quotes and comments. A driver runs one
|
|
4657
|
+
* statement per call, and a result page belongs to the last one, as a console would show it.
|
|
4658
|
+
*/
|
|
4659
|
+
function splitStatements(input) {
|
|
4660
|
+
return splitStatements$1(input.sql);
|
|
4661
|
+
}
|
|
4662
|
+
z$1.object({
|
|
4663
|
+
dialect: Dialect,
|
|
4664
|
+
sql: z$1.string().meta({
|
|
4665
|
+
description: "The statement to explain.",
|
|
4666
|
+
example: "SELECT 1"
|
|
4667
|
+
})
|
|
4668
|
+
}).readonly().meta({
|
|
4669
|
+
description: "A statement and the dialect whose EXPLAIN syntax to use",
|
|
4670
|
+
example: {
|
|
4671
|
+
dialect: "sqlite",
|
|
4672
|
+
sql: "SELECT 1"
|
|
4673
|
+
}
|
|
4674
|
+
});
|
|
4675
|
+
/** The EXPLAIN form each database answers with a machine-readable plan. */
|
|
4676
|
+
function makeExplainStatement(input) {
|
|
4677
|
+
const body = input.sql.trim().replace(/;\s*$/u, "");
|
|
4678
|
+
switch (input.dialect) {
|
|
4679
|
+
case "sqlite": return `EXPLAIN QUERY PLAN ${body}`;
|
|
4680
|
+
case "postgresql": return `EXPLAIN (FORMAT JSON) ${body}`;
|
|
4681
|
+
case "mysql": return `EXPLAIN FORMAT=JSON ${body}`;
|
|
4682
|
+
default: return `EXPLAIN ${body}`;
|
|
4683
|
+
}
|
|
4684
|
+
}
|
|
848
4685
|
//#endregion
|
|
849
4686
|
//#region src/studio/server/domain/url.ts
|
|
850
4687
|
z$1.object({ text: z$1.string().meta({
|
|
@@ -1079,6 +4916,16 @@ function openSqlite(url, baseDir) {
|
|
|
1079
4916
|
},
|
|
1080
4917
|
catch: databaseError
|
|
1081
4918
|
}),
|
|
4919
|
+
explain: (statement) => Effect.try({
|
|
4920
|
+
try: () => {
|
|
4921
|
+
const prepared = db.prepare(makeExplainStatement({
|
|
4922
|
+
dialect: "sqlite",
|
|
4923
|
+
sql: statement.sql
|
|
4924
|
+
}));
|
|
4925
|
+
return makeSqlitePlan({ rows: DriverRows.catch([]).parse(prepared.all(...statement.params)) });
|
|
4926
|
+
},
|
|
4927
|
+
catch: databaseError
|
|
4928
|
+
}),
|
|
1082
4929
|
close: Effect.sync(() => {
|
|
1083
4930
|
db.close();
|
|
1084
4931
|
})
|
|
@@ -1128,6 +4975,16 @@ function openPostgres(url, cwd) {
|
|
|
1128
4975
|
},
|
|
1129
4976
|
catch: databaseError
|
|
1130
4977
|
}),
|
|
4978
|
+
explain: (statement) => Effect.tryPromise({
|
|
4979
|
+
try: async () => {
|
|
4980
|
+
const { rows } = PgResult.catch({ rows: [] }).parse(await client.query(makeExplainStatement({
|
|
4981
|
+
dialect: "postgresql",
|
|
4982
|
+
sql: statement.sql
|
|
4983
|
+
}), statement.params));
|
|
4984
|
+
return makePostgresPlan({ document: rows[0]?.["QUERY PLAN"] ?? null });
|
|
4985
|
+
},
|
|
4986
|
+
catch: databaseError
|
|
4987
|
+
}),
|
|
1131
4988
|
close: Effect.promise(() => client.end())
|
|
1132
4989
|
};
|
|
1133
4990
|
});
|
|
@@ -1164,6 +5021,16 @@ function openMysql(url, cwd) {
|
|
|
1164
5021
|
},
|
|
1165
5022
|
catch: databaseError
|
|
1166
5023
|
}),
|
|
5024
|
+
explain: (statement) => Effect.tryPromise({
|
|
5025
|
+
try: async () => {
|
|
5026
|
+
const [data] = MysqlResult.catch([[], void 0]).parse(await connection.query(makeExplainStatement({
|
|
5027
|
+
dialect: "mysql",
|
|
5028
|
+
sql: statement.sql
|
|
5029
|
+
}), statement.params));
|
|
5030
|
+
return makeMysqlPlan({ document: (Array.isArray(data) ? data[0] : void 0)?.EXPLAIN ?? null });
|
|
5031
|
+
},
|
|
5032
|
+
catch: databaseError
|
|
5033
|
+
}),
|
|
1167
5034
|
close: Effect.promise(() => connection.end())
|
|
1168
5035
|
};
|
|
1169
5036
|
});
|
|
@@ -2389,6 +6256,269 @@ function watchSchema(input) {
|
|
|
2389
6256
|
}
|
|
2390
6257
|
//#endregion
|
|
2391
6258
|
//#region src/studio/server/routes/index.ts
|
|
6259
|
+
const StatementKindSchema = z.enum([
|
|
6260
|
+
"select",
|
|
6261
|
+
"insert",
|
|
6262
|
+
"update",
|
|
6263
|
+
"delete",
|
|
6264
|
+
"other",
|
|
6265
|
+
"invalid"
|
|
6266
|
+
]).openapi({ description: "What kind of statement was analyzed." }).openapi("StatementKind");
|
|
6267
|
+
const TextRangeSchema = z.object({
|
|
6268
|
+
start: z.int32().openapi({ description: "The first character" }),
|
|
6269
|
+
end: z.int32().openapi({ description: "One past the last character" })
|
|
6270
|
+
}).openapi({
|
|
6271
|
+
required: ["start", "end"],
|
|
6272
|
+
description: "Character offsets into the statement text, end exclusive.",
|
|
6273
|
+
example: {
|
|
6274
|
+
start: 7,
|
|
6275
|
+
end: 12
|
|
6276
|
+
}
|
|
6277
|
+
}).openapi("TextRange");
|
|
6278
|
+
const NodeKindSchema = z.enum([
|
|
6279
|
+
"table",
|
|
6280
|
+
"cte",
|
|
6281
|
+
"subquery",
|
|
6282
|
+
"values",
|
|
6283
|
+
"function",
|
|
6284
|
+
"join",
|
|
6285
|
+
"filter",
|
|
6286
|
+
"aggregate",
|
|
6287
|
+
"having",
|
|
6288
|
+
"project",
|
|
6289
|
+
"distinct",
|
|
6290
|
+
"sort",
|
|
6291
|
+
"limit",
|
|
6292
|
+
"union",
|
|
6293
|
+
"insert",
|
|
6294
|
+
"update",
|
|
6295
|
+
"delete",
|
|
6296
|
+
"returning"
|
|
6297
|
+
]).openapi({ description: "What a node of the data-flow graph stands for." }).openapi("NodeKind");
|
|
6298
|
+
const NodeColumnSchema = z.object({
|
|
6299
|
+
name: z.string().openapi({ description: "The column name" }),
|
|
6300
|
+
dataType: z.string().nullable().openapi({ description: "The declared type, when known" }),
|
|
6301
|
+
used: z.boolean().openapi({ description: "Whether the statement reads the column (for a table), or always true for a result" })
|
|
6302
|
+
}).openapi({
|
|
6303
|
+
required: [
|
|
6304
|
+
"name",
|
|
6305
|
+
"dataType",
|
|
6306
|
+
"used"
|
|
6307
|
+
],
|
|
6308
|
+
description: "A column a node produces.",
|
|
6309
|
+
example: {
|
|
6310
|
+
name: "email",
|
|
6311
|
+
dataType: "TEXT",
|
|
6312
|
+
used: true
|
|
6313
|
+
}
|
|
6314
|
+
}).openapi("NodeColumn");
|
|
6315
|
+
const GraphNodeSchema = z.object({
|
|
6316
|
+
id: z.string().openapi({ description: "The node id, unique within the statement" }),
|
|
6317
|
+
kind: NodeKindSchema.openapi({ description: "What the node stands for" }),
|
|
6318
|
+
label: z.string().openapi({ description: "The caption (`users AS u`, `LEFT JOIN`, `WHERE`)" }),
|
|
6319
|
+
details: z.array(z.string()).openapi({ description: "Lines under the caption: the condition, the grouped keys, the column names" }),
|
|
6320
|
+
range: TextRangeSchema.nullable().openapi({ description: "Where the node's clause sits in the text, when it has one" }),
|
|
6321
|
+
scope: z.string().openapi({ description: "`main`, or the CTE / subquery alias the node belongs to" }),
|
|
6322
|
+
columns: z.array(NodeColumnSchema).openapi({ description: "The columns the node produces (tables, CTEs, subqueries and projections)" })
|
|
6323
|
+
}).openapi({
|
|
6324
|
+
required: [
|
|
6325
|
+
"id",
|
|
6326
|
+
"kind",
|
|
6327
|
+
"label",
|
|
6328
|
+
"details",
|
|
6329
|
+
"range",
|
|
6330
|
+
"scope",
|
|
6331
|
+
"columns"
|
|
6332
|
+
],
|
|
6333
|
+
description: "A node of the data-flow graph.",
|
|
6334
|
+
example: {
|
|
6335
|
+
id: "n3",
|
|
6336
|
+
kind: "filter",
|
|
6337
|
+
label: "WHERE",
|
|
6338
|
+
details: ["u.id = ?"],
|
|
6339
|
+
range: {
|
|
6340
|
+
start: 40,
|
|
6341
|
+
end: 48
|
|
6342
|
+
},
|
|
6343
|
+
scope: "main",
|
|
6344
|
+
columns: []
|
|
6345
|
+
}
|
|
6346
|
+
}).openapi("GraphNode");
|
|
6347
|
+
const EdgeKindSchema = z.enum(["flow", "lookup"]).openapi({ description: "How rows travel along an edge." }).openapi("EdgeKind");
|
|
6348
|
+
const GraphEdgeSchema = z.object({
|
|
6349
|
+
id: z.string().openapi({ description: "The edge id, unique within the statement" }),
|
|
6350
|
+
source: z.string().openapi({ description: "The node rows come from" }),
|
|
6351
|
+
target: z.string().openapi({ description: "The node rows go to" }),
|
|
6352
|
+
label: z.string().nullable().openapi({ description: "A caption (`optional` for the outer side of a join, `scalar` for a scalar subquery)" }),
|
|
6353
|
+
kind: EdgeKindSchema.openapi({ description: "How rows travel" })
|
|
6354
|
+
}).openapi({
|
|
6355
|
+
required: [
|
|
6356
|
+
"id",
|
|
6357
|
+
"source",
|
|
6358
|
+
"target",
|
|
6359
|
+
"label",
|
|
6360
|
+
"kind"
|
|
6361
|
+
],
|
|
6362
|
+
description: "An edge of the data-flow graph.",
|
|
6363
|
+
example: {
|
|
6364
|
+
id: "n1->n3:0",
|
|
6365
|
+
source: "n1",
|
|
6366
|
+
target: "n3",
|
|
6367
|
+
label: null,
|
|
6368
|
+
kind: "flow"
|
|
6369
|
+
}
|
|
6370
|
+
}).openapi("GraphEdge");
|
|
6371
|
+
const TableRefSchema = z.object({
|
|
6372
|
+
nodeId: z.string().openapi({ description: "The graph node of this reference" }),
|
|
6373
|
+
name: z.string().openapi({ description: "The table name as written" }),
|
|
6374
|
+
alias: z.string().nullable().openapi({ description: "The alias, when one was given" }),
|
|
6375
|
+
scope: z.string().openapi({ description: "`main`, or the CTE / subquery alias the reference sits in" }),
|
|
6376
|
+
known: z.boolean().openapi({ description: "Whether the schema has the table" }),
|
|
6377
|
+
columnsUsed: z.array(z.string()).openapi({ description: "The columns the statement reads from this reference" }),
|
|
6378
|
+
range: TextRangeSchema.openapi({ description: "Where the name sits in the text" })
|
|
6379
|
+
}).openapi({
|
|
6380
|
+
required: [
|
|
6381
|
+
"nodeId",
|
|
6382
|
+
"name",
|
|
6383
|
+
"alias",
|
|
6384
|
+
"scope",
|
|
6385
|
+
"known",
|
|
6386
|
+
"columnsUsed",
|
|
6387
|
+
"range"
|
|
6388
|
+
],
|
|
6389
|
+
description: "A table the statement reads or writes.",
|
|
6390
|
+
example: {
|
|
6391
|
+
nodeId: "n1",
|
|
6392
|
+
name: "users",
|
|
6393
|
+
alias: "u",
|
|
6394
|
+
scope: "main",
|
|
6395
|
+
known: true,
|
|
6396
|
+
columnsUsed: ["id", "email"],
|
|
6397
|
+
range: {
|
|
6398
|
+
start: 20,
|
|
6399
|
+
end: 25
|
|
6400
|
+
}
|
|
6401
|
+
}
|
|
6402
|
+
}).openapi("TableRef");
|
|
6403
|
+
const ColumnSourceSchema = z.object({
|
|
6404
|
+
table: z.string().openapi({ description: "The base table" }),
|
|
6405
|
+
column: z.string().openapi({ description: "The column of that table" })
|
|
6406
|
+
}).openapi({
|
|
6407
|
+
required: ["table", "column"],
|
|
6408
|
+
description: "A base-table column an output column derives from.",
|
|
6409
|
+
example: {
|
|
6410
|
+
table: "users",
|
|
6411
|
+
column: "email"
|
|
6412
|
+
}
|
|
6413
|
+
}).openapi("ColumnSource");
|
|
6414
|
+
const OutputColumnSchema = z.object({
|
|
6415
|
+
name: z.string().openapi({ description: "The name a driver keys the row with" }),
|
|
6416
|
+
expression: z.string().openapi({ description: "The expression as written" }),
|
|
6417
|
+
dataType: z.string().nullable().openapi({ description: "The declared type, when known" }),
|
|
6418
|
+
tsType: z.string().openapi({ description: "The TypeScript type of the value" }),
|
|
6419
|
+
nullable: z.boolean().nullable().openapi({ description: "Whether NULL can come back; null when the analysis cannot tell" }),
|
|
6420
|
+
sources: z.array(ColumnSourceSchema).openapi({ description: "The base-table columns the value derives from" })
|
|
6421
|
+
}).openapi({
|
|
6422
|
+
required: [
|
|
6423
|
+
"name",
|
|
6424
|
+
"expression",
|
|
6425
|
+
"dataType",
|
|
6426
|
+
"tsType",
|
|
6427
|
+
"nullable",
|
|
6428
|
+
"sources"
|
|
6429
|
+
],
|
|
6430
|
+
description: "A column of the result, with its lineage and type.",
|
|
6431
|
+
example: {
|
|
6432
|
+
name: "email",
|
|
6433
|
+
expression: "u.email",
|
|
6434
|
+
dataType: "TEXT",
|
|
6435
|
+
tsType: "string",
|
|
6436
|
+
nullable: true,
|
|
6437
|
+
sources: [{
|
|
6438
|
+
table: "users",
|
|
6439
|
+
column: "email"
|
|
6440
|
+
}]
|
|
6441
|
+
}
|
|
6442
|
+
}).openapi("OutputColumn");
|
|
6443
|
+
const SqlParameterSchema = z.object({
|
|
6444
|
+
index: z.int32().openapi({ description: "The bind position (1-based), or the `$n` number" }),
|
|
6445
|
+
placeholder: z.string().openapi({ description: "The placeholder as written (`?`, `$1`, `:name`)" }),
|
|
6446
|
+
dataType: z.string().nullable().openapi({ description: "The declared type of the column it is compared with, when known" }),
|
|
6447
|
+
tsType: z.string().openapi({ description: "The TypeScript type a value should have" }),
|
|
6448
|
+
nullable: z.boolean().nullable().openapi({ description: "Whether NULL is a valid value; null when the analysis cannot tell" }),
|
|
6449
|
+
context: z.string().openapi({ description: "The expression the placeholder sits in" })
|
|
6450
|
+
}).openapi({
|
|
6451
|
+
required: [
|
|
6452
|
+
"index",
|
|
6453
|
+
"placeholder",
|
|
6454
|
+
"dataType",
|
|
6455
|
+
"tsType",
|
|
6456
|
+
"nullable",
|
|
6457
|
+
"context"
|
|
6458
|
+
],
|
|
6459
|
+
description: "A placeholder and the type of what it stands beside.",
|
|
6460
|
+
example: {
|
|
6461
|
+
index: 1,
|
|
6462
|
+
placeholder: "?",
|
|
6463
|
+
dataType: "INTEGER",
|
|
6464
|
+
tsType: "number",
|
|
6465
|
+
nullable: false,
|
|
6466
|
+
context: "u.id = ?"
|
|
6467
|
+
}
|
|
6468
|
+
}).openapi("SqlParameter");
|
|
6469
|
+
const SqlSeveritySchema = z.enum([
|
|
6470
|
+
"error",
|
|
6471
|
+
"warning",
|
|
6472
|
+
"info"
|
|
6473
|
+
]).openapi({ description: "How serious a problem the analysis found is." }).openapi("SqlSeverity");
|
|
6474
|
+
const SqlDiagnosticSchema = z.object({
|
|
6475
|
+
severity: SqlSeveritySchema.openapi({ description: "How serious it is" }),
|
|
6476
|
+
message: z.string().openapi({ description: "What is wrong" }),
|
|
6477
|
+
range: TextRangeSchema.nullable().openapi({ description: "Where, when the analysis can point at it" })
|
|
6478
|
+
}).openapi({
|
|
6479
|
+
required: [
|
|
6480
|
+
"severity",
|
|
6481
|
+
"message",
|
|
6482
|
+
"range"
|
|
6483
|
+
],
|
|
6484
|
+
description: "A problem found in the statement.",
|
|
6485
|
+
example: {
|
|
6486
|
+
severity: "warning",
|
|
6487
|
+
message: "Unknown column \"nmae\"",
|
|
6488
|
+
range: {
|
|
6489
|
+
start: 7,
|
|
6490
|
+
end: 11
|
|
6491
|
+
}
|
|
6492
|
+
}
|
|
6493
|
+
}).openapi("SqlDiagnostic");
|
|
6494
|
+
const StatementAnalysisSchema = z.object({
|
|
6495
|
+
kind: StatementKindSchema.openapi({ description: "What kind of statement it is" }),
|
|
6496
|
+
text: z.string().openapi({ description: "The statement text" }),
|
|
6497
|
+
range: TextRangeSchema.openapi({ description: "Where the statement sits in the submitted text" }),
|
|
6498
|
+
nodes: z.array(GraphNodeSchema).openapi({ description: "The nodes of the data-flow graph" }),
|
|
6499
|
+
edges: z.array(GraphEdgeSchema).openapi({ description: "The edges of the data-flow graph" }),
|
|
6500
|
+
tables: z.array(TableRefSchema).openapi({ description: "Every table the statement touches" }),
|
|
6501
|
+
columns: z.array(OutputColumnSchema).openapi({ description: "The columns of the result (empty for a write without RETURNING)" }),
|
|
6502
|
+
parameters: z.array(SqlParameterSchema).openapi({ description: "The placeholders, in bind order" }),
|
|
6503
|
+
diagnostics: z.array(SqlDiagnosticSchema).openapi({ description: "What was found wrong" }),
|
|
6504
|
+
rowType: z.string().openapi({ description: "The row type as TypeScript (`{ id: number; email: string | null }`)" }),
|
|
6505
|
+
paramsType: z.string().openapi({ description: "The parameter tuple (or object, for named placeholders) as TypeScript" })
|
|
6506
|
+
}).openapi({
|
|
6507
|
+
required: [
|
|
6508
|
+
"kind",
|
|
6509
|
+
"text",
|
|
6510
|
+
"range",
|
|
6511
|
+
"nodes",
|
|
6512
|
+
"edges",
|
|
6513
|
+
"tables",
|
|
6514
|
+
"columns",
|
|
6515
|
+
"parameters",
|
|
6516
|
+
"diagnostics",
|
|
6517
|
+
"rowType",
|
|
6518
|
+
"paramsType"
|
|
6519
|
+
],
|
|
6520
|
+
description: "The analysis of one statement."
|
|
6521
|
+
}).openapi("StatementAnalysis");
|
|
2392
6522
|
const SchemaFileSchema = z.object({
|
|
2393
6523
|
path: z.string().openapi({ description: "The file path as Studio loaded it (the value to send back as `FileWrite.path`)" }),
|
|
2394
6524
|
content: z.string().openapi({ description: "The whole file content" })
|
|
@@ -3097,12 +7227,71 @@ const SqlResultSchema = z.object({
|
|
|
3097
7227
|
durationMs: .4
|
|
3098
7228
|
}
|
|
3099
7229
|
}).openapi("SqlResult");
|
|
3100
|
-
const SqlSchema = z.string({ error: "SQL must be a string" }).trim().min(1, { error: "SQL must not be empty" }).brand().openapi({ description: "
|
|
3101
|
-
const SqlBodySchema = z.object({
|
|
7230
|
+
const SqlSchema = z.string({ error: "SQL must be a string" }).trim().min(1, { error: "SQL must not be empty" }).brand().openapi({ description: "SQL text: one or more statements, analyzed or run as written (the Studio API is loopback-only; there is no sandbox)." }).openapi("Sql");
|
|
7231
|
+
const SqlBodySchema = z.object({
|
|
7232
|
+
sql: SqlSchema.openapi({ description: "The statements; several are run one by one and the result belongs to the last" }),
|
|
7233
|
+
params: z.array(z.union([
|
|
7234
|
+
z.string(),
|
|
7235
|
+
z.float64(),
|
|
7236
|
+
z.boolean()
|
|
7237
|
+
]).nullable()).exactOptional().openapi({ description: "The values bound to the placeholders, in order; omitted means none" })
|
|
7238
|
+
}).openapi({
|
|
3102
7239
|
required: ["sql"],
|
|
3103
7240
|
description: "A statement to run.",
|
|
3104
7241
|
example: { sql: "SELECT id, email FROM users LIMIT 10" }
|
|
3105
7242
|
}).openapi("SqlBody");
|
|
7243
|
+
const PlanNodeSchema = z.object({
|
|
7244
|
+
id: z.string().openapi({ description: "The step id, unique within the plan" }),
|
|
7245
|
+
parent: z.string().nullable().openapi({ description: "The id of the step this one feeds, or null for a root" }),
|
|
7246
|
+
label: z.string().openapi({ description: "What the step does (`SCAN users`, `Seq Scan on users`, `Hash Join`)" }),
|
|
7247
|
+
detail: z.string().nullable().openapi({ description: "The rest of what the database said about the step" }),
|
|
7248
|
+
cost: z.float64().nullable().openapi({ description: "The estimated cost, when the database reports one" }),
|
|
7249
|
+
rows: z.float64().nullable().openapi({ description: "The estimated (or, with ANALYZE, actual) row count, when reported" })
|
|
7250
|
+
}).openapi({
|
|
7251
|
+
required: [
|
|
7252
|
+
"id",
|
|
7253
|
+
"parent",
|
|
7254
|
+
"label",
|
|
7255
|
+
"detail",
|
|
7256
|
+
"cost",
|
|
7257
|
+
"rows"
|
|
7258
|
+
],
|
|
7259
|
+
description: "One step of the execution plan, flattened; `parent` rebuilds the tree.",
|
|
7260
|
+
example: {
|
|
7261
|
+
id: "3",
|
|
7262
|
+
parent: null,
|
|
7263
|
+
label: "SCAN users",
|
|
7264
|
+
detail: null,
|
|
7265
|
+
cost: null,
|
|
7266
|
+
rows: null
|
|
7267
|
+
}
|
|
7268
|
+
}).openapi("PlanNode");
|
|
7269
|
+
const PlanSchema = z.object({
|
|
7270
|
+
dialect: DialectSchema.openapi({ description: "The dialect that produced the plan" }),
|
|
7271
|
+
nodes: z.array(PlanNodeSchema).openapi({ description: "The steps, parents before children" }),
|
|
7272
|
+
raw: z.string().openapi({ description: "The plan as the database printed it" })
|
|
7273
|
+
}).brand().openapi({
|
|
7274
|
+
required: [
|
|
7275
|
+
"dialect",
|
|
7276
|
+
"nodes",
|
|
7277
|
+
"raw"
|
|
7278
|
+
],
|
|
7279
|
+
description: "The execution plan of a statement.",
|
|
7280
|
+
example: {
|
|
7281
|
+
dialect: "sqlite",
|
|
7282
|
+
nodes: [],
|
|
7283
|
+
raw: ""
|
|
7284
|
+
}
|
|
7285
|
+
}).openapi("Plan");
|
|
7286
|
+
const AnalysisSchema = z.lazy(() => z.object({ statements: z.array(StatementAnalysisSchema).openapi({ description: "One entry per statement, in order" }) }).brand().openapi({
|
|
7287
|
+
required: ["statements"],
|
|
7288
|
+
description: "The analysis of every statement in the text."
|
|
7289
|
+
})).openapi("Analysis");
|
|
7290
|
+
const AnalyzeBodySchema = z.object({ sql: SqlSchema.openapi({ description: "The statements" }) }).openapi({
|
|
7291
|
+
required: ["sql"],
|
|
7292
|
+
description: "Text to analyze.",
|
|
7293
|
+
example: { sql: "SELECT id, email FROM users WHERE id = ?" }
|
|
7294
|
+
}).openapi("AnalyzeBody");
|
|
3106
7295
|
const LspTextEditSchema = z.object({
|
|
3107
7296
|
range: LspRangeSchema.openapi({ description: "What to replace" }),
|
|
3108
7297
|
newText: z.string().openapi({ description: "The replacement" })
|
|
@@ -4007,7 +8196,7 @@ const postDbSqlRoute = createRoute({
|
|
|
4007
8196
|
method: "post",
|
|
4008
8197
|
path: "/db/sql",
|
|
4009
8198
|
tags: ["db"],
|
|
4010
|
-
description: "Run one
|
|
8199
|
+
description: "Run the statements one by one and return the rows of the last, or its affected count for a write, with the wall time of the whole.",
|
|
4011
8200
|
operationId: "runSql",
|
|
4012
8201
|
request: { body: {
|
|
4013
8202
|
content: { "application/json": { schema: SqlBodySchema } },
|
|
@@ -4032,6 +8221,60 @@ const postDbSqlRoute = createRoute({
|
|
|
4032
8221
|
}
|
|
4033
8222
|
}
|
|
4034
8223
|
});
|
|
8224
|
+
const postDbExplainRoute = createRoute({
|
|
8225
|
+
method: "post",
|
|
8226
|
+
path: "/db/explain",
|
|
8227
|
+
tags: ["db"],
|
|
8228
|
+
description: "The execution plan the database chooses for the first statement of the text.",
|
|
8229
|
+
operationId: "explainSql",
|
|
8230
|
+
request: { body: {
|
|
8231
|
+
content: { "application/json": { schema: SqlBodySchema } },
|
|
8232
|
+
required: true
|
|
8233
|
+
} },
|
|
8234
|
+
responses: {
|
|
8235
|
+
200: {
|
|
8236
|
+
description: "The request has succeeded.",
|
|
8237
|
+
content: { "application/json": { schema: PlanSchema } }
|
|
8238
|
+
},
|
|
8239
|
+
422: {
|
|
8240
|
+
description: "422 Unprocessable Content (`application/problem+json`)",
|
|
8241
|
+
content: { "application/problem+json": { schema: ValidationProblemSchema } }
|
|
8242
|
+
},
|
|
8243
|
+
500: {
|
|
8244
|
+
description: "500 Internal Server Error (`application/problem+json`)",
|
|
8245
|
+
content: { "application/problem+json": { schema: InternalServerProblemSchema } }
|
|
8246
|
+
},
|
|
8247
|
+
503: {
|
|
8248
|
+
description: "503 Service Unavailable (`application/problem+json`)",
|
|
8249
|
+
content: { "application/problem+json": { schema: ServiceUnavailableProblemSchema } }
|
|
8250
|
+
}
|
|
8251
|
+
}
|
|
8252
|
+
});
|
|
8253
|
+
const postDbAnalyzeRoute = createRoute({
|
|
8254
|
+
method: "post",
|
|
8255
|
+
path: "/db/analyze",
|
|
8256
|
+
tags: ["db"],
|
|
8257
|
+
description: "Analyze the statements against the Prisma schema's tables: data flow, lineage, row type, parameters and problems.",
|
|
8258
|
+
operationId: "analyzeSql",
|
|
8259
|
+
request: { body: {
|
|
8260
|
+
content: { "application/json": { schema: AnalyzeBodySchema } },
|
|
8261
|
+
required: true
|
|
8262
|
+
} },
|
|
8263
|
+
responses: {
|
|
8264
|
+
200: {
|
|
8265
|
+
description: "The request has succeeded.",
|
|
8266
|
+
content: { "application/json": { schema: AnalysisSchema } }
|
|
8267
|
+
},
|
|
8268
|
+
422: {
|
|
8269
|
+
description: "422 Unprocessable Content (`application/problem+json`)",
|
|
8270
|
+
content: { "application/problem+json": { schema: ValidationProblemSchema } }
|
|
8271
|
+
},
|
|
8272
|
+
500: {
|
|
8273
|
+
description: "500 Internal Server Error (`application/problem+json`)",
|
|
8274
|
+
content: { "application/problem+json": { schema: InternalServerProblemSchema } }
|
|
8275
|
+
}
|
|
8276
|
+
}
|
|
8277
|
+
});
|
|
4035
8278
|
const postPrismaFormatRoute = createRoute({
|
|
4036
8279
|
method: "post",
|
|
4037
8280
|
path: "/prisma/format",
|
|
@@ -4580,27 +8823,68 @@ function deleteRow(input) {
|
|
|
4580
8823
|
return result.data;
|
|
4581
8824
|
});
|
|
4582
8825
|
}
|
|
4583
|
-
|
|
4584
|
-
|
|
4585
|
-
|
|
4586
|
-
|
|
8826
|
+
const Cell = z$1.union([
|
|
8827
|
+
z$1.string(),
|
|
8828
|
+
z$1.number(),
|
|
8829
|
+
z$1.boolean(),
|
|
8830
|
+
z$1.null()
|
|
8831
|
+
]).meta({ description: "A JSON cell value as the UI sends and shows it" });
|
|
8832
|
+
z$1.object({
|
|
8833
|
+
sql: z$1.string().trim().min(1).brand().meta({
|
|
8834
|
+
description: "The statements to run.",
|
|
8835
|
+
example: "SELECT 1"
|
|
8836
|
+
}),
|
|
8837
|
+
params: z$1.array(Cell).readonly().meta({ description: "The values bound to the placeholders, in order." })
|
|
8838
|
+
}).readonly().meta({
|
|
4587
8839
|
description: "Input for running SQL",
|
|
4588
|
-
example: {
|
|
8840
|
+
example: {
|
|
8841
|
+
sql: "SELECT * FROM users",
|
|
8842
|
+
params: []
|
|
8843
|
+
}
|
|
4589
8844
|
});
|
|
4590
8845
|
/**
|
|
4591
|
-
* Runs one
|
|
8846
|
+
* Runs the statements one by one and returns the rows of the last, or its affected count for a
|
|
8847
|
+
* write, with the wall time of the whole.
|
|
8848
|
+
*
|
|
8849
|
+
* ```mermaid
|
|
8850
|
+
* sequenceDiagram
|
|
8851
|
+
* participant U as runSql
|
|
8852
|
+
* participant Db as Database
|
|
8853
|
+
* participant D as Driver
|
|
8854
|
+
* U->>Db: driver
|
|
8855
|
+
* Db-->>U: driver / DatabaseUnavailableError
|
|
8856
|
+
* Note over U: split the text into statements (domain)
|
|
8857
|
+
* loop each statement
|
|
8858
|
+
* U->>D: query(sql, params)
|
|
8859
|
+
* end
|
|
8860
|
+
* D-->>U: columns, rows, rowCount
|
|
8861
|
+
* Note over U: first SQL_ROW_LIMIT rows → validate against SqlResult
|
|
8862
|
+
* ```
|
|
4592
8863
|
*
|
|
4593
|
-
* @param input - the
|
|
8864
|
+
* @param input - the text and the parameter values
|
|
4594
8865
|
* @returns columns, rows, rowCount and durationMs
|
|
4595
8866
|
*/
|
|
4596
8867
|
function runSql(input) {
|
|
4597
8868
|
return Effect.gen(function* () {
|
|
4598
8869
|
const driver = yield* (yield* DatabaseTag).driver;
|
|
4599
|
-
const
|
|
4600
|
-
|
|
4601
|
-
|
|
4602
|
-
|
|
8870
|
+
const statements = splitStatements({ sql: input.sql });
|
|
8871
|
+
if (statements.length === 0) return yield* new InvalidInputError({
|
|
8872
|
+
field: "sql",
|
|
8873
|
+
message: "holds no statement"
|
|
4603
8874
|
});
|
|
8875
|
+
const params = input.params.map((value) => makeBindValue({
|
|
8876
|
+
dialect: driver.dialect,
|
|
8877
|
+
value
|
|
8878
|
+
}));
|
|
8879
|
+
const started = performance.now();
|
|
8880
|
+
const executed = (yield* Effect.forEach(statements, (sql) => driver.query({
|
|
8881
|
+
sql,
|
|
8882
|
+
params
|
|
8883
|
+
}))).at(-1) ?? {
|
|
8884
|
+
columns: [],
|
|
8885
|
+
rows: [],
|
|
8886
|
+
rowCount: 0
|
|
8887
|
+
};
|
|
4604
8888
|
const sqlResult = {
|
|
4605
8889
|
columns: executed.columns,
|
|
4606
8890
|
rows: executed.rows.slice(0, 500).map((row) => makeRow({
|
|
@@ -4615,6 +8899,67 @@ function runSql(input) {
|
|
|
4615
8899
|
return result.data;
|
|
4616
8900
|
});
|
|
4617
8901
|
}
|
|
8902
|
+
/**
|
|
8903
|
+
* The execution plan the database chooses for the first statement of the text.
|
|
8904
|
+
*
|
|
8905
|
+
* @param input - the text and the parameter values
|
|
8906
|
+
* @returns the plan steps, parents first, and the plan as the database printed it
|
|
8907
|
+
*/
|
|
8908
|
+
function explainSql(input) {
|
|
8909
|
+
return Effect.gen(function* () {
|
|
8910
|
+
const driver = yield* (yield* DatabaseTag).driver;
|
|
8911
|
+
const [first] = splitStatements({ sql: input.sql });
|
|
8912
|
+
if (first === void 0) return yield* new InvalidInputError({
|
|
8913
|
+
field: "sql",
|
|
8914
|
+
message: "holds no statement"
|
|
8915
|
+
});
|
|
8916
|
+
const params = input.params.map((value) => makeBindValue({
|
|
8917
|
+
dialect: driver.dialect,
|
|
8918
|
+
value
|
|
8919
|
+
}));
|
|
8920
|
+
const explained = yield* driver.explain({
|
|
8921
|
+
sql: first,
|
|
8922
|
+
params
|
|
8923
|
+
});
|
|
8924
|
+
const plan = {
|
|
8925
|
+
dialect: driver.dialect,
|
|
8926
|
+
nodes: explained.nodes,
|
|
8927
|
+
raw: explained.raw
|
|
8928
|
+
};
|
|
8929
|
+
const result = PlanSchema.safeParse(plan);
|
|
8930
|
+
if (!result.success) return yield* new ContractViolationError({ message: result.error.message });
|
|
8931
|
+
return result.data;
|
|
8932
|
+
});
|
|
8933
|
+
}
|
|
8934
|
+
z$1.object({ sql: z$1.string().trim().min(1).brand().meta({
|
|
8935
|
+
description: "The statements to analyze.",
|
|
8936
|
+
example: "SELECT id FROM users"
|
|
8937
|
+
}) }).readonly().meta({
|
|
8938
|
+
description: "Input for analyzing SQL",
|
|
8939
|
+
example: { sql: "SELECT id FROM users" }
|
|
8940
|
+
});
|
|
8941
|
+
/**
|
|
8942
|
+
* Analyzes every statement of the text against the tables of the Prisma schema: the dialect is
|
|
8943
|
+
* the connected database's, or the datasource provider's while none is connected.
|
|
8944
|
+
*
|
|
8945
|
+
* @param input - the text
|
|
8946
|
+
* @returns the data-flow graph, lineage, row type, parameters and diagnostics of each statement
|
|
8947
|
+
*/
|
|
8948
|
+
function analyzeSql(input) {
|
|
8949
|
+
return Effect.gen(function* () {
|
|
8950
|
+
const state = yield* StudioStateTag;
|
|
8951
|
+
const db = yield* DatabaseTag;
|
|
8952
|
+
const schema = state.snapshot().schema;
|
|
8953
|
+
const analysis = analyze(input.sql, makeAnalysisSchema({
|
|
8954
|
+
dialect: db.status.dialect,
|
|
8955
|
+
provider: schema?.provider ?? null,
|
|
8956
|
+
models: schema?.models ?? []
|
|
8957
|
+
}));
|
|
8958
|
+
const result = AnalysisSchema.safeParse(analysis);
|
|
8959
|
+
if (!result.success) return yield* new ContractViolationError({ message: result.error.message });
|
|
8960
|
+
return result.data;
|
|
8961
|
+
});
|
|
8962
|
+
}
|
|
4618
8963
|
//#endregion
|
|
4619
8964
|
//#region src/studio/server/usecases/docs.ts
|
|
4620
8965
|
/**
|
|
@@ -5441,9 +9786,77 @@ const deleteDbRowsModelNameRouteHandler = (c) => {
|
|
|
5441
9786
|
};
|
|
5442
9787
|
const postDbSqlRouteHandler = (c) => {
|
|
5443
9788
|
const data = c.req.valid("json");
|
|
5444
|
-
return studioRuntime().runPromise(Effect.matchEffect(runSql({
|
|
9789
|
+
return studioRuntime().runPromise(Effect.matchEffect(runSql({
|
|
9790
|
+
sql: data.sql,
|
|
9791
|
+
params: data.params ?? []
|
|
9792
|
+
}), {
|
|
9793
|
+
onSuccess: (value) => Effect.succeed(c.json(value, 200)),
|
|
9794
|
+
onFailure: (error) => Match.value(error).pipe(Match.tag("InvalidInputError", ({ field, message }) => Effect.succeed(c.json({
|
|
9795
|
+
type: "/problems/validation-failed",
|
|
9796
|
+
title: "Validation Failed",
|
|
9797
|
+
status: 422,
|
|
9798
|
+
detail: `${field} ${message}.`,
|
|
9799
|
+
instance: c.req.path,
|
|
9800
|
+
errors: [{
|
|
9801
|
+
field,
|
|
9802
|
+
message
|
|
9803
|
+
}]
|
|
9804
|
+
}, 422, { "Content-Type": "application/problem+json" }))), Match.tag("DatabaseUnavailableError", ({ reason }) => Effect.succeed(c.json({
|
|
9805
|
+
type: "/problems/service-unavailable",
|
|
9806
|
+
title: "Service Unavailable",
|
|
9807
|
+
status: 503,
|
|
9808
|
+
detail: reason,
|
|
9809
|
+
instance: c.req.path
|
|
9810
|
+
}, 503, { "Content-Type": "application/problem+json" }))), Match.tag("DatabaseError", ({ cause }) => Effect.succeed(c.json({
|
|
9811
|
+
type: "/problems/validation-failed",
|
|
9812
|
+
title: "Validation Failed",
|
|
9813
|
+
status: 422,
|
|
9814
|
+
detail: cause,
|
|
9815
|
+
instance: c.req.path,
|
|
9816
|
+
errors: [{
|
|
9817
|
+
field: "sql",
|
|
9818
|
+
message: cause
|
|
9819
|
+
}]
|
|
9820
|
+
}, 422, { "Content-Type": "application/problem+json" }))), Match.tag("ContractViolationError", ({ message }) => Effect.logError("contract violation", message).pipe(Effect.as(c.json({
|
|
9821
|
+
type: "/problems/internal-server-error",
|
|
9822
|
+
title: "Internal Server Error",
|
|
9823
|
+
status: 500,
|
|
9824
|
+
detail: "An unexpected error occurred.",
|
|
9825
|
+
instance: c.req.path
|
|
9826
|
+
}, 500, { "Content-Type": "application/problem+json" })))), Match.exhaustive)
|
|
9827
|
+
}));
|
|
9828
|
+
};
|
|
9829
|
+
const postDbAnalyzeRouteHandler = (c) => {
|
|
9830
|
+
const data = c.req.valid("json");
|
|
9831
|
+
return studioRuntime().runPromise(Effect.matchEffect(analyzeSql({ sql: data.sql }), {
|
|
9832
|
+
onSuccess: (value) => Effect.succeed(c.json(value, 200)),
|
|
9833
|
+
onFailure: (error) => Match.value(error).pipe(Match.tag("ContractViolationError", ({ message }) => Effect.logError("contract violation", message).pipe(Effect.as(c.json({
|
|
9834
|
+
type: "/problems/internal-server-error",
|
|
9835
|
+
title: "Internal Server Error",
|
|
9836
|
+
status: 500,
|
|
9837
|
+
detail: "An unexpected error occurred.",
|
|
9838
|
+
instance: c.req.path
|
|
9839
|
+
}, 500, { "Content-Type": "application/problem+json" })))), Match.exhaustive)
|
|
9840
|
+
}));
|
|
9841
|
+
};
|
|
9842
|
+
const postDbExplainRouteHandler = (c) => {
|
|
9843
|
+
const data = c.req.valid("json");
|
|
9844
|
+
return studioRuntime().runPromise(Effect.matchEffect(explainSql({
|
|
9845
|
+
sql: data.sql,
|
|
9846
|
+
params: data.params ?? []
|
|
9847
|
+
}), {
|
|
5445
9848
|
onSuccess: (value) => Effect.succeed(c.json(value, 200)),
|
|
5446
|
-
onFailure: (error) => Match.value(error).pipe(Match.tag("
|
|
9849
|
+
onFailure: (error) => Match.value(error).pipe(Match.tag("InvalidInputError", ({ field, message }) => Effect.succeed(c.json({
|
|
9850
|
+
type: "/problems/validation-failed",
|
|
9851
|
+
title: "Validation Failed",
|
|
9852
|
+
status: 422,
|
|
9853
|
+
detail: `${field} ${message}.`,
|
|
9854
|
+
instance: c.req.path,
|
|
9855
|
+
errors: [{
|
|
9856
|
+
field,
|
|
9857
|
+
message
|
|
9858
|
+
}]
|
|
9859
|
+
}, 422, { "Content-Type": "application/problem+json" }))), Match.tag("DatabaseUnavailableError", ({ reason }) => Effect.succeed(c.json({
|
|
5447
9860
|
type: "/problems/service-unavailable",
|
|
5448
9861
|
title: "Service Unavailable",
|
|
5449
9862
|
status: 503,
|
|
@@ -5650,7 +10063,7 @@ const getDocsRouteHandler = (c) => studioRuntime().runPromise(Effect.matchEffect
|
|
|
5650
10063
|
instance: c.req.path
|
|
5651
10064
|
}, 500, { "Content-Type": "application/problem+json" })))), Match.exhaustive)
|
|
5652
10065
|
}));
|
|
5653
|
-
const api = new OpenAPIHono().openapi(getSchemaRoute, getSchemaRouteHandler).openapi(postSchemaReloadRoute, postSchemaReloadRouteHandler).openapi(putSchemaFilesRoute, putSchemaFilesRouteHandler).openapi(getSchemaEventsRoute, getSchemaEventsRouteHandler).openapi(getDbRoute, getDbRouteHandler).openapi(getDbCountsRoute, getDbCountsRouteHandler).openapi(getDbRowsModelNameRoute, getDbRowsModelNameRouteHandler).openapi(postDbRowsModelNameRoute, postDbRowsModelNameRouteHandler).openapi(patchDbRowsModelNameRoute, patchDbRowsModelNameRouteHandler).openapi(deleteDbRowsModelNameRoute, deleteDbRowsModelNameRouteHandler).openapi(postDbSqlRoute, postDbSqlRouteHandler).openapi(postPrismaFormatRoute, postPrismaFormatRouteHandler).openapi(postPrismaLintRoute, postPrismaLintRouteHandler).openapi(postPrismaSymbolsRoute, postPrismaSymbolsRouteHandler).openapi(postPrismaCompleteRoute, postPrismaCompleteRouteHandler).openapi(postPrismaHoverRoute, postPrismaHoverRouteHandler).openapi(postPrismaDefinitionRoute, postPrismaDefinitionRouteHandler).openapi(postPrismaReferencesRoute, postPrismaReferencesRouteHandler).openapi(postPrismaRenameRoute, postPrismaRenameRouteHandler).openapi(postPrismaCodeActionsRoute, postPrismaCodeActionsRouteHandler).openapi(getDocsRoute, getDocsRouteHandler);
|
|
10066
|
+
const api = new OpenAPIHono().openapi(getSchemaRoute, getSchemaRouteHandler).openapi(postSchemaReloadRoute, postSchemaReloadRouteHandler).openapi(putSchemaFilesRoute, putSchemaFilesRouteHandler).openapi(getSchemaEventsRoute, getSchemaEventsRouteHandler).openapi(getDbRoute, getDbRouteHandler).openapi(getDbCountsRoute, getDbCountsRouteHandler).openapi(getDbRowsModelNameRoute, getDbRowsModelNameRouteHandler).openapi(postDbRowsModelNameRoute, postDbRowsModelNameRouteHandler).openapi(patchDbRowsModelNameRoute, patchDbRowsModelNameRouteHandler).openapi(deleteDbRowsModelNameRoute, deleteDbRowsModelNameRouteHandler).openapi(postDbSqlRoute, postDbSqlRouteHandler).openapi(postDbExplainRoute, postDbExplainRouteHandler).openapi(postDbAnalyzeRoute, postDbAnalyzeRouteHandler).openapi(postPrismaFormatRoute, postPrismaFormatRouteHandler).openapi(postPrismaLintRoute, postPrismaLintRouteHandler).openapi(postPrismaSymbolsRoute, postPrismaSymbolsRouteHandler).openapi(postPrismaCompleteRoute, postPrismaCompleteRouteHandler).openapi(postPrismaHoverRoute, postPrismaHoverRouteHandler).openapi(postPrismaDefinitionRoute, postPrismaDefinitionRouteHandler).openapi(postPrismaReferencesRoute, postPrismaReferencesRouteHandler).openapi(postPrismaRenameRoute, postPrismaRenameRouteHandler).openapi(postPrismaCodeActionsRoute, postPrismaCodeActionsRouteHandler).openapi(getDocsRoute, getDocsRouteHandler);
|
|
5654
10067
|
//#endregion
|
|
5655
10068
|
//#region src/studio/server/app.ts
|
|
5656
10069
|
const loopbackOnly = createMiddleware((c, next) => isLoopbackHostname(new URL(c.req.url).hostname) ? next() : Promise.resolve(c.text(FORBIDDEN_HOST_MESSAGE, 403)));
|