Reserve table names from the names the SQL compiler invents

This commit is contained in:
Effect Bot
2026-11-16 09:18:15 +00:00
parent fc9ec8c988
commit be557ebd22
2 changed files with 51 additions and 8 deletions
+26 -8
View File
@@ -15,8 +15,10 @@
* renders every column as text (temporal values as integers in their unit),
* and `decode` reads the rows back as columns of those types.
*
* Helper columns (the row key and the like) share one prefix, chosen per
* plan so that no column of the plan starts with it.
* The names the compiler invents (helper columns like the row key, the
* sources of tables) share one prefix, chosen per plan so that no name the
* plan supplies (its tables' and its columns') starts with it (see
* {@link inventor}).
*
* @internal
*/
@@ -37,7 +39,7 @@ import * as V from "./vector.ts"
interface Compiler {
/** The engine's frame for every node of the plan, on zero-row inputs. */
readonly frames: ReadonlyMap<Plan.Node, F.Frame>
/** A quoted helper column name, disjoint from the plan's column names. */
/** A quoted invented name, disjoint from the plan's table and column names (see {@link inventor}). */
readonly hidden: (name: string) => string
/** The quoted row key. */
readonly row: string
@@ -1158,6 +1160,26 @@ const source = (name: string, tables: ReadonlyArray<Plan.Table>): string => {
return `MATERIALIZED (SELECT ${columns.length === 0 ? "1" : list(columns)} FROM ${quote(name)})`
}
/**
* Quotes the names the compiler invents for the plan of `frames`, all with
* one prefix that no table or column name of the plan starts with, so that
* no invented name equals a name the plan supplies: a helper column can't
* hide a column, and a source can't shadow a table it reads (a common table
* expression shadows the table of its name in every `FROM` in its scope,
* the other sources' included; qualifying the tables' names with their
* schema is no way out, as the schema isn't known). Names PostgreSQL
* truncates keep their start, so this holds for them too.
*/
const inventor = (frames: ReadonlyMap<Plan.Node, F.Frame>): (name: string) => string => {
const names = [...frames].flatMap(([node, frame]) => [
...(node._tag === "Table" ? [node.name] : []),
...frame.columns.map((col) => col.name)
])
let prefix = "__"
while (names.some((name) => name.startsWith(prefix))) prefix += "_"
return (name) => quote(prefix + name)
}
/** One SQL query whose first row holds the values of checks. */
interface Checked {
readonly sql: string
@@ -1189,11 +1211,7 @@ export interface Compiled {
export const compile = (plan: Plan.Node): Compiled => {
const frames = new Map<Plan.Node, F.Frame>()
const result = typed(plan, frames)
const used = new Set<string>()
for (const frame of frames.values()) for (const col of frame.columns) used.add(col.name)
let prefix = "__"
while ([...used].some((name) => name.startsWith(prefix))) prefix += "_"
const hidden = (name: string) => quote(prefix + name)
const hidden = inventor(frames)
const tables = [...frames].flatMap(([node, frame]) =>
node._tag === "Table" ? [{ node, checks: rowChecks(node, frame) }] : []
)
@@ -37,6 +37,9 @@ const Setup = Layer.effectDiscard(
yield* sql`DROP TABLE IF EXISTS sales`
yield* sql`DROP TABLE IF EXISTS regions`
yield* sql`DROP TABLE IF EXISTS contract`
yield* sql`DROP TABLE IF EXISTS second`
yield* sql`DROP TABLE IF EXISTS "__table0"`
yield* sql`DROP TABLE IF EXISTS "__table1"`
yield* sql`CREATE TABLE sales (id DOUBLE PRECISION, region TEXT, units DOUBLE PRECISION, price DOUBLE PRECISION, at TIMESTAMP)`
yield* sql`CREATE TABLE regions (region TEXT, manager TEXT)`
for (const s of sales) {
@@ -47,6 +50,13 @@ const Setup = Layer.effectDiscard(
for (const r of regions) yield* sql`INSERT INTO regions VALUES (${r.region}, ${r.manager})`
yield* sql`CREATE TABLE contract (s TEXT, n DOUBLE PRECISION)`
yield* sql`INSERT INTO contract VALUES ('bad', NULL), ('good', 1)`
// Tables named like the sources of other tables.
yield* sql`CREATE TABLE second (s TEXT)`
yield* sql`INSERT INTO second VALUES ('good')`
yield* sql`CREATE TABLE "__table0" (s TEXT)`
yield* sql`INSERT INTO "__table0" VALUES ('bad')`
yield* sql`CREATE TABLE "__table1" (s TEXT)`
yield* sql`INSERT INTO "__table1" VALUES ('bad')`
yield* sql`DROP TABLE IF EXISTS odd`
yield* sql`CREATE TABLE odd (nil INTEGER, nothing INTEGER, at TIMESTAMPTZ, far TIMESTAMP, months INTERVAL, forever TIMESTAMP, endless DATE)`
yield* sql`INSERT INTO odd VALUES (42, NULL, '2024-01-01 00:30:00+00', '290000-01-01', '1 month', 'infinity', 'infinity')`
@@ -614,6 +624,21 @@ describe("effect/dataframe on PostgreSQL (PGlite)", { concurrent: false }, () =>
])
}))
it.effect("tables are read from their names, whatever the compiler names", () =>
Effect.gen(function*() {
const s = (name: string) => Query.table(name, Schema.Struct({ s: Schema.String }))
assert.deepStrictEqual(
yield* rowsOnSql(Query.concat([s("contract"), s("__table0"), s("second"), s("__table1")])),
[{ s: "bad" }, { s: "good" }, { s: "bad" }, { s: "good" }, { s: "bad" }]
)
const error = yield* Effect.flip(onSql(Query.concat([
s("contract").pipe(Query.filter((c) => Expr.eq(c.s, "good"))),
s("second"),
Query.table("__table1", Schema.Struct({ s: Schema.Literal("good") }))
])))
assert.strictEqual(error.message, `column "s" has values its schema rejects`)
}))
it.effect("timestamps with time zones are UTC, whatever the session's time zone", () =>
Effect.gen(function*() {
const sql = yield* SqlClient