pogi 2.10.2 → 3.0.0-beta2

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 (83) hide show
  1. package/.vscode/launch.json +47 -15
  2. package/CHANGELOG.md +11 -0
  3. package/docs/API/PgDb.md +25 -0
  4. package/docs/notification.md +19 -0
  5. package/jest.config.js +23 -0
  6. package/lib/bin/generateInterface.js +3 -3
  7. package/lib/bin/generateInterface.js.map +1 -1
  8. package/lib/connectionOptions.d.ts +10 -0
  9. package/lib/index.d.ts +1 -1
  10. package/lib/pgConverters.d.ts +9 -8
  11. package/lib/pgConverters.js +46 -32
  12. package/lib/pgConverters.js.map +1 -1
  13. package/lib/pgConverters.test.d.ts +1 -0
  14. package/lib/pgConverters.test.js +13 -0
  15. package/lib/pgConverters.test.js.map +1 -0
  16. package/lib/pgDb.d.ts +27 -27
  17. package/lib/pgDb.js +293 -100
  18. package/lib/pgDb.js.map +1 -1
  19. package/lib/pgDb.test.d.ts +1 -0
  20. package/lib/pgDb.test.js +1126 -0
  21. package/lib/pgDb.test.js.map +1 -0
  22. package/lib/pgDbInterface.d.ts +53 -0
  23. package/lib/pgDbInterface.js +11 -0
  24. package/lib/pgDbInterface.js.map +1 -0
  25. package/lib/pgDbOperators.d.ts +3 -3
  26. package/lib/pgDbOperators.js +4 -7
  27. package/lib/pgDbOperators.js.map +1 -1
  28. package/lib/pgDbOperators.test.d.ts +1 -0
  29. package/lib/pgDbOperators.test.js +313 -0
  30. package/lib/pgDbOperators.test.js.map +1 -0
  31. package/lib/pgSchema.d.ts +10 -9
  32. package/lib/pgSchema.js.map +1 -1
  33. package/lib/pgSchemaInterface.d.ts +12 -0
  34. package/lib/pgSchemaInterface.js +3 -0
  35. package/lib/pgSchemaInterface.js.map +1 -0
  36. package/lib/pgTable.d.ts +15 -40
  37. package/lib/pgTable.js +54 -54
  38. package/lib/pgTable.js.map +1 -1
  39. package/lib/pgTableInterface.d.ts +102 -0
  40. package/lib/pgTableInterface.js +4 -0
  41. package/lib/pgTableInterface.js.map +1 -0
  42. package/lib/pgUtils.d.ts +16 -6
  43. package/lib/pgUtils.js +162 -31
  44. package/lib/pgUtils.js.map +1 -1
  45. package/lib/queryAble.d.ts +20 -53
  46. package/lib/queryAble.js +149 -80
  47. package/lib/queryAble.js.map +1 -1
  48. package/lib/queryAbleInterface.d.ts +55 -0
  49. package/lib/queryAbleInterface.js +7 -0
  50. package/lib/queryAbleInterface.js.map +1 -0
  51. package/lib/queryWhere.d.ts +2 -2
  52. package/lib/queryWhere.js +19 -23
  53. package/lib/queryWhere.js.map +1 -1
  54. package/mkdocs.yml +1 -0
  55. package/package.json +21 -11
  56. package/src/bin/generateInterface.ts +2 -2
  57. package/src/connectionOptions.ts +48 -13
  58. package/src/index.d.ts +7 -0
  59. package/src/index.ts +1 -1
  60. package/src/pgConverters.test.ts +10 -0
  61. package/src/pgConverters.ts +34 -22
  62. package/src/pgDb.test.ts +1324 -0
  63. package/src/pgDb.ts +318 -122
  64. package/src/pgDbInterface.ts +57 -0
  65. package/src/pgDbOperators.test.ts +478 -0
  66. package/src/pgDbOperators.ts +45 -22
  67. package/src/pgSchema.ts +10 -9
  68. package/src/pgSchemaInterface.ts +12 -0
  69. package/src/pgTable.ts +66 -98
  70. package/src/pgTableInterface.ts +131 -0
  71. package/src/pgUtils.ts +166 -42
  72. package/src/queryAble.ts +167 -125
  73. package/src/queryAbleInterface.ts +104 -0
  74. package/src/queryWhere.ts +42 -43
  75. package/{spec/resources → src/test}/init.sql +23 -0
  76. package/src/test/pgServiceRestartTest.ts +1500 -0
  77. package/{spec/resources → src/test}/throw_exception.sql +0 -0
  78. package/{spec/resources → src/test}/tricky.sql +0 -0
  79. package/{src/tsconfig.json → tsconfig.json} +12 -11
  80. package/spec/run.js +0 -5
  81. package/spec/support/jasmine.json +0 -9
  82. package/src/test/pgDbOperatorSpec.ts +0 -492
  83. package/src/test/pgDbSpec.ts +0 -994
@@ -0,0 +1,57 @@
1
+ import * as pg from 'pg';
2
+ import { PgDbLogger } from "./pgDbLogger";
3
+ import { IPgTable } from "./pgTableInterface";
4
+ import { IPgSchema } from "./pgSchemaInterface";
5
+ import { IQueryAble } from './queryAbleInterface';
6
+ import { ConnectionOptions } from './connectionOptions';
7
+
8
+ export interface ResultFieldType {
9
+ name: string,
10
+ tableID: number,
11
+ columnID: number,
12
+ dataTypeID: number,
13
+ dataTypeSize: number,
14
+ dataTypeModifier: number,
15
+ format: string
16
+ }
17
+
18
+ /** LISTEN callback parameter */
19
+ export interface Notification {
20
+ processId: number,
21
+ channel: string,
22
+ payload?: string
23
+ }
24
+
25
+ export enum TranzactionIsolationLevel {
26
+ serializable = 'SERIALIZABLE',
27
+ repeatableRead = 'REPEATABLE READ',
28
+ readCommitted = 'READ COMMITTED',
29
+ readUncommitted = 'READ UNCOMMITTED'
30
+ }
31
+
32
+ export type PostProcessResultFunc = (res: any[], fields: ResultFieldType[], logger: PgDbLogger) => void;
33
+
34
+ export interface IPgDb extends IQueryAble {
35
+ connection: pg.PoolClient | null;
36
+ config: ConnectionOptions;
37
+ pool: pg.Pool;
38
+ pgdbTypeParsers: any;
39
+ knownOids: Record<number, boolean>
40
+ schemas: { [name: string]: IPgSchema };
41
+ tables: { [name: string]: IPgTable<any> };
42
+
43
+ runRestartConnectionForListen(): Promise<Error | null>;
44
+ needToFixConnectionForListen(): boolean;
45
+ postProcessResult: PostProcessResultFunc | undefined | null;
46
+ resetMissingParsers(connection: pg.PoolClient, oidList: number[]): Promise<void>
47
+
48
+ transactionBegin(options?: { isolationLevel?: TranzactionIsolationLevel, deferrable?: boolean, readOnly?: boolean }): Promise<IPgDb>
49
+ transactionCommit(): Promise<IPgDb>;
50
+
51
+ listen(channel: string, callback: (notification: Notification) => void): Promise<void>
52
+ unlisten(channel: string, callback?: (notification: Notification) => void): Promise<void>
53
+ /**
54
+ * Notify a channel (https://www.postgresql.org/docs/current/sql-notify.html)
55
+ */
56
+ notify(channel: string, payload?: string): Promise<any[]>
57
+ }
@@ -0,0 +1,478 @@
1
+ import { PgDb } from "./pgDb";
2
+ import { PgTable } from "./pgTable";
3
+
4
+ describe("pgdb", () => {
5
+ let pgdb: PgDb;
6
+ let schema = 'pgdb_test';
7
+ let tableUsers: PgTable<any>;
8
+ let viewUsers: PgTable<any>;
9
+
10
+ beforeAll(async () => {
11
+ //jasmine.DEFAULT_TIMEOUT_INTERVAL = 800000;
12
+
13
+ /**
14
+ * Using environment variables, e.g.
15
+ * PGUSER (defaults USER env var, so optional)
16
+ * PGDATABASE (defaults USER env var, so optional)
17
+ * PGPASSWORD
18
+ * PGPORT
19
+ * etc...
20
+ */
21
+ try {
22
+ pgdb = await PgDb.connect({ connectionString: "postgres://" });
23
+ } catch (e) {
24
+ console.error("connection failed! Are you specified PGUSER/PGDATABASE/PGPASSWORD correctly?");
25
+ console.error(e);
26
+ process.exit(1);
27
+ }
28
+ //await pgdb.run('DROP SCHEMA IF EXISTS "' + schema + '" CASCADE ');
29
+ await pgdb.run('CREATE SCHEMA IF NOT EXISTS "' + schema + '"');
30
+ await pgdb.execute('src/test/init.sql', (cmd) => cmd.replace(/__SCHEMA__/g, '"' + schema + '"'));
31
+ await pgdb.reload();
32
+
33
+ pgdb.setLogger(console);
34
+ tableUsers = pgdb.schemas[schema]['users'];
35
+ viewUsers = pgdb.schemas[schema]['users_view'];
36
+
37
+ return Promise.resolve();
38
+ });
39
+
40
+ beforeEach(async () => {
41
+ await tableUsers.run('DELETE FROM ' + tableUsers);
42
+ });
43
+
44
+ afterAll(async () => {
45
+ await pgdb.close();
46
+ });
47
+
48
+ it("Testing Array operators", async () => {
49
+ await tableUsers.insert({ name: 'S', favourites: ['sport'] });
50
+ await tableUsers.insert({ name: 'SF', favourites: ['sport', 'food'] });
51
+ await tableUsers.insert({ name: 'TF', favourites: ['tech', 'food'] });
52
+
53
+ let res;
54
+
55
+ res = await tableUsers.find({ 'favourites': 'sport' }, { fields: ['name'] }); //=> 'sport' = ANY("favourites")
56
+ expect(res.map(r => r.name)).toEqual(['S', 'SF']);
57
+
58
+ res = await tableUsers.find({ 'favourites': ['sport', 'food'] }, { fields: ['name'] }); //=> favourites = '{sport,food}'
59
+ expect(res.map(r => r.name)).toEqual(['SF']);
60
+
61
+ res = await tableUsers.find({ 'favourites @>': ['sport'] }); //contains
62
+ expect(res.map(r => r.name)).toEqual(['S', 'SF']);
63
+
64
+ res = await tableUsers.find({ 'favourites <@': ['sport', 'food', 'tech'] });//contained by
65
+ expect(res.map(r => r.name)).toEqual(['S', 'SF', 'TF']);
66
+
67
+ res = await tableUsers.find({ 'favourites &&': ['sport', 'music'] });//overlap
68
+ expect(res.map(r => r.name)).toEqual(['S', 'SF']);
69
+
70
+ res = await tableUsers.find({ 'favourites !=': ['sport'] });//
71
+ expect(res.map(r => r.name)).toEqual(['SF', 'TF']);
72
+ });
73
+
74
+ it("Testing Array operators on view", async () => {
75
+ await viewUsers.insert({ name: 'S', favourites: ['sport'] });
76
+ await viewUsers.insert({ name: 'SF', favourites: ['sport', 'food'] });
77
+ await viewUsers.insert({ name: 'TF', favourites: ['tech', 'food'] });
78
+
79
+ let res;
80
+
81
+ res = await viewUsers.find({ 'favourites': 'sport' }, { fields: ['name'] }); //=> 'sport' = ANY("favourites")
82
+ expect(res.map(r => r.name)).toEqual(['S', 'SF']);
83
+
84
+ res = await viewUsers.find({ 'favourites': ['sport', 'food'] }, { fields: ['name'] }); //=> favourites = '{sport,food}'
85
+ expect(res.map(r => r.name)).toEqual(['SF']);
86
+
87
+ res = await viewUsers.find({ 'favourites @>': ['sport'] }); //contains
88
+ expect(res.map(r => r.name)).toEqual(['S', 'SF']);
89
+
90
+ res = await viewUsers.find({ 'favourites <@': ['sport', 'food', 'tech'] });//contained by
91
+ expect(res.map(r => r.name)).toEqual(['S', 'SF', 'TF']);
92
+
93
+ res = await viewUsers.find({ 'favourites &&': ['sport', 'music'] });//overlap
94
+ expect(res.map(r => r.name)).toEqual(['S', 'SF']);
95
+
96
+ res = await viewUsers.find({ 'favourites !=': ['sport'] });//
97
+ expect(res.map(r => r.name)).toEqual(['SF', 'TF']);
98
+ });
99
+
100
+ it("Searching in elements in jsonList", async () => {
101
+ await tableUsers.insert({ name: 'Medium and high risk', jsonList: [{ risk: 'H' }, { risk: 'M' }] });
102
+
103
+ let query1 = {
104
+ or: [{ '"jsonList" @>': [{ "risk": "H" }] }, { '"jsonList" @>': [{ "risk": "L" }] }]
105
+ };
106
+ let query2 = {
107
+ or: [{ 'jsonList @>': [{ "risk": "H" }] }, { 'jsonList @>': [{ "risk": "L" }] }]
108
+ };
109
+ let query3 = {
110
+ or: [{ 'jsonList @>': '[{"risk": "H"}]' }, { 'jsonList @>': '[{"risk": "L"}]' }]
111
+ };
112
+
113
+ let res;
114
+ res = await tableUsers.find(query1, { fields: ['name'] });
115
+ expect(res.map(r => r.name)).toEqual(['Medium and high risk']);
116
+
117
+ res = await tableUsers.find(query2, { fields: ['name'] });
118
+ expect(res.map(r => r.name)).toEqual(['Medium and high risk']);
119
+
120
+ res = await tableUsers.find(query3, { fields: ['name'] });
121
+ expect(res.map(r => r.name)).toEqual(['Medium and high risk']);
122
+ });
123
+
124
+ it("Free text search", async () => {
125
+ await tableUsers.insert({ name: 'Medium and high risk', jsonList: [{ name: "The return of the Jedi" }] });
126
+
127
+ let res;
128
+ for (let searchCol of ['"name"||"jsonList" @@', 'tsv @@']) {
129
+ res = await tableUsers.find({ [searchCol]: 'risk & return' }, { fields: ['name'] });
130
+ expect(res.map(r => r.name)).toEqual(['Medium and high risk']);
131
+
132
+ res = await tableUsers.find({ [searchCol]: 'risk & future' }, { fields: ['name'] });
133
+ expect(res.length).toEqual(0);
134
+
135
+ res = await tableUsers.find({
136
+ [searchCol]: {
137
+ lang: 'english',
138
+ query: 'risk & return'
139
+ }
140
+ }, { fields: ['name'] });
141
+ expect(res.map(r => r.name)).toEqual(['Medium and high risk']);
142
+ }
143
+ });
144
+
145
+ it("Testing Jsonb list selector operators", async () => {
146
+ //@formatter:off
147
+ await tableUsers.insert({ name: 'Somebody', jsonList: ['sport', 'season'] });
148
+ await tableUsers.insert({ name: 'Anybody', jsonList: ['art', 'age'] });
149
+ await tableUsers.insert({ name: 'Nobody', jsonList: ['neverending', 'nearby'] });
150
+ await tableUsers.insert({ name: 'Noone', jsonList: null, });
151
+ await tableUsers.insert({ name: 'Anonymous', jsonList: [] });
152
+ await tableUsers.insert({ name: 'Obi1', jsonObject: { a: { b: 3 } } });
153
+ await tableUsers.insert({ name: 'Obi2', jsonObject: { a: { b: [3, 4, 5, 6] }, d: 'c', g: 'e' } });
154
+ //@formatter:on
155
+
156
+ let res;
157
+
158
+ res = await tableUsers.find({ '"jsonObject" ?|': ['d', 'f'] }, { fields: ['name'] });
159
+ expect(res.map(r => r.name)).toEqual(['Obi2']);
160
+
161
+ res = await tableUsers.find({ 'jsonList @>': ['sport'] }, { fields: ['name'] }); //=>
162
+ expect(res.map(r => r.name)).toEqual(['Somebody']);
163
+
164
+ res = await tableUsers.find({ 'jsonList <@': ['sport', 'tech', 'season'] }, { fields: ['name'] }); //=>
165
+ expect(res.map(r => r.name)).toEqual(['Somebody', 'Anonymous']);
166
+
167
+ res = await tableUsers.find({ 'jsonList ?': 0 }, { fields: ['name'] }); //=> doesnt work
168
+ expect(res.map(r => r.name)).toEqual([]);
169
+
170
+ res = await tableUsers.find({ 'jsonList ?': '0' }, { fields: ['name'] }); //=> doesnt work
171
+ expect(res.map(r => r.name)).toEqual([]);
172
+
173
+ res = await tableUsers.find({ 'jsonObject -> a': { b: 3 } }, { fields: ['name'] });
174
+ expect(res.map(r => r.name)).toEqual(['Obi1']);
175
+
176
+ res = await tableUsers.find({ "jsonObject -> 'a'": { b: 3 } }, { fields: ['name'] });
177
+ expect(res.map(r => r.name)).toEqual(['Obi1']);
178
+
179
+ res = await tableUsers.find({ 'jsonList ->> 0': 'art' }, { fields: ['name'] });
180
+ expect(res.map(r => r.name)).toEqual(['Anybody']);
181
+
182
+ res = await tableUsers.find({ 'jsonObject ->> a': '{"b": 3}' }, { fields: ['name'] }); //->> return as a text
183
+ expect(res.map(r => r.name)).toEqual(['Obi1']);
184
+
185
+ res = await tableUsers.find({ "jsonObject ->> 'a'": '{"b": 3}' }, { fields: ['name'] }); //->> return as a text
186
+ expect(res.map(r => r.name)).toEqual(['Obi1']);
187
+
188
+ res = await tableUsers.find({ "jsonList ->> '0'": 'art' }, { fields: ['name'] }); //=> doesnt work
189
+ expect(res.map(r => r.name)).toEqual([]);
190
+
191
+ res = await tableUsers.find({ "jsonObject #> {a}": { b: 3 } }, { fields: ['name'] });
192
+ expect(res.map(r => r.name)).toEqual(['Obi1']);
193
+
194
+ res = await tableUsers.find({ "jsonObject #>> {a}": '{"b": 3}' }, { fields: ['name'] });
195
+ expect(res.map(r => r.name)).toEqual(['Obi1']);
196
+
197
+ res = await tableUsers.find({ "jsonObject #>> {a,b}": 3 }, { fields: ['name'] });
198
+ expect(res.map(r => r.name)).toEqual(['Obi1']);
199
+
200
+ res = await tableUsers.find({ "jsonObject #>> {a,b,1}": 4 }, { fields: ['name'] });
201
+ expect(res.map(r => r.name)).toEqual(['Obi2']);
202
+
203
+ res = await tableUsers.find({ "jsonObject #>> {a,b,1}": '4' }, { fields: ['name'] });
204
+ expect(res.map(r => r.name)).toEqual(['Obi2']);
205
+ });
206
+
207
+ it("Testing Jsonb list update", async () => {
208
+ await tableUsers.insert({ name: 'Somebody', jsonList: ['sport', 'season'] });
209
+ await tableUsers.update({ name: 'Somebody' }, { jsonList: [{ name: 'sport' }, { name: 'season' }] });
210
+
211
+ let res: any[] = await tableUsers.findAll();
212
+ expect(res.map(r => r.jsonList.map((e: any) => e.name))[0]).toEqual(['sport', 'season']);
213
+ });
214
+
215
+ it("Testing Jsonb list operators", async () => {
216
+ //@formatter:off
217
+ await tableUsers.insert({ name: 'Somebody', jsonObject: { realName: 'somebody', webpage: 's.com' } });
218
+ await tableUsers.insert({ name: 'Anybody', jsonObject: { realName: 'anybody', webpage: 'a.com' } });
219
+ await tableUsers.insert({ name: 'Nobody', jsonObject: { realName: 'nobody', email: 'nobody@nowhere.com' } });
220
+ await tableUsers.insert({ name: 'Noone', jsonObject: null });
221
+ await tableUsers.insert({ name: 'Anonymous', jsonObject: {} });
222
+ //@formatter:on
223
+ let res;
224
+
225
+ res = await tableUsers.find({ 'jsonObject ?': 'email' }, { fields: ['name'] }); //=> has the key ..
226
+ expect(res.map(r => r.name)).toEqual(['Nobody']);
227
+
228
+ res = await tableUsers.find({ 'jsonObject ?&': ['email', 'realName'] }, { fields: ['name'] }); //=> has all key ..
229
+ expect(res.map(r => r.name)).toEqual(['Nobody']);
230
+
231
+ res = await tableUsers.find({ 'jsonObject ?|': ['email', 'webpage'] }, { fields: ['name'] }); //=> has any of the key..
232
+ expect(res.map(r => r.name)).toEqual(['Somebody', 'Anybody', 'Nobody']);
233
+
234
+ res = await tableUsers.find({ 'jsonObject @>': { realName: 'somebody' } }, { fields: ['name'] }); //=> contains substructure
235
+ expect(res.map(r => r.name)).toEqual(['Somebody']);
236
+
237
+ res = await tableUsers.find({ 'jsonObject ->> realName': 'somebody' }, { fields: ['name'] }); //=> has the key + equals to
238
+ expect(res.map(r => r.name)).toEqual(['Somebody']);
239
+
240
+ res = await tableUsers.find({ 'jsonObject ->> \'realName\'': 'somebody' }, { fields: ['name'] }); //=> has the key + equals to
241
+ expect(res.map(r => r.name)).toEqual(['Somebody']);
242
+
243
+ res = await tableUsers.find({ '"jsonObject" ->> \'realName\'': 'somebody' }, { fields: ['name'] }); //=> has the key + equals to
244
+ expect(res.map(r => r.name)).toEqual(['Somebody']);
245
+
246
+ res = await tableUsers.find({ 'jsonObject ->> realName': ['somebody', 'anybody'] }, { fields: ['name'] }); //=> has the key + in array
247
+ expect(res.map(r => r.name)).toEqual(['Somebody', 'Anybody']);
248
+
249
+ res = await tableUsers.find({ 'jsonObject ->> realName like': '%body' }, { fields: ['name'] }); //=> has the key + like
250
+ expect(res.map(r => r.name)).toEqual(['Somebody', 'Anybody', 'Nobody']);
251
+
252
+ res = await tableUsers.find({ 'jsonObject ->> realName ~~': '%body' }, { fields: ['name'] }); //=> has the key + like
253
+ expect(res.map(r => r.name)).toEqual(['Somebody', 'Anybody', 'Nobody']);
254
+
255
+ });
256
+
257
+ it("Test deep jsonb @>", async () => {
258
+ //@formatter:off
259
+ await tableUsers.insert({ name: 'Somebody', jsonObject: { service: { indexing: { by: [1, 2, 3] }, database: true }, paid: true } });
260
+ await tableUsers.insert({ name: 'Anybody', jsonList: [{ realName: 'anyone' }, { realName: 'anybody' }] });
261
+ //@formatter:on
262
+
263
+ let res;
264
+ res = await tableUsers.find({ 'jsonObject @>': { service: { indexing: { by: [1] } }, paid: true } });
265
+ expect(res.map(r => r.name)).toEqual(['Somebody']);
266
+
267
+ res = await tableUsers.find({ 'jsonList @>': [{ realName: 'anybody' }] });
268
+ expect(res.map(r => r.name)).toEqual(['Anybody']);
269
+ });
270
+
271
+
272
+ it("Testing is (not) null", async () => {
273
+ await tableUsers.insert({ name: 'Noone', jsonObject: null });
274
+ await tableUsers.insert({ name: 'Anonymous', jsonObject: {} });
275
+
276
+ let count;
277
+
278
+ count = await tableUsers.count({ 'jsonObject !': null });
279
+ expect(count).toEqual(1);
280
+
281
+ count = await tableUsers.count({ 'jsonObject': null });
282
+ expect(count).toEqual(1);
283
+
284
+ count = await tableUsers.count({});
285
+ expect(count).toEqual(2);
286
+ });
287
+
288
+ it("Test regexp ~,~*,!~,!~*", async () => {
289
+ await tableUsers.insert({ name: "All' o Phoibe" });
290
+ await tableUsers.insert({ name: "I've got that tune" });
291
+
292
+ let res = await tableUsers.find({ 'name ~': "\\so\\s" });
293
+ expect(res.map(r => r.name)).toEqual(["All' o Phoibe"]);
294
+
295
+ res = await tableUsers.find({ 'name ~*': "\\sO\\s" });
296
+ expect(res.map(r => r.name)).toEqual(["All' o Phoibe"]);
297
+
298
+ res = await tableUsers.find({ 'name !~': "\\so\\s" });
299
+ expect(res.map(r => r.name)).toEqual(["I've got that tune"]);
300
+
301
+ res = await tableUsers.find({ 'name !~*': "\\sO\\s" });
302
+ expect(res.map(r => r.name)).toEqual(["I've got that tune"]);
303
+
304
+ });
305
+
306
+ it("Test regexp " +
307
+ "~/~* ANY" +
308
+ "!~/!~* ALL", async () => {
309
+ await tableUsers.insert({ name: "All' o Phoibe" });
310
+ await tableUsers.insert({ name: "I've got that tune" });
311
+
312
+ let res = await tableUsers.find({ 'name ~': ["\\so\\s", '\\d+'] });
313
+ expect(res.map(r => r.name)).toEqual(["All' o Phoibe"]);
314
+
315
+ res = await tableUsers.find({ 'name ~*': ["\\sO\\s", '\\d+'] });
316
+ expect(res.map(r => r.name)).toEqual(["All' o Phoibe"]);
317
+
318
+ res = await tableUsers.find({ 'name !~': ["\\so\\s", '\\d+'] });
319
+ expect(res.map(r => r.name)).toEqual(["I've got that tune"]);
320
+
321
+ res = await tableUsers.find({ 'name !~*': ["\\sO\\s", '\\d+'] });
322
+ expect(res.map(r => r.name)).toEqual(["I've got that tune"]);
323
+
324
+ });
325
+
326
+
327
+ it("Test like ~~, like, ~~*, ilike, !~~, not like, !~~*, not ilike", async () => {
328
+ await tableUsers.insert({ name: 'Iced lemonade' });
329
+ await tableUsers.insert({ name: 'Cucumber pear juice' });
330
+ let res;
331
+
332
+ res = await tableUsers.find({ 'name ~~': '%lemon%' });
333
+ expect(res.map(r => r.name)).toEqual(['Iced lemonade']);
334
+
335
+ res = await tableUsers.find({ 'name like': '%lemon%' });
336
+ expect(res.map(r => r.name)).toEqual(['Iced lemonade']);
337
+
338
+ res = await tableUsers.find({ 'name ~~*': '%LEMON%' });
339
+ expect(res.map(r => r.name)).toEqual(['Iced lemonade']);
340
+
341
+ res = await tableUsers.find({ 'name ilike': '%LEMON%' });
342
+ expect(res.map(r => r.name)).toEqual(['Iced lemonade']);
343
+
344
+ res = await tableUsers.find({ 'name !~~': '%lemon%' });
345
+ expect(res.map(r => r.name)).toEqual(['Cucumber pear juice']);
346
+
347
+ res = await tableUsers.find({ 'name not like': '%lemon%' });
348
+ expect(res.map(r => r.name)).toEqual(['Cucumber pear juice']);
349
+
350
+ res = await tableUsers.find({ 'name !~~*': '%LEMON%' });
351
+ expect(res.map(r => r.name)).toEqual(['Cucumber pear juice']);
352
+
353
+ res = await tableUsers.find({ 'name not ilike': '%LEMON%' });
354
+ expect(res.map(r => r.name)).toEqual(['Cucumber pear juice']);
355
+
356
+ });
357
+
358
+ it("Test " +
359
+ "like/~~/ilike/~~* ANY(), " +
360
+ "not like/!~~/not ilike/!~~* ALL()", async () => {
361
+
362
+ await tableUsers.insert({ name: 'Iced lemonade' });
363
+ await tableUsers.insert({ name: 'Cucumber pear juice' });
364
+ let res;
365
+
366
+ res = await tableUsers.find({ 'name ~~': ['BB', '%lemon%'] });
367
+ expect(res.map(r => r.name)).toEqual(['Iced lemonade']);
368
+
369
+ res = await tableUsers.find({ 'name like': ['BB', '%lemon%'] });
370
+ expect(res.map(r => r.name)).toEqual(['Iced lemonade']);
371
+
372
+ res = await tableUsers.find({ 'name ~~*': ['bb', '%LEMON%'] });
373
+ expect(res.map(r => r.name)).toEqual(['Iced lemonade']);
374
+
375
+ res = await tableUsers.find({ 'name ilike': ['bb', '%LEMON%'] });
376
+ expect(res.map(r => r.name)).toEqual(['Iced lemonade']);
377
+
378
+ res = await tableUsers.find({ 'name !~~': ['BB', '%lemon%'] });
379
+ expect(res.map(r => r.name)).toEqual(['Cucumber pear juice']);
380
+
381
+ res = await tableUsers.find({ 'name not like': ['BB', '%lemon%'] });
382
+ expect(res.map(r => r.name)).toEqual(['Cucumber pear juice']);
383
+
384
+ res = await tableUsers.find({ 'name !~~*': ['bb', '%LEMON%'] });
385
+ expect(res.map(r => r.name)).toEqual(['Cucumber pear juice']);
386
+
387
+ res = await tableUsers.find({ 'name not ilike': ['bb', '%LEMON%'] });
388
+ expect(res.map(r => r.name)).toEqual(['Cucumber pear juice']);
389
+ });
390
+
391
+ it("Special added operators =*, icontains", async () => {
392
+ await tableUsers.insert({ name: 'Iced lemonade' });
393
+ await tableUsers.insert({ name: 'Cucumber pear juice', textList: ['good', 'better', 'best'] });
394
+ let res;
395
+
396
+ res = await tableUsers.find({ 'name =*': 'ICED LEMONADE' });
397
+ expect(res.map(r => r.name)).toEqual(['Iced lemonade']);
398
+
399
+ res = await tableUsers.find({ 'textList icontains': 'GOOD' });
400
+ expect(res.map(r => r.name)).toEqual(['Cucumber pear juice']);
401
+
402
+ res = await tableUsers.find({ 'textList =*': 'GOOD' });
403
+ expect(res.map(r => r.name)).toEqual(['Cucumber pear juice']);
404
+
405
+ res = await tableUsers.find({ 'textList &&*': ['GOOD', 'Bad'] });
406
+ expect(res.map(r => r.name)).toEqual(['Cucumber pear juice']);
407
+ });
408
+
409
+
410
+ });
411
+
412
+ /*
413
+
414
+ console.log('--- TEST 17 jsonb [{}] update ---------');
415
+ res = await pdb.schemas['dev']['fsZones'].updateAndGetOne({id:14}, {zoneAdmins:[], buildings:[]});
416
+ if (!Array.isArray(res.buildings) || !Array.isArray(res.zoneAdmins)) {
417
+ throw Error('both should be an array!');
418
+ }
419
+ console.log(util.inspect(res, false, null));
420
+
421
+ console.log('--- TEST 18 array<int> ---------');
422
+ dbTable = pdb.schemas['dev']['fsZones'];
423
+ res = await dbTable.findAll();
424
+ console.log(util.inspect(res, false, null));
425
+
426
+
427
+ console.log('--- TEST 20 parsing array fields ----------');
428
+ res = await pdb.schemas['dev']['chemicals'].updateAndGetOne({id:167}, {extMedia:["test",'a b', 'c,d', '"e,f"','', null, null]});
429
+ console.log(res);
430
+
431
+
432
+ await pdb.close();
433
+ console.log('end');
434
+
435
+ })().catch(e => console.error(e.message, e.stack));
436
+ */
437
+
438
+ /**
439
+ * {,ads,"asdf""fd,",",3," "}
440
+ *
441
+ s = ',ads,"asdf""fd,",",3," "';
442
+ e =
443
+ e.exec(s)
444
+ */
445
+ function parseComplexTypeArray(str: string) {
446
+ let list = JSON.parse('[' + str.substring(1, str.length - 1) + ']');
447
+
448
+ let result = [];
449
+ for (let elementStr of list) {
450
+ result.push(parseComplexType(elementStr));
451
+ }
452
+ return result;
453
+ }
454
+
455
+ function parseComplexType(str: string) {
456
+ //cut of '(', ')'
457
+ str = str.substring(1, str.length - 1);
458
+ let e = /"((?:[^"]|"")*)"(?:,|$)|([^,]*)(?:,|$)/g;
459
+ let valList = [];
460
+ let parsingResult;
461
+ let valStr;
462
+ let hasNextValue;
463
+ /**
464
+ * parsingResult.index<str.length check for finish is not reliable
465
+ * as if the last value is null it goes undetected, e.g. (,,)
466
+ */
467
+ do {
468
+ parsingResult = e.exec(str);
469
+ if (!parsingResult) break;
470
+ valStr = (parsingResult[0] == '' || parsingResult[0] == ',' || parsingResult[2] == 'null') ? null : parsingResult[1] || parsingResult[2];
471
+ if (parsingResult[0] == '"",' || parsingResult[0] == '""') {
472
+ valStr = '';
473
+ }
474
+ valList.push(valStr ? valStr.replace(/""/g, '"') : valStr);
475
+ hasNextValue = parsingResult[0].substring(parsingResult[0].length - 1, parsingResult[0].length) == ',';
476
+ } while (hasNextValue);
477
+ return valList;
478
+ }
@@ -1,15 +1,11 @@
1
- const util = require("util");
2
-
3
- function escapeForLike(s) {
4
- return s.replace(/([\\%_])/g,'\\$1');
5
- }
1
+ import { pgUtils } from "./pgUtils";
6
2
 
7
3
  export default {
8
- // lowercase comparison
9
- '=*': {operator: '=', mutator: (s:string) => s.toLocaleLowerCase(), fieldMutator: s => util.format('LOWER("%s")',s)},
4
+ /** lowercase comparison */
5
+ '=*': {operator: '=', mutator: (s:string):string => s.toLocaleLowerCase(), fieldMutator: (s:string) => `LOWER("${s}")`},
10
6
 
11
- // caseless contains for string
12
- 'icontains': {operator: 'ILIKE', mutator: s => '%' + escapeForLike(s) + '%'},
7
+ /** case insensitive contains for string */
8
+ 'icontains': {operator: 'ILIKE', mutator: (s:string):string => '%' + pgUtils.escapeForLike(s) + '%'},
13
9
 
14
10
  // contains for array
15
11
  //'acontains': value = ANY("columnName")
@@ -25,36 +21,63 @@ export default {
25
21
  '<>': {operator: '<>'},
26
22
  'is not': {operator: 'IS NOT'},
27
23
 
28
- // free text search
24
+ /** free text search */
29
25
  '@@': {operator: '@@'}, //value can be {lang:string, query:string} or simply string (defaults to english)
30
26
 
31
- // jsonb / array
32
- '@>': {operator: '@>'}, //contains ARRAY[1,4,3] @> ARRAY[3,1] => true
33
- '<@': {operator: '<@'}, //is contained by ARRAY[2,7] <@ ARRAY[1,7,4,2,6] => true
34
- '&&': {operator: '&&'}, //overlap (have elements in common) ARRAY[1,4,3] && ARRAY[2,1] => true
35
- '&&*': {operator: '&&', mutator: (s:string) => s.toLocaleLowerCase(), fieldMutator: f => util.format('LOWER("%s")', f)},
27
+ /**
28
+ * jsonb / array
29
+ * contains ARRAY[1,4,3] @> ARRAY[3,1] => true
30
+ */
31
+ '@>': {operator: '@>'},
32
+ /**
33
+ * jsonb / array
34
+ * is contained by ARRAY[2,7] <@ ARRAY[1,7,4,2,6] => true
35
+ */
36
+ '<@': {operator: '<@'},
37
+ /**
38
+ * jsonb / array
39
+ * overlap (have elements in common) ARRAY[1,4,3] && ARRAY[2,1] => true
40
+ */
41
+ '&&': {operator: '&&'},
42
+ /**
43
+ * jsonb / array
44
+ * case insensitive overlap (have elements in common) ARRAY[1,4,3] && ARRAY[2,1] => true
45
+ */
46
+ '&&*': {operator: '&&', mutator: (s:string) => s.toLocaleLowerCase(), fieldMutator: (f:string) => `LOWER("${f}")`},
36
47
 
37
- // jsonb
38
- '?': {operator: '?'}, //exists key
39
- '?|': {operator: '?|'}, //exists any keys
40
- '?&': {operator: '?&'}, //exists all keys
48
+ /** jsonb exists key */
49
+ '?': {operator: '?'},
50
+ /** jsonb exists any keys */
51
+ '?|': {operator: '?|'},
52
+ /** jsonb exists all keys */
53
+ '?&': {operator: '?&'},
41
54
 
42
55
 
43
- // pattern matching
56
+ /** LIKE */
44
57
  '~~': {operator: 'LIKE'},
58
+ /** LIKE */
45
59
  'like': {operator: 'LIKE'},
60
+ /** NOT LIKE */
46
61
  '!~~': {operator: 'NOT LIKE'},
62
+ /** NOT LIKE */
47
63
  'not like': {operator: 'NOT LIKE'},
64
+ /** ILIKE */
48
65
  '~~*': {operator: 'ILIKE'},
66
+ /** ILIKE */
49
67
  'ilike': {operator: 'ILIKE'},
68
+ /** NOT ILIKE */
50
69
  '!~~*': {operator: 'NOT ILIKE'},
70
+ /** NOT ILIKE */
51
71
  'not ilike': {operator: 'NOT ILIKE'},
72
+ /** SIMILAR TO */
52
73
  'similar to': {operator: 'SIMILAR TO'},
74
+ /** NOT SIMILAR TO */
53
75
  'not similar to': {operator: 'NOT SIMILAR TO'},
54
- // regexp
76
+ /** regexp matching */
55
77
  '~': {operator: '~'},
56
78
  '!~': {operator: '!~'},
57
- '~*': {operator: '~*'}, //Matches regular expression, case insensitive
79
+ /** regexp matching, case insensitive */
80
+ '~*': {operator: '~*'},
58
81
  '!~*': {operator: '!~*'},
59
82
  // distinct
60
83
  'is distinct from': {operator: 'IS DISTINCT FROM'},
package/src/pgSchema.ts CHANGED
@@ -1,14 +1,15 @@
1
- import {QueryAble} from "./queryAble";
2
- import {PgDb} from "./pgDb";
3
- import {PgTable} from "./pgTable";
1
+ import { QueryAble } from "./queryAble";
2
+ import { IPgDb } from "./pgDbInterface";
3
+ import { IPgTable } from "./pgTableInterface";
4
+ import { IPgSchema } from "./pgSchemaInterface";
4
5
 
5
- export class PgSchema extends QueryAble {
6
- schema:PgSchema;
7
- tables:{[name:string]:PgTable<any>} = {};
8
- fn: {[name:string]:(...any)=>any} = {};
9
- [name:string]:any|PgTable<any>;
6
+ export class PgSchema extends QueryAble implements IPgSchema {
7
+ schema: IPgSchema;
8
+ tables: { [name: string]: IPgTable<any> } = {};
9
+ fn: { [name: string]: (...args: any[]) => any } = {};
10
+ [name: string]: any | IPgTable<any>;
10
11
 
11
- constructor(public db:PgDb, public schemaName:string) {
12
+ constructor(public db: IPgDb, public schemaName: string) {
12
13
  super();
13
14
  this.schema = this;
14
15
  }