-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable.ts
More file actions
309 lines (262 loc) · 8.01 KB
/
Copy pathtable.ts
File metadata and controls
309 lines (262 loc) · 8.01 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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import { SQL } from "./sql"
import { isString } from "util"
export interface Collection<T extends ColumnType> {
type: T
collection: "array"
}
export const isCollection = (obj: any): obj is Collection<ColumnType> => obj.collection === "array"
export const PArray = <T extends ColumnType>(type: T): Collection<T> => ({ collection: "array", type })
export enum ColumnType {
BigInt = "bigint",
Boolean = "boolean",
Varchar = "varchar",
Date = "date",
Integer = "integer",
Text = "text",
Timestamp = "timestamp",
TimestampTZ = "timestamptz",
UUID = "uuid",
}
export enum ForeignKeyUpdateDeleteRule {
Cascade,
Restrict,
SetNull,
NoAction,
SetDefault,
}
export interface IReferenceConstraint {
targetTable: string
targetColumn: string
onUpdate?: ForeignKeyUpdateDeleteRule
onDelete?: ForeignKeyUpdateDeleteRule
}
export interface IReferenceConstraintInternal extends IReferenceConstraint {
column: string
}
export interface ICreateIndexStatement {
table?: string
column: string
unique: boolean
}
export interface Column {
type: ColumnType | Collection<ColumnType> | IColumnTypeJson<unknown>
primaryKey?: boolean
defaultValue?: unknown | SQLFunction
nullable?: boolean
autoIncrement?: boolean
foreignKeys?: IReferenceConstraint[]
createIndex?: boolean
unique?: boolean
}
export interface Columns {
[key: string]: Column
}
export interface IColumnTypeJson<Type> {
json: true
sample?: Type
}
export const JSONType = <Type>(): IColumnTypeJson<Type> => ({ json: true })
export const isJSONType = (type: any): type is IColumnTypeJson<unknown> =>
typeof type === "object" && type.json === true
type BigInteger = BigInt | number
export const TableSchema = <C extends Columns>(columns: C): { [key in keyof C]: C[key] } => columns
type ColumnBaseType<C extends Column> = C extends { type: ColumnType.BigInt }
? BigInteger
: C extends { type: ColumnType.Boolean }
? boolean
: C extends { type: ColumnType.Varchar }
? string
: C extends { type: ColumnType.Date }
? Date
: C extends { type: ColumnType.Integer }
? number
: C extends { type: ColumnType.Text }
? string
: C extends { type: ColumnType.Timestamp }
? Date
: C extends { type: ColumnType.TimestampTZ }
? Date
: C extends { type: ColumnType.UUID }
? string
: C extends { type: Collection<ColumnType.BigInt> }
? BigInteger[]
: C extends { type: Collection<ColumnType.Boolean> }
? boolean[]
: C extends { type: Collection<ColumnType.Varchar> }
? string[]
: C extends { type: Collection<ColumnType.Date> }
? Date[]
: C extends { type: Collection<ColumnType.Integer> }
? number[]
: C extends { type: Collection<ColumnType.Text> }
? string[]
: C extends { type: Collection<ColumnType.Timestamp> }
? Date[]
: C extends { type: Collection<ColumnType.TimestampTZ> }
? Date[]
: C extends { type: Collection<ColumnType.UUID> }
? string[]
: C extends { type: IColumnTypeJson<unknown> }
? Required<C["type"]>["sample"]
: unknown
type ColumnTypeFinal<C extends Column> = C extends { primaryKey: true }
? ColumnBaseType<C>
: C extends { defaultValue: {} }
? ColumnBaseType<C>
: C extends { nullable: false }
? ColumnBaseType<C>
: ColumnBaseType<C> | null
export type TableRecord<C extends Columns> = {
-readonly [key in keyof C]: ColumnTypeFinal<C[key]>
}
export enum NativeFunction {
Now = "now()",
}
interface SQLFunction {
func: NativeFunction | string
}
export const SQLFunc = (cqlFunction: NativeFunction | string): SQLFunction => ({
func: cqlFunction,
})
export const isSQLFunction = (value: any): value is SQLFunction => typeof value.func === "string"
type ColumnValuesBase<C extends Columns, Subset extends (keyof C)[]> = {
[key in keyof Subset]: TableRecord<C>[Extract<Subset[key], keyof C>] | SQLFunction | IWhereCondition
}
type ColumnValues<C extends Columns, Subset extends (keyof C)[]> = ColumnValuesBase<C, Subset>[keyof Subset][] &
ColumnValuesBase<C, Subset>
export type IQuery<C extends Columns> = {
sql: string
values?: unknown[]
columns?: C
}
export const Query = (sql: string, values?: unknown[]): IQuery<{}> => ({ sql, values })
export interface ISQLArg {
toString: () => string
}
export interface IWhereCondition {
type: "where_filter"
sql: string
}
export interface IWhereConditionColumned extends IWhereCondition, ISQLArg {
column: string
}
const isWhereCondition = (obj: any): obj is IWhereCondition => typeof obj === "object" && obj.type === "where_filter"
export const Where = {
isNull: (): IWhereCondition => ({
type: "where_filter",
sql: "IS NULL",
}),
isNotNull: (): IWhereCondition => ({
type: "where_filter",
sql: "IS NOT NULL",
}),
}
type NonEmpty<Type> = [Type, ...Type[]]
export type Keys<C extends Columns> = (keyof C)[] & (NonEmpty<keyof C> | [])
export interface ITable<C extends Columns> {
readonly name: string
create(): IQuery<{}>
insert<Subset extends Keys<C>>(subset: Subset): (values: ColumnValues<C, Subset>) => IQuery<{}>
insertFromObj<Subset extends TableRecord<C>>(obj: Partial<Subset>): IQuery<{}>
update<Subset extends Keys<C>, Where extends Keys<C>>(
subset: Subset,
where: Where,
): (subsetValues: ColumnValues<C, Subset>, whereValues: ColumnValues<C, Where>) => IQuery<{}>
selectAll<Subset extends Keys<C>>(subset: Subset | "*"): IQuery<Pick<C, Extract<Subset[number], string>>>
select<Subset extends Keys<C>, Where extends Keys<C>>(
subset: Subset | "*",
where: Where,
allowFiltering?: boolean,
): (conditions: ColumnValues<C, Where>) => IQuery<Pick<C, Extract<Subset[number], string>>>
drop(): IQuery<{}>
delete<Where extends Keys<C>>(where: Where): (conditions: ColumnValues<C, Where>) => IQuery<{}>
addColumns(columns: Columns): IQuery<{}>
dropColumns<Subset extends Keys<C>>(columns: Subset): IQuery<{}>
}
export const Table = <Tables extends { [key: string]: Columns }, Table extends Extract<keyof Tables, string>>(
tables: Tables,
table: Table,
): ITable<Tables[Table]> => {
const columns = tables[table]
return {
name: table,
create: () => ({
sql: SQL.createTable(table, columns),
}),
insert: (subset) => (values) => ({
sql: SQL.insert(table, subset.filter(isString)),
values,
}),
insertFromObj: (obj) => {
const subset = Object.keys(obj)
const values = Object.values(obj)
return {
sql: SQL.insert(table, subset),
values,
}
},
update: (subset, where) => (subsetValues, whereValues) => ({
sql: SQL.update(table, subset.filter(isString), where.filter(isString)),
values: [...subsetValues, ...whereValues],
}),
selectAll: (subset) => {
const sql = subset === "*" ? SQL.selectAll(table, subset) : SQL.selectAll(table, subset.filter(isString))
return {
sql,
}
},
select: (subset, where) => (values: any[]) => {
const whereSubstitutions = new Map<number, IWhereConditionColumned>()
const whereStringValued = where.filter(isString)
const finalValues = values.filter((value, idx) => {
if (isWhereCondition(value)) {
const whereCond = value
whereSubstitutions.set(idx, {
...whereCond,
column: whereStringValued[idx],
toString: () => `${whereStringValued[idx]} ${whereCond.sql}`,
})
return false
}
return true
})
const finalWhere = whereStringValued.map((where, idx) => {
if (whereSubstitutions.has(idx)) {
return whereSubstitutions.get(idx)!
}
return where
})
const sql =
subset === "*"
? SQL.select(table, subset, finalWhere)
: SQL.select(table, subset.filter(isString), finalWhere)
return {
sql,
values: finalValues,
}
},
drop: () => ({
sql: SQL.dropTable(table),
}),
delete: (where) => {
const sql = SQL.deleteEntry(table, where.filter(isString))
return (values) => ({
sql,
values,
})
},
addColumns: (columns) => ({
sql: SQL.addColumns(table, columns),
}),
dropColumns: (columnsToRemove) => {
const columnNames = columnsToRemove.filter(isString)
const columndObject: Columns = columnNames.reduce((obj, columnName) => {
const columnDefinition = columns[columnName]
return { ...obj, [columnName]: columnDefinition }
}, {})
return {
sql: SQL.dropColumns(table, columndObject),
}
},
}
}