orange-orm 4.2.0-beta.6 → 4.3.0-beta.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.
package/docs/changelog.md CHANGED
@@ -1,4 +1,6 @@
1
1
  ## Changelog
2
+ __4.2.0__
3
+ Improved performance.
2
4
  __4.1.4__
3
5
  Better error message when running over http.
4
6
  __4.1.3__
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orange-orm",
3
- "version": "4.2.0-beta.6",
3
+ "version": "4.3.0-beta.0",
4
4
  "main": "./src/index.js",
5
5
  "browser": "./src/client/index.mjs",
6
6
  "bin": {
@@ -63,6 +63,7 @@
63
63
  "glob": "^10.3.4",
64
64
  "module-definition": "^4.0.0",
65
65
  "node-cls": "^1.0.5",
66
+ "postgres": "^3.4.4",
66
67
  "promise": "^8.0.3",
67
68
  "rfdc": "^1.2.0",
68
69
  "uuid": "^8.3.2"
@@ -71,6 +72,7 @@
71
72
  "msnodesqlv8": "^4.1.0",
72
73
  "mysql2": "^2.2.5 || ^3.9.4",
73
74
  "oracledb": "^6.3.0",
75
+ "postgres": "^3.4.4",
74
76
  "pg": "^8.5.1",
75
77
  "pg-native": "^3.0.0",
76
78
  "pg-query-stream": "^3.3.2",
@@ -78,6 +80,9 @@
78
80
  "tedious": "^15.1.2 || ^16.0.0 || ^18.1.0"
79
81
  },
80
82
  "peerDependenciesMeta": {
83
+ "postgres": {
84
+ "optional": true
85
+ },
81
86
  "pg": {
82
87
  "optional": true
83
88
  },
@@ -114,6 +119,7 @@
114
119
  "mysql2": "^3.9.4",
115
120
  "oracledb": "^6.3.0",
116
121
  "owasp-dependency-check": "^0.0.21",
122
+ "postgres": "^3.4.4",
117
123
  "pg": "^8.5.1",
118
124
  "pg-query-stream": "^3.3.2",
119
125
  "rollup": "^2.52.7",
@@ -815,7 +815,7 @@ var fastJsonPatch = /*#__PURE__*/Object.freeze({
815
815
 
816
816
  var require$$0 = /*@__PURE__*/getAugmentedNamespace(fastJsonPatch);
817
817
 
818
- function dateToISOString$1(date) {
818
+ function dateToISOString$2(date) {
819
819
  let tzo = -date.getTimezoneOffset();
820
820
  let dif = tzo >= 0 ? '+' : '-';
821
821
 
@@ -839,9 +839,9 @@ function dateToISOString$1(date) {
839
839
  ':' + pad(tzo % 60);
840
840
  }
841
841
 
842
- var dateToISOString_1 = dateToISOString$1;
842
+ var dateToISOString_1 = dateToISOString$2;
843
843
 
844
- let dateToISOString = dateToISOString_1;
844
+ let dateToISOString$1 = dateToISOString_1;
845
845
  const isNode = (typeof window === 'undefined');
846
846
 
847
847
  function stringify$4(value) {
@@ -853,7 +853,7 @@ function replacer(key, value) {
853
853
  return value.toString('base64');
854
854
  // @ts-ignore
855
855
  else if (value instanceof Date && !isNaN(value))
856
- return dateToISOString(value);
856
+ return dateToISOString$1(value);
857
857
  else
858
858
  return value;
859
859
  }
@@ -1587,6 +1587,57 @@ var createPatch$1 = function createPatch(original, dto, options) {
1587
1587
 
1588
1588
  };
1589
1589
 
1590
+ let dateToISOString = dateToISOString_1;
1591
+
1592
+ function cloneFromDbFast(obj) {
1593
+ if (obj === null || typeof obj !== 'object')
1594
+ return obj;
1595
+ if (Array.isArray(obj)) {
1596
+ const arrClone = [];
1597
+ for (let i = 0; i < obj.length; i++) {
1598
+ arrClone[i] = cloneFromDbFast(obj[i]);
1599
+ }
1600
+ return arrClone;
1601
+ }
1602
+ const clone = {};
1603
+ const keys = Object.keys(obj);
1604
+ for (let i = 0; i < keys.length; i++) {
1605
+ const key = keys[i];
1606
+ clone[key] = cloneFromDbFast(obj[key]);
1607
+ }
1608
+ return clone;
1609
+ }
1610
+
1611
+ function cloneRegular(obj) {
1612
+ if (obj === null || typeof obj !== 'object')
1613
+ return obj;
1614
+ if (Array.isArray(obj)) {
1615
+ const arrClone = [];
1616
+ for (let i = 0; i < obj.length; i++) {
1617
+ arrClone[i] = cloneRegular(obj[i]);
1618
+ }
1619
+ return arrClone;
1620
+ }
1621
+ else if (obj instanceof Date && !isNaN(obj))
1622
+ return dateToISOString(obj);
1623
+ const clone = {};
1624
+ const keys = Object.keys(obj);
1625
+ for (let i = 0; i < keys.length; i++) {
1626
+ const key = keys[i];
1627
+ clone[key] = cloneRegular(obj[key]);
1628
+ }
1629
+ return clone;
1630
+ }
1631
+
1632
+ function cloneFromDb$1(obj, isFast) {
1633
+ if (isFast)
1634
+ return cloneFromDbFast(obj);
1635
+ else
1636
+ return cloneRegular(obj);
1637
+ }
1638
+
1639
+ var cloneFromDb_1 = cloneFromDb$1;
1640
+
1590
1641
  function bind(fn, thisArg) {
1591
1642
  return function wrap() {
1592
1643
  return fn.apply(thisArg, arguments);
@@ -3607,7 +3658,7 @@ function isAbsoluteURL(url) {
3607
3658
  */
3608
3659
  function combineURLs(baseURL, relativeURL) {
3609
3660
  return relativeURL
3610
- ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
3661
+ ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
3611
3662
  : baseURL;
3612
3663
  }
3613
3664
 
@@ -4241,7 +4292,7 @@ function mergeConfig(config1, config2) {
4241
4292
  return config;
4242
4293
  }
4243
4294
 
4244
- const VERSION = "1.6.3";
4295
+ const VERSION = "1.6.2";
4245
4296
 
4246
4297
  const validators$1 = {};
4247
4298
 
@@ -5298,6 +5349,7 @@ var axiosInterceptor = function create() {
5298
5349
 
5299
5350
  const createPatch = createPatch$1;
5300
5351
  const stringify = stringify_1;
5352
+ const cloneFromDb = cloneFromDb_1;
5301
5353
  const netAdapter = netAdapter_1;
5302
5354
  const toKeyPositionMap = toKeyPositionMap_1;
5303
5355
  const rootMap = new WeakMap();
@@ -5524,7 +5576,7 @@ function rdbClient(options = {}) {
5524
5576
  let args = [_, strategy].concat(Array.prototype.slice.call(arguments).slice(2));
5525
5577
  let rows = await getManyCore.apply(null, args);
5526
5578
  await metaPromise;
5527
- return proxify(rows, strategy, {fastStringify : true});
5579
+ return proxify(rows, strategy, true);
5528
5580
  }
5529
5581
 
5530
5582
  async function groupBy(strategy) {
@@ -5556,7 +5608,7 @@ function rdbClient(options = {}) {
5556
5608
  await metaPromise;
5557
5609
  if (rows.length === 0)
5558
5610
  return;
5559
- return proxify(rows[0], strategy, {fastStringify : true});
5611
+ return proxify(rows[0], strategy, true);
5560
5612
  }
5561
5613
 
5562
5614
  async function getById() {
@@ -5744,14 +5796,14 @@ function rdbClient(options = {}) {
5744
5796
  }
5745
5797
 
5746
5798
 
5747
- function proxify(itemOrArray, strategy, options) {
5799
+ function proxify(itemOrArray, strategy, fast) {
5748
5800
  if (Array.isArray(itemOrArray))
5749
- return proxifyArray(itemOrArray, strategy, options);
5801
+ return proxifyArray(itemOrArray, strategy, fast);
5750
5802
  else
5751
- return proxifyRow(itemOrArray, strategy, options);
5803
+ return proxifyRow(itemOrArray, strategy, fast);
5752
5804
  }
5753
5805
 
5754
- function proxifyArray(array, strategy, { fastStringify } = {}) {
5806
+ function proxifyArray(array, strategy, fast) {
5755
5807
  let _array = array;
5756
5808
  if (_reactive)
5757
5809
  array = _reactive(array);
@@ -5778,8 +5830,11 @@ function rdbClient(options = {}) {
5778
5830
  }
5779
5831
 
5780
5832
  };
5781
- let innerProxy = new Proxy(array, handler);
5782
- rootMap.set(array, { json: fastStringify ? JSON.stringify(array) : stringify(array), strategy, originalArray: [...array] });
5833
+
5834
+ let watcher = onChange(array, () => {
5835
+ rootMap.set(array, { json: cloneFromDb(array, fast), strategy, originalArray: [...array] });
5836
+ });
5837
+ let innerProxy = new Proxy(watcher, handler);
5783
5838
  if (strategy !== undefined) {
5784
5839
  const { limit, ...cleanStrategy } = { ...strategy };
5785
5840
  fetchingStrategyMap.set(array, cleanStrategy);
@@ -5787,18 +5842,18 @@ function rdbClient(options = {}) {
5787
5842
  return innerProxy;
5788
5843
  }
5789
5844
 
5790
- function proxifyRow(row, strategy, { fastStringify } = {}) {
5845
+ function proxifyRow(row, strategy, fast) {
5791
5846
  let handler = {
5792
5847
  get(_target, property,) {
5793
5848
  if (property === 'save' || property === 'saveChanges') //call server then acceptChanges
5794
5849
  return saveRow.bind(null, row);
5795
- else if (property === 'delete') //call server then remove from jsonMap and original
5850
+ else if (property === 'delete') //call server then remove from json and original
5796
5851
  return deleteRow.bind(null, row);
5797
5852
  else if (property === 'refresh') //refresh from server then acceptChanges
5798
5853
  return refreshRow.bind(null, row);
5799
- else if (property === 'clearChanges') //refresh from jsonMap, update original if present
5854
+ else if (property === 'clearChanges') //refresh from json, update original if present
5800
5855
  return clearChangesRow.bind(null, row);
5801
- else if (property === 'acceptChanges') //remove from jsonMap
5856
+ else if (property === 'acceptChanges') //remove from json
5802
5857
  return acceptChangesRow.bind(null, row);
5803
5858
  else if (property === 'toJSON')
5804
5859
  return () => {
@@ -5811,8 +5866,10 @@ function rdbClient(options = {}) {
5811
5866
  }
5812
5867
 
5813
5868
  };
5814
- let innerProxy = new Proxy(row, handler);
5815
- rootMap.set(row, { json: fastStringify ? JSON.stringify(row) : stringify(row), strategy });
5869
+ let watcher = onChange(row, () => {
5870
+ rootMap.set(row, { json: cloneFromDb(row, fast), strategy });
5871
+ });
5872
+ let innerProxy = new Proxy(watcher, handler);
5816
5873
  fetchingStrategyMap.set(row, strategy);
5817
5874
  return innerProxy;
5818
5875
  }
@@ -5882,12 +5939,14 @@ function rdbClient(options = {}) {
5882
5939
 
5883
5940
  async function saveArray(array, concurrencyOptions, strategy) {
5884
5941
  let deduceStrategy = false;
5885
- let { json } = rootMap.get(array);
5942
+ let json = rootMap.get(array)?.json;
5943
+ if (!json)
5944
+ return;
5886
5945
  strategy = extractStrategy({ strategy }, array);
5887
5946
  strategy = extractFetchingStrategy(array, strategy);
5888
5947
 
5889
5948
  let meta = await getMeta();
5890
- const patch = createPatch(JSON.parse(json), array, meta);
5949
+ const patch = createPatch(json, array, meta);
5891
5950
  if (patch.length === 0)
5892
5951
  return;
5893
5952
  let body = stringify({ patch, options: { strategy, ...tableOptions, ...concurrencyOptions, deduceStrategy } });
@@ -5902,7 +5961,7 @@ function rdbClient(options = {}) {
5902
5961
  let insertedPositions = getInsertedRowsPosition(array);
5903
5962
  let { changed, strategy: newStrategy } = await p;
5904
5963
  copyIntoArray(changed, array, [...insertedPositions, ...updatedPositions]);
5905
- rootMap.set(array, { json: stringify(array), strategy: newStrategy, originalArray: [...array] });
5964
+ rootMap.set(array, { json: cloneFromDb(array), strategy: newStrategy, originalArray: [...array] });
5906
5965
  }
5907
5966
 
5908
5967
  async function patch(patch, concurrencyOptions, strategy) {
@@ -5962,7 +6021,7 @@ function rdbClient(options = {}) {
5962
6021
  return options.strategy;
5963
6022
  if (obj) {
5964
6023
  let context = rootMap.get(obj);
5965
- if (context.strategy !== undefined) {
6024
+ if (context?.strategy !== undefined) {
5966
6025
  // @ts-ignore
5967
6026
  let { limit, ...strategy } = { ...context.strategy };
5968
6027
  return strategy;
@@ -5981,14 +6040,18 @@ function rdbClient(options = {}) {
5981
6040
  }
5982
6041
 
5983
6042
  function clearChangesArray(array) {
5984
- let { json } = rootMap.get(array);
5985
- let old = JSON.parse(json);
6043
+ let json = rootMap.get(array)?.json;
6044
+ if (!json)
6045
+ return;
6046
+ let old = cloneFromDb(json);
5986
6047
  array.splice(0, old.length, ...old);
5987
6048
  }
5988
6049
 
5989
6050
  function acceptChangesArray(array) {
5990
6051
  const map = rootMap.get(array);
5991
- map.json = stringify(array);
6052
+ if (!map)
6053
+ return;
6054
+ map.json = cloneFromDb(array);
5992
6055
  map.originalArray = [...array];
5993
6056
  }
5994
6057
 
@@ -6001,7 +6064,7 @@ function rdbClient(options = {}) {
6001
6064
  let adapter = netAdapter(url, tableName, { axios: axiosInterceptor, tableOptions });
6002
6065
  let { strategy } = await adapter.patch(body);
6003
6066
  array.length = 0;
6004
- rootMap.set(array, { jsonMap: stringify(array), strategy });
6067
+ rootMap.set(array, { json: cloneFromDb(array), strategy });
6005
6068
  }
6006
6069
 
6007
6070
  function setMapValue(rowsMap, keys, row, index) {
@@ -6064,7 +6127,7 @@ function rdbClient(options = {}) {
6064
6127
  array.splice(i + offset, 1);
6065
6128
  offset--;
6066
6129
  }
6067
- rootMap.set(array, { json: stringify(array), strategy, originalArray: [...array] });
6130
+ rootMap.set(array, { json: cloneFromDb(array), strategy, originalArray: [...array] });
6068
6131
  fetchingStrategyMap.set(array, strategy);
6069
6132
  }
6070
6133
 
@@ -6085,12 +6148,12 @@ function rdbClient(options = {}) {
6085
6148
  strategy = extractStrategy({ strategy }, row);
6086
6149
  strategy = extractFetchingStrategy(row, strategy);
6087
6150
 
6088
- let { json } = rootMap.get(row);
6151
+ let json = rootMap.get(row)?.json;
6089
6152
  if (!json)
6090
6153
  return;
6091
6154
  let meta = await getMeta();
6092
6155
 
6093
- let patch = createPatch([JSON.parse(json)], [row], meta);
6156
+ let patch = createPatch([json], [row], meta);
6094
6157
  if (patch.length === 0)
6095
6158
  return;
6096
6159
 
@@ -6099,7 +6162,7 @@ function rdbClient(options = {}) {
6099
6162
  let adapter = netAdapter(url, tableName, { axios: axiosInterceptor, tableOptions });
6100
6163
  let { changed, strategy: newStrategy } = await adapter.patch(body);
6101
6164
  copyInto(changed, [row]);
6102
- rootMap.set(row, { json: stringify(row), strategy: newStrategy });
6165
+ rootMap.set(row, { json: cloneFromDb(row), strategy: newStrategy });
6103
6166
  }
6104
6167
 
6105
6168
  async function refreshRow(row, strategy) {
@@ -6123,20 +6186,23 @@ function rdbClient(options = {}) {
6123
6186
  for (let p in rows[0]) {
6124
6187
  row[p] = rows[0][p];
6125
6188
  }
6126
- rootMap.set(row, { json: stringify(row), strategy });
6189
+ rootMap.set(row, { json: cloneFromDb(row), strategy });
6127
6190
  fetchingStrategyMap.set(row, strategy);
6128
6191
  }
6129
6192
 
6130
6193
  function acceptChangesRow(row) {
6131
- const { strategy } = rootMap.get(row);
6132
- rootMap.set(row, { json: stringify(row), strategy });
6194
+ const data = rootMap.get(row);
6195
+ if (!data)
6196
+ return;
6197
+ const { strategy } = data;
6198
+ rootMap.set(row, { json: cloneFromDb(row), strategy });
6133
6199
  }
6134
6200
 
6135
6201
  function clearChangesRow(row) {
6136
- let { json } = rootMap.get(row);
6202
+ let json = rootMap.get(row)?.json;
6137
6203
  if (!json)
6138
6204
  return;
6139
- let old = JSON.parse(json);
6205
+ let old = cloneFromDb(json);
6140
6206
  for (let p in row) {
6141
6207
  delete row[p];
6142
6208
  }
@@ -6298,6 +6364,38 @@ function column(path, ...previous) {
6298
6364
 
6299
6365
  }
6300
6366
 
6367
+ function onChange(target, onChange) {
6368
+
6369
+ let notified = false;
6370
+ const handler = {
6371
+ get(target, prop, receiver) {
6372
+ const value = Reflect.get(target, prop, receiver);
6373
+ if (typeof value === 'object' && value !== null) {
6374
+ return new Proxy(value, handler);
6375
+ }
6376
+ return value;
6377
+ },
6378
+ set(target, prop, value, receiver) {
6379
+ if (!notified) {
6380
+ notified = true;
6381
+ onChange(JSON.stringify(target));
6382
+ }
6383
+ return Reflect.set(target, prop, value, receiver);
6384
+
6385
+ },
6386
+ deleteProperty(target, prop) {
6387
+ if (!notified) {
6388
+ notified = true;
6389
+ onChange(JSON.stringify(target));
6390
+ }
6391
+ return Reflect.deleteProperty(target, prop);
6392
+ }
6393
+ };
6394
+
6395
+ return new Proxy(target, handler);
6396
+ }
6397
+
6398
+
6301
6399
  var client = rdbClient();
6302
6400
 
6303
6401
  export { client as default };
@@ -0,0 +1,301 @@
1
+ const emptyFilter = require('./emptyFilter');
2
+ const newQuery = require('./getManyDto/newQuery');
3
+ const negotiateRawSqlFilter = require('./table/column/negotiateRawSqlFilter');
4
+ const strategyToSpan = require('./table/strategyToSpan');
5
+ const executeQueries = require('./table/executeQueries');
6
+
7
+ async function getManyDto(table, filter, strategy, spanFromParent) {
8
+ filter = negotiateRawSqlFilter(filter, table);
9
+ if (strategy && strategy.where) {
10
+ let arg = typeof strategy.where === 'function' ? strategy.where(table) : strategy.where;
11
+ filter = filter.and(arg);
12
+ }
13
+
14
+ let span = spanFromParent || strategyToSpan(table, strategy);
15
+ let alias = table._dbName;
16
+
17
+ const query = newQuery(table, filter, span, alias);
18
+ const res = await executeQueries([query]);
19
+ return decode(strategy, span, await res[0]);
20
+ }
21
+
22
+ function newCreateRow(span) {
23
+ let columnsMap = span.columns;
24
+ const columns = span.table._columns.filter(column => !columnsMap || columnsMap.get(column));
25
+ const protoRow = createProto(columns, span);
26
+ const manyNames = [];
27
+
28
+ const c = {};
29
+ c.visitJoin = () => { };
30
+ c.visitOne = () => { };
31
+ c.visitMany = function(leg) {
32
+ manyNames.push(leg.name);
33
+ };
34
+
35
+ span.legs.forEach(onEachLeg);
36
+ return createRow;
37
+
38
+ function onEachLeg(leg) {
39
+ leg.accept(c);
40
+ }
41
+
42
+ function createRow() {
43
+ const obj = Object.create(protoRow);
44
+ for (let i = 0; i < manyNames.length; i++) {
45
+ obj[manyNames[i]] = [];
46
+ }
47
+ return obj;
48
+ }
49
+ }
50
+
51
+ function createProto(columns, span) {
52
+ let obj = {};
53
+ for (let i = 0; i < columns.length; i++) {
54
+ obj[columns[i].alias] = null;
55
+ }
56
+ for (let key in span.aggregates) {
57
+ obj[key] = null;
58
+ }
59
+ const c = {};
60
+
61
+ c.visitJoin = function(leg) {
62
+ obj[leg.name] = null;
63
+ };
64
+ c.visitOne = c.visitJoin;
65
+ c.visitMany = function(leg) {
66
+ obj[leg.name] = null;
67
+ };
68
+
69
+ span.legs.forEach(onEachLeg);
70
+
71
+ function onEachLeg(leg) {
72
+ leg.accept(c);
73
+ }
74
+
75
+ return obj;
76
+ }
77
+
78
+ function hasManyRelations(span) {
79
+ let result;
80
+ const c = {};
81
+ c.visitJoin = () => { };
82
+ c.visitOne = c.visitJoin;
83
+ c.visitMany = function() {
84
+ result = true;
85
+ };
86
+
87
+ span.legs.forEach(onEachLeg);
88
+ return result;
89
+
90
+ function onEachLeg(leg) {
91
+ leg.accept(c);
92
+ }
93
+ }
94
+
95
+ async function decode(strategy, span, rows, keys = rows.length > 0 ? Object.keys(rows[0]) : []) {
96
+ const table = span.table;
97
+ let columnsMap = span.columns;
98
+ const columns = table._columns.filter(column => !columnsMap || columnsMap.get(column));
99
+ const rowsLength = rows.length;
100
+ const columnsLength = columns.length;
101
+ const primaryColumns = table._primaryColumns;
102
+ const primaryColumnsLength = primaryColumns.length;
103
+ const rowsMap = new Map();
104
+ const fkIds = new Array(rows.length);
105
+ const getIds = createGetIds();
106
+ const aggregateKeys = Object.keys(span.aggregates);
107
+
108
+ const outRows = new Array(rowsLength);
109
+ const createRow = newCreateRow(span);
110
+ const shouldCreateMap = hasManyRelations(span);
111
+ for (let i = 0; i < rowsLength; i++) {
112
+ const row = rows[i];
113
+ let outRow = createRow();
114
+ let pkWithNullCount = 0;
115
+ for (let j = 0; j < primaryColumnsLength; j++) {
116
+ if (row[keys[j]] === null)
117
+ pkWithNullCount++;
118
+ if (pkWithNullCount === primaryColumnsLength) {
119
+ outRow = null;
120
+ break;
121
+ }
122
+ const column = columns[j];
123
+ outRow[column.alias] = column.decode(row[keys[j]]);
124
+ }
125
+
126
+ outRows[i] = outRow;
127
+ if (shouldCreateMap) {
128
+ fkIds[i] = getIds(outRow);
129
+ addToMap(rowsMap, primaryColumns, outRow);
130
+ }
131
+ }
132
+ span._rowsMap = rowsMap;
133
+ span._ids = fkIds;
134
+ const manyPromise = decodeManyRelations(strategy, span, rows, outRows, keys);
135
+
136
+ for (let i = 0; i < rowsLength; i++) {
137
+ const row = rows[i];
138
+ let outRow = outRows[i];
139
+ if (outRow === null)
140
+ continue;
141
+ for (let j = primaryColumnsLength; j < columnsLength; j++) {
142
+ const column = columns[j];
143
+ outRow[column.alias] = column.decode(row[keys[j]]);
144
+ }
145
+
146
+ for (let j = 0; j < aggregateKeys.length; j++) {
147
+ const key = aggregateKeys[j];
148
+ const parse = span.aggregates[key].column?.decode || Number.parseFloat;
149
+ outRow[key] = parse(row[keys[j+columnsLength]]);
150
+ }
151
+ }
152
+
153
+
154
+ keys.splice(0, columnsLength + aggregateKeys.length);
155
+
156
+ await decodeRelations(strategy, span, rows, outRows, keys);
157
+ await manyPromise;
158
+ return outRows;
159
+
160
+
161
+ function createGetIds() {
162
+ const primaryColumns = table._primaryColumns;
163
+ const length = primaryColumns.length;
164
+ if (length === 1) {
165
+ const alias = table._primaryColumns[0].alias;
166
+ return (row) => row[alias];
167
+ }
168
+ else
169
+ return (row) => {
170
+ const result = new Array(length);
171
+ for (let i = 0; i < length; i++) {
172
+ result[i] = row[primaryColumns[i].alias];
173
+ }
174
+ return result;
175
+ };
176
+ }
177
+
178
+ }
179
+
180
+ async function decodeManyRelations(strategy, span, rawRows, resultRows, keys) {
181
+ const promises = [];
182
+ const c = {};
183
+ c.visitJoin = () => {};
184
+ c.visitOne = c.visitJoin;
185
+
186
+ c.visitMany = function(leg) {
187
+ const name = leg.name;
188
+ const table = span.table;
189
+ const relation = table._relations[name];
190
+ const filter = createOneFilter(relation, span._ids);
191
+ const rowsMap = span._rowsMap;
192
+ const p = getManyDto(relation.childTable, filter, strategy[name], leg.span).then(subRows => {
193
+ for (let i = 0; i < subRows.length; i++) {
194
+ const key = leg.columns.map(column => subRows[i][column.alias]);
195
+ const parentRow = getFromMap(rowsMap, table._primaryColumns, key);
196
+ parentRow[name].push(subRows[i]);
197
+ }
198
+ });
199
+ promises.push(p);
200
+ };
201
+
202
+ span.legs.forEach(onEachLeg);
203
+
204
+ function onEachLeg(leg) {
205
+ leg.accept(c);
206
+ }
207
+
208
+ await Promise.all(promises);
209
+ }
210
+ async function decodeRelations(strategy, span, rawRows, resultRows, keys) {
211
+ const promises = [];
212
+ const c = {};
213
+ c.visitJoin = function(leg) {
214
+ const name = leg.name;
215
+ const p = decode(strategy[name], leg.span, rawRows, keys).then((rows) => {
216
+ for (let i = 0; i < rows.length; i++) {
217
+ resultRows[i][name] = rows[i];
218
+ }
219
+ });
220
+ promises.push(p);
221
+ };
222
+
223
+ c.visitOne = c.visitJoin;
224
+
225
+ c.visitMany = () => {};
226
+ // function(leg) {
227
+ // const name = leg.name;
228
+ // const table = span.table;
229
+ // const relation = table._relations[name];
230
+ // const filter = createOneFilter(relation, span._ids);
231
+ // const rowsMap = span._rowsMap;
232
+ // const p = getManyDto(relation.childTable, filter, strategy[name], leg.span).then(subRows => {
233
+ // for (let i = 0; i < subRows.length; i++) {
234
+ // const key = leg.columns.map(column => subRows[i][column.alias]);
235
+ // const parentRow = getFromMap(rowsMap, table._primaryColumns, key);
236
+ // parentRow[name].push(subRows[i]);
237
+ // }
238
+ // });
239
+ // promises.push(p);
240
+ // };
241
+
242
+ span.legs.forEach(onEachLeg);
243
+
244
+ function onEachLeg(leg) {
245
+ leg.accept(c);
246
+ }
247
+
248
+ await Promise.all(promises);
249
+ }
250
+
251
+ function createOneFilter(relation, ids) {
252
+ const columns = relation.joinRelation.columns;
253
+
254
+ if (columns.length === 1)
255
+ return columns[0].in(ids);
256
+
257
+ else
258
+ return createCompositeFilter();
259
+
260
+ function createCompositeFilter() {
261
+ let filter = emptyFilter;
262
+ for(let id of ids) {
263
+ let nextFilter;
264
+ for (let i = 0; i < columns.length; i++) {
265
+ if (nextFilter)
266
+ nextFilter = nextFilter.and(columns[i].eq(id[i]));
267
+ else
268
+ nextFilter = columns[i].eq(id[i]);
269
+ }
270
+ filter = filter.or(nextFilter);
271
+ }
272
+ return filter;
273
+ }
274
+ }
275
+
276
+ function addToMap(map, primaryColumns, row) {
277
+
278
+ const lastIndex = primaryColumns.length - 1;
279
+ for (let i = 0; i < lastIndex; i++) {
280
+ const id = row[primaryColumns[i].alias];
281
+ if (map.has(id))
282
+ map = map.get(id);
283
+ else {
284
+ const next = new Map();
285
+ map.set(id, next);
286
+ map = next;
287
+ }
288
+ }
289
+ map.set(row[primaryColumns[lastIndex].alias], row);
290
+ }
291
+
292
+ function getFromMap(map, primaryColumns, values) {
293
+ const length = primaryColumns.length;
294
+ for (let i = 0; i < length; i++) {
295
+ map = map.get(values[i]);
296
+ }
297
+ return map;
298
+ }
299
+
300
+
301
+ module.exports = getManyDto;
@@ -1,5 +1,5 @@
1
1
  function encodeBoolean(bool) {
2
- return bool.toString();
2
+ return bool;
3
3
  }
4
4
 
5
5
  module.exports = encodeBoolean;
@@ -1,7 +1,7 @@
1
1
  function encodeDate(date) {
2
2
  if (date.toISOString)
3
- return '\'' + date.toISOString() + '\'';
4
- return '\'' + date + '\'';
3
+ return '' + date.toISOString() + '';
4
+ return '' + date + '';
5
5
  }
6
6
 
7
7
  module.exports = encodeDate;
@@ -1,15 +1,16 @@
1
1
  function encode(arg) {
2
- if (Array.isArray(arg))
3
- return new JsonBArrayParam(arg);
4
- else
5
- return arg;
2
+ // if (Array.isArray(arg))
3
+ // return new JsonBArrayParam(arg);
4
+ // else
5
+ return arg;
6
6
  }
7
7
 
8
- class JsonBArrayParam {
9
- constructor(actualArray) { this.actualArray = actualArray; }
10
- toPostgres() {
11
- return JSON.stringify(this.actualArray);
12
- }
13
- }
8
+ //todo
9
+ // class JsonBArrayParam {
10
+ // constructor(actualArray) { this.actualArray = actualArray; }
11
+ // toPostgres() {
12
+ // return JSON.stringify(this.actualArray);
13
+ // }
14
+ // }
14
15
 
15
16
  module.exports = encode;
@@ -4,45 +4,19 @@ var EventEmitter = require('events').EventEmitter;
4
4
 
5
5
  var defaults = require('./defaults');
6
6
  var genericPool = require('../../generic-pool');
7
- var _pg = require('pg');
7
+ var pg = require('postgres');
8
8
 
9
9
  function newPgPool(connectionString, poolOptions) {
10
10
  poolOptions = poolOptions || {};
11
- let pg = poolOptions.native ? _pg.native : _pg;
12
11
  var pool = genericPool.Pool({
13
12
  max: poolOptions.size || poolOptions.poolSize || defaults.poolSize,
14
13
  idleTimeoutMillis: poolOptions.idleTimeout || defaults.poolIdleTimeout,
15
14
  reapIntervalMillis: poolOptions.reapIntervalMillis || defaults.reapIntervalMillis,
16
15
  log: poolOptions.log || defaults.poolLog,
17
16
  create: function(cb) {
18
- var client = new pg.Client(connectionString);
19
- client.connect(function(err) {
20
- if (err) return cb(err, null);
21
-
22
- //handle connected client background errors by emitting event
23
- //via the pg object and then removing errored client from the pool
24
- client.on('error', function(e) {
25
- pool.emit('error', e, client);
26
-
27
- // If the client is already being destroyed, the error
28
- // occurred during stream ending. Do not attempt to destroy
29
- // the client again.
30
- if (!client._destroying) {
31
- pool.destroy(client);
32
- }
33
- });
34
-
35
- // Remove connection from pool on disconnect
36
- client.on('end', function(_e) {
37
- // Do not enter infinite loop between pool.destroy
38
- // and client 'end' event...
39
- if (!client._destroying) {
40
- pool.destroy(client);
41
- }
42
- });
43
- client.poolCount = 0;
44
- return cb(null, client);
45
- });
17
+ var client = pg(connectionString, {max: 1});
18
+ client.poolCount = 0;
19
+ cb(null, client);
46
20
  },
47
21
  destroy: function(client) {
48
22
  client._destroying = true;
@@ -2,7 +2,7 @@ var log = require('../table/log');
2
2
  var replaceParamChar = require('./replaceParamChar');
3
3
 
4
4
  function wrapQuery(connection) {
5
- var runOriginalQuery = connection.query;
5
+ // var runOriginalQuery = connection.query;
6
6
  return runQuery;
7
7
 
8
8
  function runQuery(query, onCompleted) {
@@ -13,18 +13,15 @@ function wrapQuery(connection) {
13
13
  values: params,
14
14
  types: query.types
15
15
  };
16
- log.emitQuery({sql, parameters: params});
16
+ log.emitQuery({ sql, parameters: params });
17
17
 
18
- runOriginalQuery.call(connection, query, onInnerCompleted);
18
+ connection.unsafe(sql, params).then(onInnerCompleted, onCompleted);
19
+ // runOriginalQuery.call(connection, query, onInnerCompleted);
19
20
 
20
- function onInnerCompleted(err, result) {
21
- if (err)
22
- onCompleted(err);
23
- else {
24
- if (Array.isArray(result))
25
- result = result[result.length-1];
26
- onCompleted(null, result.rows);
27
- }
21
+ function onInnerCompleted(result) {
22
+ // if (Array.isArray(result))
23
+ // result = result[result.length - 1];
24
+ onCompleted(null, result);
28
25
  }
29
26
  }
30
27