-
Notifications
You must be signed in to change notification settings - Fork 0
/
SQLCon.ts
350 lines (319 loc) · 8.56 KB
/
SQLCon.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import Path from 'path';
import {
ConfigType,
CoreDBCon,
CoreEntity,
EntityConfig,
EProperties,
EUpDateProperties,
getColumnMeta,
ICoreCache,
ICoreClient,
ICoreKernel,
ICoreKernelModule,
ICorePresenter,
IDataBase,
QueryInterface,
RawQuery,
} from '@grandlinex/core';
import Database, { RunResult } from 'better-sqlite3';
import {
buildSearchQ,
mappingWithDataType,
objToTable,
rowToObj,
tableToObj,
} from '../util/index.js';
export type DbType = Database.Database;
export default class SQLCon<
K extends ICoreKernel<any> = ICoreKernel<any>,
T extends IDataBase<any, any> | null = any,
P extends ICoreClient | null = any,
C extends ICoreCache | null = any,
X extends ICorePresenter<any> | null = any
>
extends CoreDBCon<DbType, RunResult, K, T, P, C, X>
implements IDataBase<DbType, RunResult, K, T, P, C, X>
{
db: DbType | null;
private readonly path: string;
constructor(
module: ICoreKernelModule<any, any, any, any, any>,
dbversion: string
) {
super(dbversion, 'main', module);
const store = module.getKernel().getConfigStore();
const path = store.get('GLOBAL_PATH_DB');
if (!path) {
this.error('Cant get db path from store');
throw new Error('Cant get db path from store');
}
this.path = Path.join(path, `${module.getName()}.db`);
this.db = null;
}
async createEntity<E extends CoreEntity>(
config: EntityConfig<E>,
entity: EProperties<E>
): Promise<E> {
const [keys, values, params] = objToTable(entity, config);
const query: RawQuery = {
exec: `INSERT INTO ${this.schemaName}.${config.className}(${keys.join(
', '
)})
VALUES (${values.join(', ')})`,
param: params,
};
const res = await this.execScripts([query]);
if (!res || !res[0]) {
throw this.lError('Cant Create entity');
}
return entity as E;
}
async updateEntity<E extends CoreEntity>(
config: EntityConfig<E>,
e_id: string,
entity: EUpDateProperties<E>
): Promise<boolean> {
const [, values, params] = objToTable(entity, config, true);
const result = await this.execScripts([
{
exec: `UPDATE ${this.schemaName}.${config.className}
SET ${values.join(', ')}
WHERE e_id = ?;`,
param: [...params, e_id],
},
]);
return result[0] !== null;
}
async getEntityById<E extends CoreEntity>(
config: EntityConfig<E>,
id: string
): Promise<E | null> {
const query = this.db?.prepare(
`SELECT *
FROM ${this.schemaName}.${config.className}
WHERE e_id = ?;`
);
const res = query?.get([id]);
if (res) {
return rowToObj<E>(config, res);
}
return null;
}
async findEntity<E extends CoreEntity>(
config: EntityConfig<E>,
search: { [D in keyof E]?: E[D] | undefined }
): Promise<E | null> {
let searchQ = '';
const param: any[] = [];
searchQ = buildSearchQ<E>(config, search, param, searchQ);
const query = this.db?.prepare(
`SELECT *
FROM ${this.schemaName}.${config.className} ${searchQ};`
);
const res = query?.get(param);
if (res) {
return rowToObj<E>(config, res);
}
return null;
}
async deleteEntityById(className: string, id: string): Promise<boolean> {
const query = this.db?.prepare(
`DELETE
FROM ${this.schemaName}.${className}
WHERE e_id = ?;`
);
return query?.run([id]).changes === 1;
}
async getEntityList<E extends CoreEntity>(
q: QueryInterface<E>
): Promise<E[]> {
const { limit, search, config, order, offset } = q;
if (limit === 0) {
return [];
}
let searchQ = '';
const orderBy: string[] = [];
let orderByQ = '';
const off = offset !== undefined ? ` OFFSET ${offset}` : '';
const range = limit ? `LIMIT ${limit}${off}` : '';
const param: any[] = [];
if (search) {
searchQ = buildSearchQ<E>(config, search, param, searchQ);
}
if (order && order.length > 0) {
order.forEach((val) => {
orderBy.push(`${String(val.key)} ${val.order}`);
});
orderByQ = `ORDER BY ${orderBy.join(',\n')}`;
}
const query = this.db?.prepare(
`SELECT *
FROM ${this.schemaName}.${config.className}
${searchQ}
${orderByQ}
${range};`
);
const res = query?.all(param);
if (res) {
return tableToObj<E>(config, res);
}
return [];
}
async initEntity<E extends CoreEntity>(
className: string,
entity: E
): Promise<boolean> {
await this.execScripts([
{
exec: `CREATE TABLE ${this.schemaName}.${className}
(
${this.transformEntityKeys<E>(entity)}
);`,
param: [],
},
]);
return true;
}
transformEntityKeys<E extends CoreEntity>(entity: E): string {
const keys: (keyof E)[] = Object.keys(entity) as (keyof E)[];
const out: string[] = [];
keys.forEach((key) => {
const meta = getColumnMeta(entity, key);
if (key === 'e_id') {
out.push(`e_id TEXT PRIMARY KEY`);
} else if (meta?.dataType) {
mappingWithDataType(meta, out, key);
} else {
const type = typeof entity[key];
switch (type) {
case 'bigint':
case 'number':
out.push(`${String(key)} INTEGER NOT NULL`);
break;
case 'string':
out.push(`${String(key)} TEXT NOT NULL`);
break;
default:
throw Error('TypeNotSupported');
}
}
});
return out.join(',\n');
}
async removeConfig(key: string): Promise<void> {
try {
const query = await this.execScripts([
{
exec: `DELETE
FROM ${this.schemaName}.config
WHERE c_key = ?;`,
param: [key],
},
]);
this.log(query);
if (query.length !== 1) {
this.error('invalid result');
}
} catch (e) {
this.error(e);
}
}
async initNewDB(): Promise<void> {
this.debug('no init ');
}
async connect(): Promise<boolean> {
try {
this.db = new Database(this.path, {
verbose: this.debug,
});
} catch (e) {
this.error(e);
return false;
}
try {
const query = this.db.prepare(
`SELECT *
FROM ${this.schemaName}.config;`
);
const result = query.all();
const version = result.find((el) => {
return el.c_key === 'dbversion';
});
return !!version;
} catch (e) {
this.warn(e);
this.log('Create new Database');
await this.execScripts([
{
exec: `CREATE TABLE ${this.schemaName}.config
(
c_key text not null,
c_value text,
PRIMARY KEY (c_key)
);`,
param: [],
},
{
exec: `INSERT INTO ${this.schemaName}.config (c_key, c_value)
VALUES ('dbversion', '${this.dbVersion}');`,
param: [],
},
]);
this.setNew(true);
return true;
}
}
getRawDBObject(): DbType | null {
return this.db;
}
async configExist(key: string): Promise<boolean> {
const query = this.db?.prepare(
`SELECT *
FROM ${this.schemaName}.config
WHERE c_key = '${key}'`
);
const exist = query?.get();
return !!exist && exist.c_key !== undefined && exist.c_value !== undefined;
}
async setConfig(key: string, value: string): Promise<boolean> {
const query = this.db?.prepare(
`REPLACE INTO
${this.schemaName}
.
config
(
c_key,
c_value
)
VALUES ('${key}', '${value}');`
);
if (query === undefined) {
return false;
}
query.run();
return true;
}
async getConfig(key: string): Promise<ConfigType> {
const query = this.db?.prepare(
`SELECT *
FROM ${this.schemaName}.config
WHERE c_key = '${key}'`
);
return query?.get();
}
async execScripts(list: RawQuery[]): Promise<RunResult[]> {
const result: any[] = [];
list.forEach((el) => {
const prep = this.db?.prepare(el.exec);
const res = prep?.run(el.param);
if (res) {
result.push(res);
}
});
return result;
}
async disconnect(): Promise<boolean> {
return true;
}
}