Repository navigation
Expand file tree
/
Copy pathsql-query.ts
More file actions
102 lines (85 loc) · 2.5 KB
/
Copy pathsql-query.ts
File metadata and controls
102 lines (85 loc) · 2.5 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
import type { SqlFragment } from "./sql-fragment"
import { compile } from "./sql-fragment"
// Query structure
interface SqlJoin {
readonly type: "INNER" | "LEFT" | "CROSS"
readonly table: string
readonly alias: string
readonly on?: string
}
export interface SqlQuery {
/** `SELECT DISTINCT`. */
readonly distinct?: boolean
/** `SELECT DISTINCT ON (...)`; implies `distinct`. */
readonly distinctOn?: ReadonlyArray<SqlFragment>
readonly select: ReadonlyArray<SqlFragment>
/** Absent for a SELECT of values with no FROM. */
readonly from?: SqlFragment
readonly joins?: ReadonlyArray<SqlJoin>
readonly where: ReadonlyArray<SqlFragment>
readonly groupBy: ReadonlyArray<SqlFragment>
readonly having?: ReadonlyArray<SqlFragment>
readonly orderBy: ReadonlyArray<SqlFragment>
readonly limit?: SqlFragment
readonly offset?: SqlFragment
/** A locking clause written after OFFSET, e.g. `FOR UPDATE SKIP LOCKED`. */
readonly lock?: string
readonly format?: string
}
// Compiler
export function compileQuery(q: SqlQuery): string {
const parts: string[] = []
// SELECT
const selectCols = q.select.map(compile).filter(Boolean)
const distinct = q.distinctOn?.length
? ` DISTINCT ON (${q.distinctOn.map(compile).join(", ")})`
: q.distinct
? " DISTINCT"
: ""
parts.push(`SELECT${distinct}\n ${selectCols.join(",\n ")}`)
// FROM
if (q.from !== undefined) parts.push(`FROM ${compile(q.from)}`)
// JOINs
if (q.joins?.length) {
for (const j of q.joins) {
const joinType = j.type === "CROSS" ? "CROSS JOIN" : `${j.type} JOIN`
const onClause = j.on ? ` ON ${j.on}` : ""
parts.push(`${joinType} ${j.table} AS ${j.alias}${onClause}`)
}
}
// WHERE
const whereClauses = q.where.map(compile).filter(Boolean)
if (whereClauses.length > 0) {
parts.push(`WHERE ${whereClauses.join("\n AND ")}`)
}
// GROUP BY
if (q.groupBy.length > 0) {
parts.push(`GROUP BY ${q.groupBy.map(compile).join(", ")}`)
}
// HAVING
const havingClauses = (q.having ?? []).map(compile).filter(Boolean)
if (havingClauses.length > 0) {
parts.push(`HAVING ${havingClauses.join("\n AND ")}`)
}
// ORDER BY
if (q.orderBy.length > 0) {
parts.push(`ORDER BY ${q.orderBy.map(compile).join(", ")}`)
}
// LIMIT
if (q.limit) {
parts.push(`LIMIT ${compile(q.limit)}`)
}
// OFFSET
if (q.offset) {
parts.push(`OFFSET ${compile(q.offset)}`)
}
// Locking
if (q.lock) {
parts.push(q.lock)
}
// FORMAT
if (q.format) {
parts.push(`FORMAT ${q.format}`)
}
return parts.join("\n ")
}