@or-sdk/pgsql 1.0.3-beta.1950.0 → 1.0.3-beta.1953.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/cjs/Pgsql.js +35 -128
  2. package/dist/cjs/Pgsql.js.map +1 -1
  3. package/dist/cjs/utils/encodeValue.js +17 -0
  4. package/dist/cjs/utils/encodeValue.js.map +1 -0
  5. package/dist/cjs/utils/extractDatabaseNames.js +10 -0
  6. package/dist/cjs/utils/extractDatabaseNames.js.map +1 -0
  7. package/dist/cjs/utils/getDeleteRowsQuery.js +9 -0
  8. package/dist/cjs/utils/getDeleteRowsQuery.js.map +1 -0
  9. package/dist/cjs/utils/getEditRowQuery.js +10 -0
  10. package/dist/cjs/utils/getEditRowQuery.js.map +1 -0
  11. package/dist/cjs/utils/getInsertKeys.js +9 -0
  12. package/dist/cjs/utils/getInsertKeys.js.map +1 -0
  13. package/dist/cjs/utils/getInsertQueries.js +18 -0
  14. package/dist/cjs/utils/getInsertQueries.js.map +1 -0
  15. package/dist/cjs/utils/index.js +13 -1
  16. package/dist/cjs/utils/index.js.map +1 -1
  17. package/dist/esm/Pgsql.js +28 -106
  18. package/dist/esm/Pgsql.js.map +1 -1
  19. package/dist/esm/utils/encodeValue.js +12 -0
  20. package/dist/esm/utils/encodeValue.js.map +1 -0
  21. package/dist/esm/utils/extractDatabaseNames.js +5 -0
  22. package/dist/esm/utils/extractDatabaseNames.js.map +1 -0
  23. package/dist/esm/utils/getDeleteRowsQuery.js +8 -0
  24. package/dist/esm/utils/getDeleteRowsQuery.js.map +1 -0
  25. package/dist/esm/utils/getEditRowQuery.js +10 -0
  26. package/dist/esm/utils/getEditRowQuery.js.map +1 -0
  27. package/dist/esm/utils/getInsertKeys.js +7 -0
  28. package/dist/esm/utils/getInsertKeys.js.map +1 -0
  29. package/dist/esm/utils/getInsertQueries.js +14 -0
  30. package/dist/esm/utils/getInsertQueries.js.map +1 -0
  31. package/dist/esm/utils/index.js +6 -0
  32. package/dist/esm/utils/index.js.map +1 -1
  33. package/dist/types/Pgsql.d.ts +18 -31
  34. package/dist/types/Pgsql.d.ts.map +1 -1
  35. package/dist/types/types.d.ts +13 -20
  36. package/dist/types/types.d.ts.map +1 -1
  37. package/dist/types/utils/encodeValue.d.ts +4 -0
  38. package/dist/types/utils/encodeValue.d.ts.map +1 -0
  39. package/dist/types/utils/extractDatabaseNames.d.ts +4 -0
  40. package/dist/types/utils/extractDatabaseNames.d.ts.map +1 -0
  41. package/dist/types/utils/getDeleteRowsQuery.d.ts +4 -0
  42. package/dist/types/utils/getDeleteRowsQuery.d.ts.map +1 -0
  43. package/dist/types/utils/getEditRowQuery.d.ts +4 -0
  44. package/dist/types/utils/getEditRowQuery.d.ts.map +1 -0
  45. package/dist/types/utils/getInsertKeys.d.ts +4 -0
  46. package/dist/types/utils/getInsertKeys.d.ts.map +1 -0
  47. package/dist/types/utils/getInsertQueries.d.ts +4 -0
  48. package/dist/types/utils/getInsertQueries.d.ts.map +1 -0
  49. package/dist/types/utils/index.d.ts +6 -0
  50. package/dist/types/utils/index.d.ts.map +1 -1
  51. package/package.json +2 -2
  52. package/src/Pgsql.ts +60 -153
  53. package/src/types.ts +18 -20
  54. package/src/utils/encodeValue.ts +11 -0
  55. package/src/utils/extractDatabaseNames.ts +7 -0
  56. package/src/utils/getDeleteRowsQuery.ts +10 -0
  57. package/src/utils/getEditRowQuery.ts +12 -0
  58. package/src/utils/getInsertKeys.ts +9 -0
  59. package/src/utils/getInsertQueries.ts +18 -0
  60. package/src/utils/index.ts +6 -0
package/src/Pgsql.ts CHANGED
@@ -1,30 +1,33 @@
1
- import _ from 'lodash';
2
1
  import { Base, CalApiParams, List, MakeApiUrlData, makeList } from '@or-sdk/base';
3
2
  import { LIST_SCHEMAS_QUERY, SERVICE_KEY } from './constants';
4
3
  import {
5
4
  AddColumnsArgs,
6
5
  CreateDatabaseParams,
7
- CreateTableArgs,
6
+ CreateDatabaseResponse, CreateTableArgs,
8
7
  DatabaseItem,
9
8
  DeleteRowsArgs, DropDatabaseResponse, EditRowArgs,
10
- ExecuteQueryArgs, ExecuteQueryResponse, GetDBSizeResult, GetTableDataProps, InsertArgs,
9
+ ExecuteQueryArgs, ExecuteQueryResponse, GetDBSizeResult, InsertArgs,
11
10
  ListDatabasesResponse,
12
- PgsqlConfig, QueryField, Row, SelectAllArgs,
11
+ PgsqlConfig, Row, SelectAllArgs,
13
12
  } from './types';
14
13
  import {
15
14
  createSchemaQuery,
16
15
  getAddColumnsQuery,
17
16
  getCreateTableQuery,
17
+ getDeleteRowsQuery,
18
18
  getDropSchemaQuery,
19
- getDropTableQuery, getGenerateTableSchemaQuery,
19
+ getDropTableQuery, getEditRowQuery, getGenerateTableSchemaQuery,
20
20
  getGetPrimaryKeysQuery,
21
- getListTablesQuery, getSelectAllCountQuery, getSelectAllQuery, splitPrimaryKeys,
21
+ getInsertQueries,
22
+ getListTablesQuery, getSelectAllCountQuery, getSelectAllQuery,
22
23
  } from './utils';
23
24
 
24
25
 
25
26
  export class Pgsql extends Base {
27
+ private isExternal?: boolean;
28
+
26
29
  constructor(params: PgsqlConfig) {
27
- const { token, discoveryUrl, accountId, pgsqlUrl, version = 'master' } = params;
30
+ const { token, discoveryUrl, accountId, pgsqlUrl, version = 'master', isExternal } = params;
28
31
  super({
29
32
  token,
30
33
  discoveryUrl,
@@ -33,6 +36,7 @@ export class Pgsql extends Base {
33
36
  serviceUrl: pgsqlUrl,
34
37
  feature: version,
35
38
  });
39
+ this.isExternal = isExternal;
36
40
  }
37
41
 
38
42
  /**
@@ -52,7 +56,7 @@ export class Pgsql extends Base {
52
56
  (params.params as any).feature = this.feature;
53
57
  }
54
58
 
55
- return this.callApiV2<T>(params);
59
+ return this.callApi<T>(params);
56
60
  }
57
61
 
58
62
  makeApiUrl(data: MakeApiUrlData): string {
@@ -66,19 +70,17 @@ export class Pgsql extends Base {
66
70
  * ```typescript
67
71
  * const result = await pgsql.executeQuery({
68
72
  * query: 'select * from table',
69
- * database: 'db-name',
70
- * isExternal: false,
71
- * params: [],
73
+ * database: 'db-name'
72
74
  * });
73
75
  * ```
74
76
  */
75
- public async executeQuery<T>({ query, params, database, isExternal }: ExecuteQueryArgs): Promise<ExecuteQueryResponse<T>> {
77
+ public async executeQuery<T>({ query, params, database }: ExecuteQueryArgs): Promise<ExecuteQueryResponse<T>> {
76
78
  return this.makeRequest<ExecuteQueryResponse<T>>({
77
79
  data: {
78
80
  query,
79
81
  params,
80
82
  database,
81
- isExternal,
83
+ isExternal: this.isExternal,
82
84
  },
83
85
  method: 'POST',
84
86
  route: 'query',
@@ -90,7 +92,6 @@ export class Pgsql extends Base {
90
92
  * ```typescript
91
93
  * const databaseList = await pgsql.listDatabases();
92
94
  * ```
93
- * @returns {Array} database names
94
95
  */
95
96
  public async listDatabases(): Promise<List<DatabaseItem>> {
96
97
  const { databases } = await this.makeRequest<ListDatabasesResponse>({
@@ -107,8 +108,8 @@ export class Pgsql extends Base {
107
108
  * const result = await pgsql.createDatabase({ database: 'db-name' });
108
109
  * ```
109
110
  */
110
- public async createDatabase({ database, externalCredentials }: CreateDatabaseParams): Promise<void> {
111
- return this.makeRequest<void>({
111
+ public async createDatabase({ database, externalCredentials }: CreateDatabaseParams): Promise<CreateDatabaseResponse> {
112
+ return this.makeRequest<CreateDatabaseResponse>({
112
113
  data: {
113
114
  database,
114
115
  externalCredentials,
@@ -126,17 +127,18 @@ export class Pgsql extends Base {
126
127
  * const result = await pgsql.getDatabaseInfo({ database: 'db-name' });
127
128
  * ```
128
129
  */
129
- public async getDatabaseInfo({ database }: { database: string; }): Promise<unknown> {
130
- return this.callApiV2<unknown>({
131
- method: 'GET',
132
- route: `databases/${encodeURIComponent(database)}`,
133
- });
134
- }
130
+ // TODO: uncomment or replace route?
131
+ // public async getDatabaseInfo({ database }: { database: string; }): Promise<unknown> {
132
+ // return this.callApi<unknown>({
133
+ // method: 'GET',
134
+ // route: `databases/${encodeURIComponent(database)}`
135
+ // })
136
+ // }
135
137
 
136
138
  /**
137
139
  * Drop database
138
140
  * ```typescript
139
- * const result = await pgsql.dropDatabase({ database: 'db-name', isExternal: false });
141
+ * const result = await pgsql.dropDatabase({ database: 'db-name' });
140
142
  * ```
141
143
  */
142
144
  public async dropDatabase({ database, isExternal }: { database: string; isExternal?: boolean;}): Promise<DropDatabaseResponse> {
@@ -153,74 +155,67 @@ export class Pgsql extends Base {
153
155
  /**
154
156
  * List tables
155
157
  * ```typescript
156
- * const result = await pgsql.listTables({ database: 'db-name', schema: 'schema-name', isExternal: false });
158
+ * const result = await pgsql.listTables({ database: 'db-name', schema: 'schema-name' });
157
159
  * ```
158
160
  */
159
- public async listTables({ database, schema, isExternal }: { database: string; schema: string; isExternal: boolean; }): Promise<List<string>> {
161
+ public async listTables({ database, schema = 'public' }: { database: string; schema?: string; }): Promise<List<string>> {
160
162
  const { rows } = await this.executeQuery<{ table_name: string; }>({
161
163
  query: getListTablesQuery(schema),
162
164
  database,
163
- isExternal,
164
165
  });
165
-
166
166
  return makeList<string>(rows.map(x => x.table_name));
167
167
  }
168
168
 
169
169
  /**
170
170
  * List schemas
171
171
  * ```typescript
172
- * const result = await pgsql.listSchemas({ database: 'db-name', isExternal: false });
172
+ * const result = await pgsql.listSchemas({ database: 'db-name' });
173
173
  * ```
174
174
  */
175
- public async listSchemas({ database, isExternal }: { database: string; isExternal: boolean; }): Promise<List<string>> {
175
+ public async listSchemas({ database }: { database: string; }): Promise<List<string>> {
176
176
  const { rows } = await this.executeQuery<{ schema_name: string; }>({
177
177
  query: LIST_SCHEMAS_QUERY,
178
178
  database,
179
- isExternal,
180
179
  });
181
-
182
180
  return makeList<string>(rows.map(x => x.schema_name));
183
181
  }
184
182
 
185
183
  /**
186
184
  * Create schema
187
185
  * ```typescript
188
- * const result = await pgsql.createSchema({ database: 'db-name', schema: 'schema-name', isExternal: false });
186
+ * const result = await pgsql.createSchema({ database: 'db-name', schema: 'schema-name' });
189
187
  * ```
190
188
  */
191
- public async createSchema({ database, schema, isExternal }: { database: string; schema: string; isExternal: boolean; }): Promise<ExecuteQueryResponse<void>> {
189
+ public async createSchema({ database, schema }: { database: string; schema: string; }): Promise<ExecuteQueryResponse<void>> {
192
190
  return this.executeQuery<void>({
193
191
  query: createSchemaQuery(schema),
194
192
  database,
195
- isExternal,
196
193
  });
197
194
  }
198
195
 
199
196
  /**
200
197
  * Drop schema
201
198
  * ```typescript
202
- * const result = await pgsql.dropSchema({ database: 'db-name', schema: 'schema-name', isExternal: false });
199
+ * const result = await pgsql.dropSchema({ database: 'db-name', schema: 'schema-name' });
203
200
  * ```
204
201
  */
205
- public async dropSchema({ database, schema, isExternal }: { database: string; schema: string; isExternal: boolean; }): Promise<ExecuteQueryResponse<void>> {
202
+ public async dropSchema({ database, schema }: { database: string; schema: string; }): Promise<ExecuteQueryResponse<void>> {
206
203
  return this.executeQuery<void>({
207
204
  query: getDropSchemaQuery(schema),
208
205
  database,
209
- isExternal,
210
206
  });
211
207
  }
212
208
 
213
209
  /**
214
210
  * Drop table
215
211
  * ```typescript
216
- * const result = await pgsql.dropSchema({ database: 'db-name', schema: 'schema-name', table: 'table-name', isExternal: false });
212
+ * const result = await pgsql.dropSchema({ database: 'db-name', schema: 'schema-name', table: 'table-name' });
217
213
  * ```
218
214
  */
219
- public async dropTable({ database, schema, table, isExternal }: { database: string; schema: string; table: string; isExternal: boolean; }): Promise<ExecuteQueryResponse<void>> {
215
+ public async dropTable({ database, schema, table }: { database: string; schema: string; table: string; }): Promise<ExecuteQueryResponse<void>> {
220
216
  return this.executeQuery<void>({
221
217
  query: getDropTableQuery(schema, table),
222
218
  database,
223
- isExternal,
224
219
  });
225
220
  }
226
221
 
@@ -235,16 +230,14 @@ export class Pgsql extends Base {
235
230
  * { name: 'col1', type: 'integer' },
236
231
  * { name: 'col2', type: 'text' }
237
232
  * ],
238
- * primaryKey: 'col1,col2',
239
- * isExternal: false
233
+ * primaryKey: 'col1,col2'
240
234
  * });
241
235
  * ```
242
236
  */
243
- public async createTable({ database, schema, table, columns, primaryKey, isExternal }: CreateTableArgs): Promise<ExecuteQueryResponse<void>> {
237
+ public async createTable({ database, schema, table, columns, primaryKey }: CreateTableArgs): Promise<ExecuteQueryResponse<void>> {
244
238
  return this.executeQuery<void>({
245
239
  query: getCreateTableQuery(schema, table, columns, primaryKey),
246
240
  database,
247
- isExternal,
248
241
  });
249
242
  }
250
243
 
@@ -259,15 +252,13 @@ export class Pgsql extends Base {
259
252
  * { name: 'col1', type: 'integer' },
260
253
  * { name: 'col2', type: 'text' }
261
254
  * ],
262
- * isExternal: false
263
255
  * });
264
256
  * ```
265
257
  */
266
- public async addColumns({ database, schema, table, columns, isExternal }: AddColumnsArgs): Promise<ExecuteQueryResponse<void>> {
258
+ public async addColumns({ database, schema, table, columns }: AddColumnsArgs): Promise<ExecuteQueryResponse<void>> {
267
259
  return this.executeQuery<void>({
268
260
  query: getAddColumnsQuery(schema, table, columns),
269
261
  database,
270
- isExternal,
271
262
  });
272
263
  }
273
264
 
@@ -282,101 +273,52 @@ export class Pgsql extends Base {
282
273
  * { col1: 'value' }
283
274
  * ],
284
275
  * chunkSize: 300,
285
- * context: { progress: 0 } // progress of insert will be set from 0 to 100,
286
- * isExternal: false
276
+ * context: { progress: 0 } // progress of insert will be set from 0 to 100
287
277
  * });
288
278
  * ```
289
279
  */
290
- public async insert({ database, schema, table, rows, chunkSize = 300, context, isExternal }: InsertArgs): Promise<ExecuteQueryResponse<unknown>[]> {
291
- let params: any[] = [];
292
- const addParam = (val: any) => {params.push(val);return `$${params.length}`;};
280
+ public async insert({ database, schema, table, rows, chunkSize = 300, context }: InsertArgs): Promise<ExecuteQueryResponse<void>[]> {
293
281
  const res = [];
294
- if (!_.isArray(rows)) rows = [rows];
295
- const allKeys = {};
296
- rows.forEach(x => Object.assign(allKeys, x));
297
- const keys = Object.keys(allKeys);
298
- const stringifyRow = (row: any) => `${keys.map(key => addParam(row[key])).join(', ')}`;
299
-
300
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
301
- // @ts-ignore
302
- for (const [index, chunk] of _.chunk(rows, chunkSize).entries()) {
303
- params = [];
304
- const query = `insert into ${schema}.${table} (${keys.join(', ')})
305
- values (${chunk.map(stringifyRow).join('), (')});`;
306
- res.push(await this.executeQuery({
307
- query,
308
- database,
309
- isExternal,
310
- params,
311
- }));
312
- if (context) context.progress = (index + 1) / (rows.length / chunkSize) * 100;
313
- }
314
-
315
- return res;
316
- }
317
-
318
282
 
319
- // TODO: add method description and example
320
- // TODO: add context ass in selectAll and rethink this two methods
321
- public async getDatabaseRows({ database, schema, table, chunkSize = 1000, offset = 0, limit, isExternal, params }: GetTableDataProps): Promise<{ rows: List<Row>; fields: QueryField[]; }> {
322
- let fields: QueryField[] = [];
323
- let rows, result: Row[] = [];
283
+ const queries = getInsertQueries(schema, table, rows, chunkSize);
324
284
 
325
- // TODO: add order by primary key?
326
- // const query = `select * from ${schema}.${table} order by int`;
327
- const query = `select * from ${schema}.${table}`;
328
-
329
- if (limit && limit < chunkSize) chunkSize = limit;
330
-
331
- do {
332
- ({ rows, fields } = await this.executeQuery<Row>({
333
- query: getSelectAllQuery(query, offset, chunkSize),
285
+ for (const [index, query] of Array.from(queries.entries())) {
286
+ res.push(await this.executeQuery<void>({
287
+ query,
334
288
  database,
335
- isExternal,
336
- params,
337
289
  }));
338
- offset += chunkSize;
339
- result = result.concat(rows);
340
290
 
341
- if (limit && result.length >= limit) {
342
- result = result.slice(0, limit);
343
- break;
291
+ if (context) {
292
+ context.progress = Math.min((index + 1) / (rows.length / Math.min(chunkSize, rows.length)), 1) * 100;
344
293
  }
345
- } while (rows.length === chunkSize);
294
+ }
346
295
 
347
- return {
348
- rows: makeList<Row>(result),
349
- fields,
350
- };
296
+ return res;
351
297
  }
352
298
 
353
-
354
299
  /**
355
300
  * Select all
356
301
  * ```typescript
357
302
  * const result = await pgsql.selectAll({
358
303
  * database: 'db-name',
359
- * query: 'select * from table where id = $1', // must be select only, without limit and offset
304
+ * query: 'select * from table', // must be select only, without limit and offset
360
305
  * chunkSize: 300,
361
306
  * offset: 0,
362
307
  * limit: 0,
363
308
  * context: { progress: 0, total: 0 } // progress of select will be set from 0 to 100
364
- * isExternal: false,
365
- * params: ['123']
366
309
  * });
367
310
  * ```
368
311
  */
369
- public async selectAll({ database, query, context, chunkSize = 1000, offset = 0, limit, isExternal, params }: SelectAllArgs): Promise<List<Row>> {
312
+ public async selectAll({ database, query, context, chunkSize = 1000, offset = 0, limit }: SelectAllArgs): Promise<List<Row>> {
370
313
  let count: number, rows, result: Row[] = [];
371
-
372
- if (limit && limit < chunkSize) chunkSize = limit;
314
+ if (limit && limit < chunkSize) {
315
+ chunkSize = limit;
316
+ }
373
317
 
374
318
  if (context) {
375
319
  const { rows } = await this.executeQuery<{ count: number; }>({
376
320
  query: getSelectAllCountQuery(query),
377
321
  database,
378
- isExternal,
379
- params,
380
322
  });
381
323
  count = rows[0].count;
382
324
  context.total = count;
@@ -386,16 +328,12 @@ values (${chunk.map(stringifyRow).join('), (')});`;
386
328
  ({ rows } = await this.executeQuery<Row>({
387
329
  query: getSelectAllQuery(query, offset, chunkSize),
388
330
  database,
389
- isExternal,
390
- params,
391
331
  }));
392
332
  offset += chunkSize;
393
333
  result = result.concat(rows);
394
-
395
334
  if (context) {
396
335
  context.progress = Math.min(offset / count! * 100, 100);
397
336
  }
398
-
399
337
  if (limit && result.length >= limit) {
400
338
  result = result.slice(0, limit);
401
339
  break;
@@ -408,14 +346,13 @@ values (${chunk.map(stringifyRow).join('), (')});`;
408
346
  /**
409
347
  * Get primary keys
410
348
  * ```typescript
411
- * const result = await pgsql.getPrimaryKeys({ database: 'db-name', schema: 'schema-name', table: 'table-name', isExternal: false });
349
+ * const result = await pgsql.getPrimaryKeys({ database: 'db-name', schema: 'schema-name', table: 'table-name' });
412
350
  * ```
413
351
  */
414
- public async getPrimaryKeys({ database, schema, table, isExternal }: { database: string; schema: string; table: string; isExternal: boolean; }): Promise<string> {
352
+ public async getPrimaryKeys({ database, schema, table }: { database: string; schema: string; table: string; }): Promise<string> {
415
353
  const { rows } = await this.executeQuery<{ pk: string; }>({
416
354
  database,
417
355
  query: getGetPrimaryKeysQuery(schema, table),
418
- isExternal,
419
356
  });
420
357
  return rows[0].pk;
421
358
  }
@@ -431,28 +368,13 @@ values (${chunk.map(stringifyRow).join('), (')});`;
431
368
  * value: 'new_value',
432
369
  * row: { pk: 'pk_val', col1: 'old_value' },
433
370
  * primaryKeys: 'pk',
434
- * isExternal: false
435
371
  * });
436
372
  * ```
437
373
  */
438
- public async editRow({ database, schema, table, key, value, row, primaryKeys, isExternal }: EditRowArgs): Promise<ExecuteQueryResponse<void>> {
439
- // TODO: maybe move query and params to utils and return both
440
- const params: any[] = [];
441
- const addParam = (val: any) => {
442
- params.push(val);
443
- return `$${params.length}`;
444
- };
445
-
446
- const pk = splitPrimaryKeys(primaryKeys);
447
-
448
- // TODO: move query to utils
374
+ public async editRow({ database, schema, table, key, value, row, primaryKeys }: EditRowArgs): Promise<ExecuteQueryResponse<void>> {
449
375
  return this.executeQuery({
450
376
  database,
451
- query: `update ${schema}.${table}
452
- set ${key} = ${addParam(value)}
453
- where ${pk.map(primaryKey => `${primaryKey} = ${addParam(row[primaryKey])}`).join(' AND ')}`,
454
- isExternal,
455
- params,
377
+ query: getEditRowQuery(schema, table, key, value, row, primaryKeys),
456
378
  });
457
379
  }
458
380
 
@@ -467,27 +389,13 @@ where ${pk.map(primaryKey => `${primaryKey} = ${addParam(row[primaryKey])}`).joi
467
389
  * { pk: 'pk_val', col1: 'value' }
468
390
  * ],
469
391
  * primaryKeys: 'pk',
470
- * isExternal: false
471
392
  * });
472
393
  * ```
473
394
  */
474
- public async deleteRows({ database, schema, table, rows, primaryKeys, isExternal }: DeleteRowsArgs): Promise<ExecuteQueryResponse<void>> {
475
- const params: any[] = [];
476
- const addParam = (val: any) => {
477
- params.push(val);
478
- return `$${params.length}`;
479
- };
480
-
481
- const pk = splitPrimaryKeys(primaryKeys);
482
- // TODO: move query to util
483
- const query = `delete from ${schema}.${table}
484
- where (${rows.map(row => `${pk.map(primaryKey => `${primaryKey} = ${addParam(row[primaryKey])}`).join(' AND ')}`).join(') \nOR (')})`;
485
-
395
+ public async deleteRows({ database, schema, table, rows, primaryKeys }: DeleteRowsArgs): Promise<ExecuteQueryResponse<void>> {
486
396
  return this.executeQuery({
487
397
  database,
488
- query,
489
- isExternal,
490
- params,
398
+ query: getDeleteRowsQuery(schema, table, rows, primaryKeys),
491
399
  });
492
400
  }
493
401
 
@@ -497,11 +405,10 @@ where ${pk.map(primaryKey => `${primaryKey} = ${addParam(row[primaryKey])}`).joi
497
405
  * const result = await pgsql.generateTableSchema({ database: 'db-name', schema: 'schema-name', table: 'table-name' });
498
406
  * ```
499
407
  */
500
- public async generateTableSchema({ database, schema, table, isExternal }: { database: string; schema: string; table: string; isExternal: boolean; }): Promise<string> {
408
+ public async generateTableSchema({ database, schema, table }: { database: string; schema: string; table: string; }): Promise<string> {
501
409
  const { rows } = await this.executeQuery<{ code: string; }>({
502
410
  database,
503
411
  query: getGenerateTableSchemaQuery(schema, table),
504
- isExternal,
505
412
  });
506
413
 
507
414
  return rows[0].code;
package/src/types.ts CHANGED
@@ -25,6 +25,11 @@ export type PgsqlConfig = {
25
25
  * Api version
26
26
  */
27
27
  version?: string;
28
+
29
+ /**
30
+ * use external database
31
+ */
32
+ isExternal?: boolean;
28
33
  };
29
34
 
30
35
  export type QueryField = {
@@ -49,9 +54,18 @@ export type ExecuteQueryResponse<T> = {
49
54
 
50
55
  export type ExecuteQueryArgs = {
51
56
  query: string;
52
- params?: any[];
57
+ params?: {
58
+ [key: string]: unknown;
59
+ };
53
60
  database: string;
54
- isExternal: boolean;
61
+ };
62
+
63
+ export type CreateDatabaseResponse = {
64
+ ok: number;
65
+ result: [
66
+ unknown[],
67
+ unknown[],
68
+ ];
55
69
  };
56
70
 
57
71
  export type ListDatabasesResponseItem = {
@@ -73,7 +87,7 @@ export type GetDBSizeResult = {
73
87
 
74
88
  export type TableColumn = {
75
89
  name: string;
76
- type: string;
90
+ type: number;
77
91
  };
78
92
 
79
93
  export type CreateTableArgs = {
@@ -82,7 +96,6 @@ export type CreateTableArgs = {
82
96
  table: string;
83
97
  columns: TableColumn[];
84
98
  primaryKey: string;
85
- isExternal: boolean;
86
99
  };
87
100
 
88
101
  export type AddColumnsArgs = {
@@ -90,7 +103,6 @@ export type AddColumnsArgs = {
90
103
  schema: string;
91
104
  table: string;
92
105
  columns: TableColumn[];
93
- isExternal: boolean;
94
106
  };
95
107
 
96
108
  export type Row = {
@@ -106,19 +118,9 @@ export type InsertArgs = {
106
118
  context?: {
107
119
  progress?: number;
108
120
  };
109
- isExternal: boolean;
110
121
  };
111
122
 
112
- export type GetTableDataProps = {
113
- database: string;
114
- schema: string;
115
- table: string;
116
- isExternal: boolean;
117
- chunkSize?: number;
118
- offset?: number;
119
- limit?: number;
120
- params?: any[];
121
- };
123
+ export type EncodedValue = string | number | boolean;
122
124
 
123
125
  export type SelectAllArgs = {
124
126
  database: string;
@@ -130,8 +132,6 @@ export type SelectAllArgs = {
130
132
  chunkSize?: number;
131
133
  offset?: number;
132
134
  limit?: number;
133
- isExternal: boolean;
134
- params?: any[];
135
135
  };
136
136
 
137
137
  export type EditRowArgs = {
@@ -142,7 +142,6 @@ export type EditRowArgs = {
142
142
  value: unknown;
143
143
  row: Row;
144
144
  primaryKeys: string;
145
- isExternal: boolean;
146
145
  };
147
146
 
148
147
  export type DeleteRowsArgs = {
@@ -151,7 +150,6 @@ export type DeleteRowsArgs = {
151
150
  table: string;
152
151
  rows: Row[];
153
152
  primaryKeys: string;
154
- isExternal: boolean;
155
153
  };
156
154
 
157
155
  export type DatabaseItem = {
@@ -0,0 +1,11 @@
1
+ import { EncodedValue } from '../types';
2
+ import _ from 'lodash';
3
+
4
+ function encodeValue(value: unknown): EncodedValue {
5
+ if (_.isUndefined(value) || value === '' || _.isNull(value)) return 'NULL';
6
+ if (_.isString(value)) return `'${value.replaceAll('\'', '\'\'')}'`;
7
+ if (_.isNumber(value) || _.isBoolean(value)) return value;
8
+ return `'${JSON.stringify(value).replaceAll('\'', '\'\'')}'`;
9
+ }
10
+
11
+ export default encodeValue;
@@ -0,0 +1,7 @@
1
+ import { ListDatabasesResponseItem } from '../types';
2
+
3
+ function extractDatabaseNames(databaseNameArr: ListDatabasesResponseItem[]): string[] {
4
+ return databaseNameArr.map(({ name }) => name);
5
+ }
6
+
7
+ export default extractDatabaseNames;
@@ -0,0 +1,10 @@
1
+ import { Row } from '../types';
2
+ import { encodeValue, splitPrimaryKeys } from '../utils';
3
+
4
+ function getDeleteRowQuery(schema: string, table: string, rows: Row[], primaryKeys: string): string {
5
+ const pk = splitPrimaryKeys(primaryKeys);
6
+ return `delete from ${schema}.${table}
7
+ where (${rows.map(row => `${pk.map(primaryKey => `${primaryKey} = ${encodeValue(row[primaryKey])}`).join(' AND ')}`).join(') \nOR (')})`;
8
+ }
9
+
10
+ export default getDeleteRowQuery;
@@ -0,0 +1,12 @@
1
+ import { encodeValue, splitPrimaryKeys } from '../utils';
2
+ import { Row } from '../types';
3
+
4
+ function getEditRowQuery(schema: string, table: string, key: string, value: unknown, row: Row, primaryKeys: string): string {
5
+ value = encodeValue(value);
6
+ const pk = splitPrimaryKeys(primaryKeys);
7
+ return `update ${schema}.${table}
8
+ set ${key} = ${value}
9
+ where ${pk.map(primaryKey => `${primaryKey} = ${encodeValue(row[primaryKey])}`).join(' AND ')}`;
10
+ }
11
+
12
+ export default getEditRowQuery;
@@ -0,0 +1,9 @@
1
+ import { Row } from '../types';
2
+
3
+ function getInsertKeys(rows: Row[]): string[] {
4
+ const allKeys = {};
5
+ rows.forEach(x => Object.assign(allKeys, x));
6
+ return Object.keys(allKeys);
7
+ }
8
+
9
+ export default getInsertKeys;
@@ -0,0 +1,18 @@
1
+ import { Row } from '../types';
2
+ import { encodeValue, getInsertKeys } from '../utils';
3
+ import _ from 'lodash';
4
+
5
+ function getInsertQueries(schema: string, table: string, insertRows: Row[], chunkSize: number): string[] {
6
+ const rows = _.isArray(insertRows) ? insertRows : [insertRows];
7
+
8
+ const keys = getInsertKeys(rows);
9
+ const stringifyRow = (row: Row) => `${keys.map(key => encodeValue(row[key])).join(', ')}`;
10
+
11
+ return _.chain(rows)
12
+ .chunk(chunkSize)
13
+ .map((chunk) => `insert into ${schema}.${table} (${keys.join(', ')})
14
+ values (${chunk.map(stringifyRow).join('), (')});`)
15
+ .value();
16
+ }
17
+
18
+ export default getInsertQueries;
@@ -2,6 +2,9 @@
2
2
  * @internal
3
3
  */
4
4
 
5
+ export { default as extractDatabaseNames } from './extractDatabaseNames';
6
+ export { default as getInsertKeys } from './getInsertKeys';
7
+ export { default as encodeValue } from './encodeValue';
5
8
  export { default as splitPrimaryKeys } from './splitPrimaryKeys';
6
9
  export { default as getListTablesQuery } from './getListTablesQuery';
7
10
  export { default as createSchemaQuery } from './createSchemaQuery';
@@ -9,7 +12,10 @@ export { default as getDropSchemaQuery } from './getDropSchemaQuery';
9
12
  export { default as getCreateTableQuery } from './getCreateTableQuery';
10
13
  export { default as getDropTableQuery } from './getDropTableQuery';
11
14
  export { default as getAddColumnsQuery } from './getAddColumnsQuery';
15
+ export { default as getInsertQueries } from './getInsertQueries';
12
16
  export { default as getSelectAllCountQuery } from './getSelectAllCountQuery';
13
17
  export { default as getSelectAllQuery } from './getSelectAllQuery';
18
+ export { default as getEditRowQuery } from './getEditRowQuery';
19
+ export { default as getDeleteRowsQuery } from './getDeleteRowsQuery';
14
20
  export { default as getGenerateTableSchemaQuery } from './getGenerateTableSchemaQuery';
15
21
  export { default as getGetPrimaryKeysQuery } from './getGetPrimaryKeysQuery';