/
selection.ts
300 lines (261 loc) · 9.85 KB
/
selection.ts
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
import { defineProperty, Dict, filterKeys, valueMap } from 'cosmokit'
import { Driver } from './driver.ts'
import { Eval, executeEval } from './eval.ts'
import { Model } from './model.ts'
import { Query } from './query.ts'
import { FlatKeys, FlatPick, Flatten, Keys, randomId, Row } from './utils.ts'
import { Type } from './type.ts'
declare module './eval.ts' {
export namespace Eval {
export interface Static {
exec<S, T>(value: Executable<S, T>): Expr<T>
}
}
}
export type Direction = 'asc' | 'desc'
export interface Modifier {
limit: number
offset: number
sort: [Eval.Expr, Direction][]
group?: string[]
having: Eval.Expr<boolean>
fields?: Dict<Eval.Expr>
optional: Dict<boolean>
}
namespace Executable {
export type Action = 'get' | 'set' | 'remove' | 'create' | 'upsert' | 'eval'
export interface Payload {
type: Action
table: string | Selection | Dict<Selection.Immutable>
ref: string
query: Query.Expr
args: any[]
}
}
const createRow = (ref: string, expr = {}, prefix = '', model?: Model) => new Proxy(expr, {
get(target, key) {
if (key === '$prefix') return prefix
if (key === '$model') return model
if (typeof key === 'symbol' || key in target || key.startsWith('$')) return Reflect.get(target, key)
let type: Type
const field = model?.fields[prefix + key as string]
if (Type.getInner(expr?.[Type.kType], key)) {
// type may conatins object layout
type = Type.getInner(expr?.[Type.kType], key)!
} else if (field) {
type = Type.fromField(field)
} else if (Object.keys(model?.fields!).some(k => k.startsWith(`${prefix}${key}.`))) {
type = Type.Object(Object.fromEntries(Object.entries(model?.fields!)
.filter(([k]) => k.startsWith(`${prefix}${key}`))
.map(([k, field]) => [k.slice(prefix.length + key.length + 1), Type.fromField(field!)])))
} else {
// unknown field inside json
type = Type.fromField('expr')
}
const row = createRow(ref, Eval('', [ref, `${prefix}${key}`], type), `${prefix}${key}.`, model)
if (Object.keys(model?.fields!).some(k => k.startsWith(`${prefix}${key}.`))) {
return createRow(ref, Eval.object(row), `${prefix}${key}.`, model)
} else {
return row
}
},
})
interface Executable extends Executable.Payload {}
class Executable<S = any, T = any> {
public readonly row!: Row<S>
public readonly model!: Model
public readonly driver!: Driver
constructor(driver: Driver, payload: Executable.Payload) {
Object.assign(this, payload)
defineProperty(this, 'driver', driver)
defineProperty(this, 'model', driver.model(this.table))
defineProperty(this, 'row', createRow(this.ref, {}, '', this.model))
}
protected resolveQuery(query?: Query<S>): Query.Expr<S>
protected resolveQuery(query: Query<S> = {}): any {
if (typeof query === 'function') return { $expr: query(this.row) }
if (Array.isArray(query) || query instanceof RegExp || ['string', 'number'].includes(typeof query)) {
const { primary } = this.model
if (Array.isArray(primary)) {
throw new TypeError('invalid shorthand for composite primary key')
}
return { [primary]: query }
}
return query
}
protected resolveField(field: FieldLike<S>): Eval.Expr {
if (typeof field === 'string') {
return this.row[field]
} else if (typeof field === 'function') {
return field(this.row)
} else {
throw new TypeError('invalid field definition')
}
}
protected resolveFields(fields: string | string[] | Dict<FieldLike<S>>) {
if (typeof fields === 'string') fields = [fields]
if (Array.isArray(fields)) {
const modelFields = Object.keys(this.model.fields)
const entries = fields.flatMap((key) => {
if (this.model.fields[key]) return [[key, this.row[key]]]
else if (modelFields.some(path => path.startsWith(key + '.'))) {
return modelFields.filter(path => path.startsWith(key + '.')).map(path => [path, this.row[path]])
}
return [[key, key.split('.').reduce((row, k) => row[k], this.row)]]
})
return Object.fromEntries(entries)
} else {
return valueMap(fields, field => this.resolveField(field))
}
}
async execute(): Promise<T> {
await this.driver.database.prepared()
await this.driver._ensureSession()
return this.driver[this.type as any](this, ...this.args)
}
}
type FieldLike<S = any> = FlatKeys<S> | Selection.Callback<S>
type FieldType<S, T extends FieldLike<S>> =
| T extends FlatKeys<S> ? Flatten<S>[T]
: T extends Selection.Callback<S> ? Eval<ReturnType<T>>
: never
type FieldMap<S, M extends Dict<FieldLike<S>>> = {
[K in keyof M]: FieldType<S, M[K]>
}
export namespace Selection {
export type Callback<S = any, T = any, A extends boolean = boolean> = (row: Row<S>) => Eval.Expr<T, A>
export interface Immutable extends Executable, Executable.Payload {
tables: Dict<Model>
}
export interface Mutable extends Executable, Executable.Payload {
tables: Dict<Model>
table: string
}
}
export interface Selection extends Executable.Payload {
args: [Modifier]
}
export class Selection<S = any> extends Executable<S, S[]> {
public tables: Dict<Model> = {}
constructor(driver: Driver<any>, table: string | Selection | Dict<Selection.Immutable>, query?: Query) {
super(driver, {
type: 'get',
ref: randomId(),
table,
query: null as never,
args: [{ sort: [], limit: Infinity, offset: 0, group: undefined, having: Eval.and(), optional: {} }],
})
this.tables[this.ref] = this.model
this.query = this.resolveQuery(query)
if (typeof table !== 'string') {
Object.assign(this.tables, table.tables)
}
}
where(query: Query<S>) {
this.query.$and ||= []
this.query.$and.push(this.resolveQuery(query))
return this
}
limit(limit: number): this
limit(offset: number, limit: number): this
limit(...args: [number] | [number, number]) {
if (args.length > 1) this.offset(args.shift()!)
this.args[0].limit = args[0]
return this
}
offset(offset: number) {
this.args[0].offset = offset
return this
}
orderBy(field: FieldLike<S>, direction: Direction = 'asc') {
this.args[0].sort.push([this.resolveField(field), direction])
return this
}
groupBy<K extends FlatKeys<S>>(fields: K | readonly K[], query?: Selection.Callback<S, boolean>): Selection<FlatPick<S, K>>
groupBy<K extends FlatKeys<S>, U extends Dict<FieldLike<S>>>(
fields: K | K[],
extra?: U,
query?: Selection.Callback<S, boolean>,
): Selection<FlatPick<S, K> & FieldMap<S, U>>
groupBy<K extends Dict<FieldLike<S>>>(fields: K, query?: Selection.Callback<S, boolean>): Selection<FieldMap<S, K>>
groupBy<K extends Dict<FieldLike<S>>, U extends Dict<FieldLike<S>>>(
fields: K,
extra?: U,
query?: Selection.Callback<S, boolean>,
): Selection<FieldMap<S, K & U>>
groupBy(fields: any, ...args: any[]) {
this.args[0].fields = this.resolveFields(fields)
this.args[0].group = Object.keys(this.args[0].fields!)
const extra = typeof args[0] === 'function' ? undefined : args.shift()
Object.assign(this.args[0].fields!, this.resolveFields(extra || {}))
if (args[0]) this.having(args[0])
return new Selection(this.driver, this)
}
having(query: Selection.Callback<S, boolean>) {
this.args[0].having['$and'].push(this.resolveField(query))
return this
}
project<K extends FlatKeys<S>>(fields: K | readonly K[]): Selection<FlatPick<S, K>>
project<U extends Dict<FieldLike<S>>>(fields: U): Selection<FieldMap<S, U>>
project(fields: Keys<S>[] | Dict<FieldLike<S>>) {
this.args[0].fields = this.resolveFields(fields)
return new Selection(this.driver, this)
}
_action(type: Executable.Action, ...args: any[]) {
return new Executable(this.driver, { ...this, type, args })
}
evaluate<T>(callback: Selection.Callback<S, T, true>): Eval.Expr<T, true>
evaluate<K extends Keys<S>>(field: K): Eval.Expr<S[K][], boolean>
evaluate(): Eval.Expr<S[], boolean>
evaluate(callback?: any): any {
const selection = new Selection(this.driver, this)
if (!callback) callback = (row: any) => Eval.array(Eval.object(row))
const expr = this.resolveField(callback)
if (expr['$']) defineProperty(expr, Type.kType, Type.Array(Type.fromTerm(expr)))
return Eval.exec(selection._action('eval', expr))
}
execute<K extends FlatKeys<S> = any>(cursor?: Driver.Cursor<K>): Promise<Extract<FlatPick<S, K>, S>[]>
execute<T>(callback: Selection.Callback<S, T, true>): Promise<T>
async execute(cursor?: any) {
if (typeof cursor === 'function') {
const selection = new Selection(this.driver, this)
return selection._action('eval', this.resolveField(cursor)).execute()
}
if (Array.isArray(cursor)) {
cursor = { fields: cursor }
} else if (!cursor) {
cursor = {}
}
if (cursor.fields) this.project(cursor.fields)
if (cursor.limit !== undefined) this.limit(cursor.limit)
if (cursor.offset !== undefined) this.offset(cursor.offset)
if (cursor.sort) {
for (const field in cursor.sort) {
this.orderBy(field as any, cursor.sort[field])
}
}
const rows = await super.execute()
if (!cursor.fields) return rows
return rows.map((row) => {
return filterKeys(row as any, key => {
return (cursor.fields as string[]).some(k => k === key || k.startsWith(`${key}.`))
})
})
}
}
export function executeSort(data: any[], modifier: Modifier, name: string) {
const { limit, offset, sort } = modifier
// step 1: sort data
data.sort((a, b) => {
for (const [field, direction] of sort) {
const sign = direction === 'asc' ? 1 : -1
const x = executeEval({ [name]: a, _: a }, field)
const y = executeEval({ [name]: b, _: b }, field)
if (x < y) return -sign
if (x > y) return sign
}
return 0
})
// step 2: truncate data
return data.slice(offset, offset + limit)
}