deno.land / x / pg_mem@2.8.1 / transforms / 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
import { _ISelection, _IIndex, IValue, setId, getId, _IType, _Transaction, _Column, _ITable, _Explainer, _SelectExplanation, IndexKey, _IndexExplanation, IndexExpression, IndexOp, Stats, _IAlias } from '../interfaces-private.ts';import { QueryError, ColumnNotFound, AmbiguousColumn, nil } from '../interfaces.ts';import { buildValue } from '../parser/expression-builder.ts';import { Evaluator } from '../evaluator.ts';import { TransformBase } from './transform-base.ts';import { SelectedColumn, Expr, astVisitor, ExprRef } from 'https://deno.land/x/pgsql_ast_parser@12.0.1/mod.ts';import { aggregationFunctions, buildGroupBy } from './aggregation.ts';
import { asSingleQName, colByName, colToStr, isSelectAllArgList, suggestColumnName } from '../utils.ts';import { withSelection } from '../parser/context.ts';

export function buildSelection(on: _ISelection, select: SelectedColumn[] | nil) { select = select ?? [];
// if this is a "SELECT *" => just ignore if (isSelectAllArgList(select.map(x => x.expr))) { if (!on.columns.length) { throw new QueryError('SELECT * with no tables specified is not valid'); } return on; }
// if there is any aggregation function // check if there is any aggregation for (const col of select ?? []) { if (!on.isAggregation() && 'expr' in col && hasAggreg(col.expr)) { // yea, there is an aggregation somewhere in selection return buildGroupBy(on, []).select(select); } }
return new Selection(on, select);}

function hasAggreg(e: Expr) { let has = false; astVisitor(visitor => ({ call: expr => { const nm = asSingleQName(expr.function, 'pg_catalog'); if (nm && aggregationFunctions.has(nm)) { // yea, this is an aggregation has = true; return; } visitor.super().call(expr); } })).expr(e); return has}


export function columnEvaluator(this: void, on: _ISelection, id: string, type: _IType) { if (!id) { throw new Error('Invalid column id'); } const ret = new Evaluator( type , id , id , null , raw => raw[id] , { isColumnOf: on, }); return ret;}
function* buildCols(this: void, base: _ISelection, columns: (SelectedColumn | CustomAlias)[]): Iterable<CustomAlias> { for (const s of columns) { if ('val' in s) { if (s.val.origin !== base) { throw new Error('Corrupted selection'); } yield s; continue; } if (s.expr.type === 'ref' && s.expr.name === '*') { // handle select "*" if (s.alias) { throw new QueryError('Cannot alias *'); } let of: _IAlias = base; const alias = s.expr.table; if (alias) { // handle select "x.*" const sub = base.selectAlias(alias.name); if (!sub) { throw new QueryError(`Unknown alias "${alias.name}"`); } of = sub; }
for (const val of of.listColumns()) { yield { val }; }
} else { const val = buildValue(s.expr); yield { val, as: s.alias?.name, expr: s.expr }; } }}
export interface CustomAlias { val: IValue; as?: string; expr?: Expr}
export class Selection<T = any> extends TransformBase<T> implements _ISelection<T> {
private columnIds: string[] = []; private columnsOrigin: IValue[] = []; private columnMapping = new Map<IValue, IValue>(); private indexCache = new Map<IValue, _IIndex>(); private columnsById = new Map<string, IValue[]>(); private symbol = Symbol();
readonly columns: IValue[] = [];
isAggregation() { return false; }

constructor(base: _ISelection, _columns: (SelectedColumn | CustomAlias)[]) { super(base);
// build non-conflicting column ids based on existing ones const columns = withSelection(base, () => [...buildCols(base, _columns)]); this.columnIds = columns.map(x => x.as ?? x.val.id!);
// build column ids let anonymousBases = new Map<string, number>(); for (let i = 0; i < this.columnIds.length; i++) { if (!this.columnIds[i]) { let id = suggestColumnName(columns[i].expr) ?? 'column';
// check no collision with an existing column let cnt = anonymousBases.get(id); this.columnIds[i] = id + (cnt ? cnt : ''); anonymousBases.set(id, (cnt ?? 0) + 1); } }

// build columns to select for (let i = 0; i < columns.length; i++) { this.refColumn(columns[i].val, this.columnIds[i]); }

// ONLY ONCE COLUMNS HAVE BEEN REFERENCED BY ID, // rename ids for columns which have the same id // this allows yielding ambiguous columns data const has = new Map<string, number>(); for (let i = 0; i < columns.length; i++) { const orig = this.columnIds[i]; const oi = has.get(orig); if (typeof oi !== 'number') { has.set(orig, i); continue; } let ret: string = orig; let k = 0; do { ret = orig + (++k); } while (this.columnIds.includes(ret)); this.columnIds[i] = ret; has.set(ret, i); } }
private refColumn(fromCol: IValue, alias: string) { const col = columnEvaluator(this, alias, fromCol.type); this.columns.push(col); this.columnMapping.set(col, fromCol); this.columnsOrigin.push(fromCol); if (!col.id) { return; } let ci = this.columnsById.get(col.id); if (!ci) { this.columnsById.set(col.id, ci = []); } ci.push(col); }

stats(t: _Transaction): Stats | null { return this.base.stats(t); }

*enumerate(t: _Transaction): Iterable<T> { for (const item of this.base.enumerate(t)) { yield this.build(item, t); } }
build(item: any, t: _Transaction): T { const ret: any = {}; setId(ret, getId(item)); ret[this.symbol] = this.symbol; for (let i = 0; i < this.columns.length; i++) { const col = this.columnsOrigin[i]; ret[this.columnIds[i]] = col.get(item, t) ?? null; } return ret as any; }
hasItem(value: T, t: _Transaction): boolean { return (value as any)[this.symbol] === this.symbol; }
getColumn(column: string | ExprRef): IValue; getColumn(column: string | ExprRef, nullIfNotFound?: boolean): IValue | nil; getColumn(column: string | ExprRef, nullIfNotFound?: boolean): IValue | nil { const ret = colByName(this.columnsById, column, true); if (!ret?.length) { if (nullIfNotFound) { return null; } throw new ColumnNotFound(colToStr(column)); } if (ret.length !== 1) { throw new AmbiguousColumn(colToStr(column)); } return ret[0]; }
getIndex(val: IValue): _IIndex | nil { if (this.indexCache.has(val)) { return this.indexCache.get(val); } const mapped = this.columnMapping.get(val); const originIndex = this.base.getIndex(mapped!); const ret = originIndex && new SelectionIndex(this, originIndex); this.indexCache.set(val, ret!); return ret; }
explain(e: _Explainer): _SelectExplanation { return { id: e.idFor(this), _: 'map', of: this.base.explain(e), select: this.columnIds.map((x, i) => ({ what: this.columnsOrigin[i].explain(e), as: x })), }; }}

export class SelectionIndex<T> implements _IIndex<T> { constructor(readonly owner: Selection<T>, private base: _IIndex) { }
stats(t: _Transaction, key?: IndexKey) { return this.base.stats(t, key); }
iterateKeys(t: _Transaction) { return this.base.iterateKeys(t); }
get expressions(): IndexExpression[] { return this.base.expressions; }
entropy(op: IndexOp): number { // same as source return this.base.entropy(op); }
eqFirst(rawKey: IndexKey, t: _Transaction) { return this.base.eqFirst(rawKey, t); }
*enumerate(op: IndexOp): Iterable<T> { for (const i of this.base.enumerate(op)) { yield this.owner.build(i, op.t); } }

explain(e: _Explainer): _IndexExplanation { return { _: 'indexMap', of: this.base.explain(e), } }}
pg_mem

Version Info

Tagged at
4 months ago