-
Notifications
You must be signed in to change notification settings - Fork 70
/
query.builder.ts
88 lines (77 loc) · 2.48 KB
/
query.builder.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
// Copyright (c) 2023 Sourcefuse Technologies
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
import {AnyObject, Model, ShortHandEqualType} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {Errors} from '../../const';
import {ColumnMap} from '../../types';
import {SearchQueryBuilder} from '../base';
export class PsqlQueryBuilder<T extends Model> extends SearchQueryBuilder<T> {
unionString = ' UNION ALL ';
schema: string;
_placeholderIndex = 1;
search(
model: typeof Model,
columns: Array<keyof T> | ColumnMap<T>,
ignoreColumns: (keyof T)[],
) {
const tableName = this.getTableName(model);
const sourceName = this.getModelName(model);
const schemaName = this.getSchemaName(model);
const {columnList, selectors} = this.getColumnListFromArrayOrMap(
model,
columns,
ignoreColumns,
);
if (!columnList) {
throw new HttpErrors.BadRequest(Errors.NO_COLUMNS_TO_MATCH);
}
const where = this.whereBuild(model, this.query.where?.[sourceName]);
const whereClause = [
`to_tsvector(${schemaName}.f_concat_ws(' ', ${columnList})) @@ to_tsquery($1)`,
];
if (where.sql) {
whereClause.push(where.sql);
}
let query = `SELECT ${selectors}, '${sourceName}' as source, ts_rank_cd(to_tsvector(${schemaName}.f_concat_ws(' ', ${columnList})), to_tsquery($1)) as rank
from ${schemaName}.${tableName} where ${whereClause.join(' AND ')}`;
query = query.replace('\n', '');
this.baseQueryList.push({
sql: query,
params: where.params,
});
}
paramString(index: number) {
return `$${index}`;
}
paramsBuild(param: string): AnyObject | Array<AnyObject | string> {
const params = this.baseQueryList.reduce(
(t: ShortHandEqualType[], v) => [...t, ...v.params],
[],
);
return [this._formatAndSanitize(param), ...params];
}
getModelName(model: typeof Model) {
const mappedName = this.modelNameMap.get(model.name);
return (
mappedName ??
model.definition?.settings?.postgresql?.table ??
model.modelName ??
model.name.toLowerCase()
);
}
getSchemaName(model: typeof Model) {
return (
this.schema ?? model.definition?.settings?.postgresql?.schema ?? `public`
);
}
_formatAndSanitize(param: string) {
return param
.replace(/[^A-Za-z\s0-9]/g, ' ')
.split(' ')
.filter(p => p)
.map(p => `${p}:*`)
.join('<->');
}
}