Repository navigation
Expand file tree
/
Copy pathsql.ts
More file actions
186 lines (172 loc) · 7.73 KB
/
Copy pathsql.ts
File metadata and controls
186 lines (172 loc) · 7.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// `Db.sql`: a statement written as a template, every `${value}` bound.
//
// The template does not know its database, so it keeps the text and the values
// apart and is rendered by the `Database` that runs it: `$1, $2, ...` for
// Postgres, an escaped literal for ClickHouse, which takes no bound values over
// HTTP. Nothing in a value can become SQL.
import { Effect, Redacted } from "effect"
import { checkedLiteral, type Dialect } from "../ch/dialect"
import { QueryBuilderError } from "../ch/errors"
import { collectFailures, fail } from "../ch/failure"
import { DatabaseError } from "./errors"
const SqlTemplateTag = "@maple-dev/effect-orm/SqlTemplate"
const IdentifierTag = "@maple-dev/effect-orm/SqlIdentifier"
const RawTag = "@maple-dev/effect-orm/SqlTemplateRaw"
/** SQL text spliced as-is. From `sql.raw`. */
export interface SqlRawText {
readonly _tag: typeof RawTag
readonly sql: string
}
/** A name written as an identifier, quoted by the dialect. From `sql.identifier`. */
export interface SqlIdentifier {
readonly _tag: typeof IdentifierTag
readonly name: string
}
/** A statement from `sql\`...\``: text and values, rendered per dialect when it runs. */
export interface SqlTemplate {
readonly _tag: typeof SqlTemplateTag
readonly strings: ReadonlyArray<string>
readonly values: ReadonlyArray<unknown>
}
// The templates, identifiers and raw text `sql` made. Recognised by identity,
// not by `_tag`: a `_tag` survives JSON, so a value parsed from a request body
// could otherwise pass for a template or raw text and be spliced as SQL.
const minted = new WeakSet<object>()
const mint = <A extends object>(value: A): A => {
minted.add(value)
return value
}
// `join` of no values, which would write `IN ()`: refused when rendered.
const emptyJoins = new WeakSet<object>()
/**
* A statement with every `${value}` bound, never spliced into the text. A
* `sql\`...\`` inside another is spliced as SQL, so statements compose.
*
* ```ts
* Db.execute(Db.sql`UPDATE api_keys SET revoked = true WHERE family = ${family}`)
* ```
*/
export const sql: {
(strings: TemplateStringsArray, ...values: ReadonlyArray<unknown>): SqlTemplate
/** A table or column name, quoted by the dialect: `sql\`SELECT * FROM ${sql.identifier(table)}\``. */
readonly identifier: (name: string) => SqlIdentifier
/**
* Values joined by `separator` (default `sql\`, \``): a plain value is bound, a
* `sql\`...\`` spliced. `sql\`id IN (${sql.join(ids)})\`` binds one value per id.
*/
readonly join: (values: ReadonlyArray<unknown>, separator?: SqlTemplate) => SqlTemplate
/** SQL text spliced as-is. Only for text under your control, never for input. */
readonly raw: (text: string) => SqlRawText
/** A template that writes nothing, for an optional part: `${cond ? sql\`AND x\` : sql.empty}`. */
readonly empty: SqlTemplate
} = Object.assign(
(strings: TemplateStringsArray, ...values: ReadonlyArray<unknown>): SqlTemplate =>
mint({ _tag: SqlTemplateTag, strings: [...strings], values }),
{
identifier: (name: string): SqlIdentifier => mint({ _tag: IdentifierTag, name }),
join: (values: ReadonlyArray<unknown>, separator?: SqlTemplate): SqlTemplate => {
const sep: SqlTemplate = separator ?? mint({ _tag: SqlTemplateTag, strings: [", "], values: [] })
const interleaved = values.flatMap((value, index) => (index === 0 ? [value] : [sep, value]))
const joined = mint({
_tag: SqlTemplateTag,
strings: Array.from({ length: interleaved.length + 1 }, () => ""),
values: interleaved,
} satisfies SqlTemplate)
if (values.length === 0) emptyJoins.add(joined)
return joined
},
raw: (text: string): SqlRawText => mint({ _tag: RawTag, sql: text }),
empty: mint({ _tag: SqlTemplateTag, strings: [""], values: [] } satisfies SqlTemplate),
},
)
const isRaw = (value: unknown): value is SqlRawText =>
typeof value === "object" && value !== null && minted.has(value) && "_tag" in value && value._tag === RawTag
const isIdentifier = (value: unknown): value is SqlIdentifier =>
typeof value === "object" && value !== null && minted.has(value) && "_tag" in value && value._tag === IdentifierTag
/** Whether `value` is a template `sql` made: by identity, so JSON cannot forge one. */
export const isSqlTemplate = (value: unknown): value is SqlTemplate =>
typeof value === "object" && value !== null && minted.has(value) && "_tag" in value && value._tag === SqlTemplateTag
// ClickHouse writes identifiers bare, so only plain names are accepted, for
// every dialect: letters, digits and `_`, dotted for `schema.table`.
const PLAIN_NAME = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/
const identifier = (dialect: Dialect, name: string): string => {
if (!PLAIN_NAME.test(name)) {
return fail(
new QueryBuilderError({
code: "InvalidLiteral",
message: `sql.identifier: ${JSON.stringify(name)} is not a plain identifier (letters, digits, _, dotted for schema.table)`,
}),
"",
)
}
return name
.split(".")
.map((segment) => dialect.quoteIdent(segment))
.join(".")
}
/** A rendered template: text with the dialect's placeholders, and the values they bind. */
export interface RenderedTemplate {
readonly sql: string
readonly parameters: ReadonlyArray<unknown>
/** The indexes in `parameters` of the values given as `Redacted`. Absent when there are none. */
readonly sensitiveParameters?: ReadonlyArray<number>
}
/**
* Text with the dialect's placeholders, and the values they bind. A `Redacted`
* value binds as its plain value and is marked in `sensitiveParameters`. A
* dialect that writes values into the text (ClickHouse) refuses it: the value
* would be in the statement text, which spans and errors carry.
*/
export const renderTemplate = (template: SqlTemplate, dialect: Dialect): Effect.Effect<RenderedTemplate, DatabaseError> =>
Effect.suspend(() => {
const { value, failures } = collectFailures((): RenderedTemplate => {
const parameters: Array<unknown> = []
const sensitiveParameters: Array<number> = []
const render = (current: SqlTemplate): string => {
if (emptyJoins.has(current)) {
return fail(new QueryBuilderError({ code: "InvalidArguments", message: "sql.join: no values to join" }), "")
}
return current.strings.reduce((text, part, index) => {
if (index === 0) return part
const value = current.values[index - 1]
if (isSqlTemplate(value)) return text + render(value) + part
if (isIdentifier(value)) return text + identifier(dialect, value.name) + part
if (isRaw(value)) return text + value.sql + part
if (dialect.params._tag === "inline") {
if (Redacted.isRedacted(value)) {
return fail(
new QueryBuilderError({
code: "InvalidLiteral",
message: `a Redacted sql\`\` value would be written into the ${dialect.name} statement text; ${dialect.name} binds no values here`,
}),
"",
)
}
// A negative literal after `-` would write `--`, which comments out the line.
const literal = checkedLiteral(dialect, value, "a sql`` value")
return text + (literal.startsWith("-") ? `(${literal})` : literal) + part
}
if (Redacted.isRedacted(value)) {
sensitiveParameters.push(parameters.length)
parameters.push(Redacted.value(value))
} else {
parameters.push(value)
}
return text + dialect.params.placeholder(parameters.length, "") + part
}, "")
}
const sql = render(template)
return sensitiveParameters.length > 0 ? { sql, parameters, sensitiveParameters } : { sql, parameters }
})
const failure = failures[0]
return failure === undefined
? Effect.succeed(value)
: Effect.fail(
new DatabaseError({
message: failure.message,
sql: template.strings.join("?"),
reason: failure instanceof QueryBuilderError ? failure.code : "InvalidLiteral",
cause: failure,
}),
)
})