Merge pull request #2 from TimonKK/master

- Merge upstream
This commit is contained in:
Truong.NX
2022-09-22 16:24:54 +07:00
committed by GitHub
7 changed files with 523 additions and 80 deletions

2
.gitignore vendored
View File

@@ -1,3 +1,5 @@
node_modules
.idea/*
.vscode/
test_config.json
*.code-workspace

201
LICENSE Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -24,6 +24,8 @@ const clickhouse = new ClickHouse({
debug: false,
basicAuth: null,
isUseGzip: false,
trimQuery: false,
usePost: false,
format: "json", // "json" || "csv" || "tsv"
raw: false,
config: {
@@ -197,6 +199,48 @@ const result = await rs.pipe(tf).pipe(ws).exec();
```
***
insert array of objects:
```javascript
/*
CREATE TABLE IF NOT EXISTS test_array (
date Date,
str String,
arr Array(String),
arr2 Array(Date),
arr3 Array(UInt8),
id1 UUID
) ENGINE=MergeTree(date, date, 8192)
*/
const rows = [
{
date: '2018-01-01',
str: 'Something1...',
arr: [],
arr2: ['1985-01-02', '1985-01-03'],
arr3: [1,2,3,4,5],
id1: '102a05cb-8aaf-4f11-a442-20c3558e4384'
},
{
date: '2018-02-01',
str: 'Something2...',
arr: ['5670000000', 'Something3...'],
arr2: ['1985-02-02'],
arr3: [],
id1: 'c2103985-9a1e-4f4a-b288-b292b5209de1'
}
];
await clickhouse.insert(
`insert into test_array
(date, str, arr, arr2,
arr3, id1)`,
rows
).toPromise();
```
***
Parameterized Values:
```javascript
const rows = await clickhouse.query(
@@ -224,6 +268,8 @@ npm run test
***
**Changelogs**:
* 2020-08-26 (v2.6.0)
- A lot of PRs from community
* 2020-11-02 (v2.4.1)
- Merge list of PR
- fix test with Base Auth check

View File

@@ -10,6 +10,7 @@ const stream2asynciter = require('stream2asynciter');
const { URL } = require('url');
const tsv = require('tsv');
const uuidv4 = require('uuid/v4');
const INSERT_FIELDS_MASK = /^INSERT\sINTO\s(.+?)\s*\(((\n|.)+?)\)/i;
/**
@@ -39,7 +40,7 @@ var ESCAPE_STRING = {
TSV: function (value) {
return value
.replace(/\\/g, '\\\\')
.replace(/\\/g, '\\')
.replace(/\'/g, '\\\'')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n');
},
@@ -302,12 +303,16 @@ class Rs extends Transform {
return Promise.resolve();
} else {
return new Promise((resolve, reject) => {
this.ws.once('error', err => reject(err));
const fn = err => reject(err);
this.ws.once('error', fn);
this.ws.once('drain', err => {
if (err) return reject(err);
resolve();
})
this.ws.removeListener('error', fn);
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
}
@@ -416,7 +421,7 @@ class QueryCursor {
}
if (isFirstElObject) {
let m = query.match(/INSERT INTO (.+?) \((.+?)\)/);
let m = query.match(INSERT_FIELDS_MASK);
if (m) {
fieldList = m[2].split(',').map(s => s.trim());
} else {
@@ -492,11 +497,7 @@ class QueryCursor {
// when passed in the request.
Object.keys(data.params).forEach(k => {
let value = data.params[k].toString();
if (Array.isArray(data.params[k])) {
value = '[' + value + ']'
};
let value = encodeValue(false, data.params[k], 'TabSeparated');
url.searchParams.append(
`param_${k}`, value
@@ -511,9 +512,14 @@ class QueryCursor {
}
// Hack for Sequelize ORM
query = query.trim().trimEnd().replace(/;$/gm, "");
query = query.trim().trimEnd().replace(/;$/gm, '');
if (me.connection.trimQuery) {
// Remove comments from the SQL
// replace multiple white spaces with one white space
query = query.replace(/(--[^\n]*)/g, '').replace(/\s+/g, ' ')
}
if (query.match(/^(select|show|exists)/i)) {
if (query.match(/^(with|select|show|exists|create|drop)/i)) {
if ( ! R_FORMAT_PARSER.test(query)) {
query += ` FORMAT ${ClickHouse.getFullFormatName(me.format)}`;
}
@@ -543,7 +549,7 @@ class QueryCursor {
}
} else if (me.isInsert) {
if (query.match(/values/i)) {
if (data && data.every(d => typeof d === 'string')) {
if (data && Array.isArray(data) && data.every(d => typeof d === 'string')) {
params['body'] = me._getBodyForInsert();
}
} else {
@@ -559,8 +565,16 @@ class QueryCursor {
if (me.opts.sessionId !== undefined && typeof me.opts.sessionId === 'string') {
url.searchParams.append('session_id', me.opts.sessionId);
}
url.searchParams.append('query', query);
if (me.connection.usePost) {
// use formData transfer query body for long sql
if (typeof params['formData'] === 'undefined') {
params['formData'] = {}
}
params['formData']['query'] = query;
} else {
url.searchParams.append('query', query);
}
if (me.connection.isUseGzip) {
params.headers['Accept-Encoding'] = 'gzip';
@@ -722,6 +736,11 @@ class QueryCursor {
const requestStream = request.post(reqParams);
// handle network socket errors to avoid uncaught error
requestStream.on('error', function (err) {
rs.emit('error', err);
});
// Не делаем .pipe(rs) потому что rs - Readable,
// а для pipe нужен Writable
let s;
@@ -824,6 +843,8 @@ class ClickHouse {
format: FORMAT_NAMES.JSON,
raw: false,
isSessionPerQuery: false,
trimQuery: false,
usePost: false,
},
opts
);
@@ -940,6 +961,24 @@ class ClickHouse {
return JSON.parse;
}
}
get trimQuery() {
return this.opts.trimQuery;
}
set trimQuery(val) {
this.opts.trimQuery = !!val;
return this;
}
get usePost() {
return this.opts.usePost;
}
set usePost(val) {
this.opts.usePost = !!val;
return this;
}
static mapRowAsArray(row) {
return row

96
package-lock.json generated
View File

@@ -1,6 +1,6 @@
{
"name": "clickhouse",
"version": "2.4.0",
"version": "2.5.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
@@ -37,9 +37,9 @@
"dev": true
},
"ansi-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
"integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.1.tgz",
"integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==",
"dev": true
},
"ansi-styles": {
@@ -71,9 +71,9 @@
}
},
"asn1": {
"version": "0.2.4",
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz",
"integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==",
"version": "0.2.6",
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
"requires": {
"safer-buffer": "~2.1.0"
}
@@ -192,9 +192,9 @@
},
"dependencies": {
"ansi-regex": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz",
"integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==",
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz",
"integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==",
"dev": true
},
"string-width": {
@@ -510,9 +510,9 @@
"dev": true
},
"is-glob": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz",
"integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==",
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
"dev": true,
"requires": {
"is-extglob": "^2.1.1"
@@ -562,9 +562,9 @@
"integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM="
},
"json-schema": {
"version": "0.2.3",
"resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz",
"integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM="
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",
"integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="
},
"json-schema-traverse": {
"version": "0.4.1",
@@ -582,13 +582,13 @@
"integrity": "sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA="
},
"jsprim": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz",
"integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=",
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz",
"integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==",
"requires": {
"assert-plus": "1.0.0",
"extsprintf": "1.3.0",
"json-schema": "0.2.3",
"json-schema": "0.4.0",
"verror": "1.10.0"
}
},
@@ -616,16 +616,16 @@
}
},
"mime-db": {
"version": "1.49.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.49.0.tgz",
"integrity": "sha512-CIc8j9URtOVApSFCQIF+VBkX1RwXp/oMMOrqdyXSBXq5RWNEsRfyj1kiRnQgmNXmHxPoFIxOroKA3zcU9P+nAA=="
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="
},
"mime-types": {
"version": "2.1.32",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.32.tgz",
"integrity": "sha512-hJGaVS4G4c9TSMYh2n6SQAGrC4RnfU+daP8G7cSCmaqNjiOoUY0VHCMS42pxnQmVF1GWwFhbHWn3RIxCqTmZ9A==",
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"requires": {
"mime-db": "1.49.0"
"mime-db": "1.52.0"
}
},
"minimatch": {
@@ -744,9 +744,9 @@
"integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns="
},
"picomatch": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz",
"integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==",
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"dev": true
},
"psl": {
@@ -760,9 +760,9 @@
"integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A=="
},
"qs": {
"version": "6.5.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz",
"integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA=="
"version": "6.5.3",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz",
"integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA=="
},
"querystring": {
"version": "0.2.0",
@@ -858,9 +858,9 @@
"dev": true
},
"sshpk": {
"version": "1.16.1",
"resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz",
"integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==",
"version": "1.17.0",
"resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.17.0.tgz",
"integrity": "sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ==",
"requires": {
"asn1": "~0.2.3",
"assert-plus": "^1.0.0",
@@ -874,9 +874,9 @@
}
},
"stream2asynciter": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/stream2asynciter/-/stream2asynciter-1.0.2.tgz",
"integrity": "sha512-ye/h2HsqnSDF+bD68AJHpCypZ5hVcxan3HXEEmDf49K+Jr3n3/smBoQrjiOtq2RRVI3w28AA+oahcmFKmo2SDg=="
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/stream2asynciter/-/stream2asynciter-1.0.3.tgz",
"integrity": "sha512-9/dEZW+LQjuW6ub5hmWi4n9Pn8W8qA8k7NAE1isecesA164e73xTdy1CJ3S9o9YS+O21HuiK7T+4uS7FgKDy4w=="
},
"string-width": {
"version": "2.1.1",
@@ -1025,9 +1025,9 @@
},
"dependencies": {
"ansi-regex": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz",
"integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==",
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz",
"integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==",
"dev": true
},
"ansi-styles": {
@@ -1107,9 +1107,9 @@
},
"dependencies": {
"ansi-regex": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz",
"integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==",
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz",
"integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==",
"dev": true
},
"find-up": {
@@ -1200,9 +1200,9 @@
},
"dependencies": {
"camelcase": {
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.2.0.tgz",
"integrity": "sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg==",
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",
"integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==",
"dev": true
},
"decamelize": {

View File

@@ -54,7 +54,7 @@
"lodash": "4.17.21",
"querystring": "0.2.0",
"request": "2.88.0",
"stream2asynciter": "1.0.2",
"stream2asynciter": "1.0.3",
"through": "2.3.8",
"tsv": "0.2.0",
"uuid": "3.4.0"
@@ -91,5 +91,5 @@
"test": "mocha --bail --timeout 60000 --slow 5000"
},
"types": "index.d.ts",
"version": "2.4.2"
"version": "2.6.0"
}

View File

@@ -5,15 +5,21 @@ const expect = require('expect.js');
const _ = require('lodash');
const https = require('https');
const fs = require('fs');
const path = require('path');
const { ClickHouse } = require('../.');
const database = 'test_' + _.random(1000, 100000);
const
configFilepath = process.env.CLICKHOUSE_TEST_CONF_FILE || './test_config.json',
configPath = path.resolve(process.cwd(), configFilepath),
extConfig = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, { encoding: 'utf-8' })) : undefined,
config = {
debug: false,
...extConfig,
debug: false,
},
clickhouse = new ClickHouse({
...config,
database : database,
@@ -34,6 +40,24 @@ before(async () => {
await temp.query(`CREATE DATABASE ${database}`).toPromise();
});
describe.skip('On cluster', () => {
// Note: this test only works with ClickHouse setup as Cluster named test_cluster
it('should be able to create and drop a table', async () => {
const createTableQuery = `
CREATE TABLE ${database}.test_on_cluster ON CLUSTER test_cluster (
test String
)
ENGINE=MergeTree ORDER BY test;`;
const createTableQueryResult = await clickhouse.query(createTableQuery).toPromise();
expect(createTableQueryResult).to.be.ok();
const dropTableQuery = `
DROP TABLE ${database}.test_on_cluster ON CLUSTER test_cluster;`;
const dropTableQueryResult = await clickhouse.query(dropTableQuery).toPromise();
expect(dropTableQueryResult).to.be.ok();
});
});
describe('Exec', () => {
it('should return not null object', async () => {
const sqlList = [
@@ -144,6 +168,24 @@ describe('Select', () => {
callback();
})
});
it('streams should handle network error', function(callback) {
let i = 0;
const host = 'non-existing-clickhouse-server'; // to simulate a dns failure
new ClickHouse({
...config,
host
}).query('SELECT number FROM system.numbers LIMIT 10').stream()
.on('data', () => ++i)
.on('error', error => {
expect(error.code).to.be.equal('ENOTFOUND');
expect(error.syscall).to.be.equal('getaddrinfo');
expect(error.hostname).to.be.equal(host);
expect(i).to.be(0);
callback();
});
});
const nodeVersion = process.version.split('.')[0].substr(1);
if (parseInt(nodeVersion, 10) >= 10) {
@@ -305,7 +347,7 @@ describe('Select', () => {
});
describe('session', () => {
(extConfig? describe.skip : describe)('session', () => {
it('use session', async () => {
const sessionId = clickhouse.sessionId;
clickhouse.sessionId = Date.now();
@@ -407,7 +449,8 @@ describe('session', () => {
// You can use all settings from request library (https://github.com/request/request#tlsssl-protocol)
// Generate ssl file with:
// sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout test/cert/server.key -out test/cert/server.crt
describe('TLS/SSL Protocol', () => {
(extConfig? describe.skip : describe)('TLS/SSL Protocol', () => {
it('use TLS/SSL Protocol', async () => {
let server = null;
@@ -472,7 +515,8 @@ describe('queries', () => {
str String,
arr Array(String),
arr2 Array(Date),
arr3 Array(UInt8)
arr3 Array(UInt8),
id1 UUID
) ENGINE=MergeTree(date, date, 8192)
`).toPromise();
expect(r).to.be.ok();
@@ -482,24 +526,30 @@ describe('queries', () => {
date: '2018-01-01',
str: 'Вам, проживающим за оргией оргию,',
arr: [],
arr2: ['1915-01-02', '1915-01-03'],
arr3: [1,2,3,4,5]
arr2: ['1985-01-02', '1985-01-03'],
arr3: [1,2,3,4,5],
id1: '102a05cb-8aaf-4f11-a442-20c3558e4384'
},
{
date: '2018-02-01',
str: 'имеющим ванную и теплый клозет!',
arr: ['5670000000', 'asdas dasf'],
arr2: ['1915-02-02'],
arr3: []
str: 'It\'s apostrophe test.',
arr: ['5670000000', 'asdas dasf. It\'s apostrophe test.'],
arr2: ['1985-02-02'],
arr3: [],
id1: 'c2103985-9a1e-4f4a-b288-b292b5209de1'
}
];
const r2 = await clickhouse.insert(
'INSERT INTO test_array (date, str, arr, arr2, arr3)',
`insert into test_array
(date, str, arr, arr2,
arr3, id1)`,
rows
).toPromise();
expect(r2).to.be.ok();
const r3 = await clickhouse.query('SELECT * FROM test_array ORDER BY date').toPromise();
expect(r3).to.eql(rows);
});
it('insert field as raw string', async () => {
@@ -519,7 +569,7 @@ describe('queries', () => {
const rows = [
'(\'2018-01-01 10:00:00\',\'Вам, проживающим за оргией оргию,\',[],[\'1915-01-02 10:00:00\',\'1915-01-03 10:00:00\'],[1,2,3,4,5],unhex(\'60ed56e75bb93bd353267faa\'))',
'(\'2018-02-01 10:00:00\',\'имеющим ванную и теплый клозет!\',[\'5670000000\',\'asdas dasf\'],[\'1915-02-02 10:00:00\'],[],unhex(\'60ed56f4a88cd5dcb249d959\'))'
'(\'2018-02-01 10:00:00\',\'имеющим ванную и теплый клозет! It\'\'s apostrophe test.\',[\'5670000000\',\'asdas dasf\'],[\'1915-02-02 10:00:00\'],[],unhex(\'60ed56f4a88cd5dcb249d959\'))'
];
const r2 = await clickhouse.insert(
@@ -657,6 +707,102 @@ describe('queries', () => {
const result4 = await clickhouse.query('SELECT int_value FROM test_int_temp').toPromise();
expect(result4).to.eql(int_value_data);
});
it('insert with params', async () => {
const result = await clickhouse.query('DROP TABLE IF EXISTS test_par_temp').toPromise();
expect(result).to.be.ok();
const result1 = await clickhouse.query(`CREATE TABLE test_par_temp (
int_value UInt32,
str_value1 String,
str_value2 String,
date_value Date,
date_time_value DateTime,
decimal_value Decimal(10,4),
arr Array(String),
arr2 Array(Date),
arr3 Array(UInt32)
) ENGINE=Memory`).toPromise();
expect(result1).to.be.ok();
const row = {
int_value: 12345,
str_value1: 'Test for "masked" characters. It workes, isn\'t it?',
str_value2: JSON.stringify({name:'It is "something".'}),
date_value: '2022-08-18',
date_time_value: '2022-08-18 19:07:00',
decimal_value: 1234.678,
arr: ['asdfasdf', 'It\'s apostrophe test'],
arr2: ['2022-01-01', '2022-10-10'],
arr3: [12345, 54321],
};
const result2 = await clickhouse.insert(`INSERT INTO test_par_temp (int_value, str_value1, str_value2, date_value, date_time_value, decimal_value,
arr, arr2, arr3)
VALUES ({int_value:UInt32}, {str_value1:String}, {str_value2:String}, {date_value:Date}, {date_time_value:DateTime}, {decimal_value: Decimal(10,4)},
{arr:Array(String)},{arr2:Array(Date)},{arr3:Array(UInt32)})`,
{params: {
...row,
decimal_value: row.decimal_value.toFixed(4)
}
}).toPromise();
expect(result2).to.be.ok();
const result3 = await clickhouse.query('SELECT * FROM test_par_temp').toPromise();
expect(result3).to.eql([row]);
});
it('insert select', async () => {
const result = await clickhouse.query('DROP TABLE IF EXISTS test_par_temp').toPromise();
expect(result).to.be.ok();
const result1 = await clickhouse.query(`CREATE TABLE test_par_temp (
int_value UInt32,
str_value1 String,
str_value2 String,
date_value Date,
date_time_value DateTime,
decimal_value Decimal(10,4),
arr Array(String),
arr2 Array(Date),
arr3 Array(UInt32)
) ENGINE=Memory`).toPromise();
expect(result1).to.be.ok();
const row = {
int_value: 12345,
str_value1: 'Test for "masked" characters. It workes, isn\'t it?',
str_value2: JSON.stringify({name:'It is "something".'}),
date_value: '2022-08-18',
date_time_value: '2022-08-18 19:07:00',
decimal_value: 1234.678,
arr: ['asdfasdf', 'It\'s apostrophe test'],
arr2: ['2022-01-01', '2022-10-10'],
arr3: [12345, 54321],
};
const result2 = await clickhouse.insert(`INSERT INTO test_par_temp (int_value, str_value1, str_value2, date_value, date_time_value, decimal_value,
arr, arr2, arr3)
select {int_value:UInt32}, {str_value1:String}, {str_value2:String}, {date_value:Date}, {date_time_value:DateTime}, {decimal_value: Decimal(10,4)},
{arr:Array(String)},{arr2:Array(Date)},{arr3:Array(UInt32)}`,
{params: {
...row,
decimal_value: row.decimal_value.toFixed(4)
}
}).toPromise();
expect(result2).to.be.ok();
const result3 = await clickhouse.query('SELECT * FROM test_par_temp').toPromise();
expect(result3).to.eql([row]);
const result4 = await clickhouse.insert(`INSERT INTO test_par_temp (int_value, str_value1, str_value2, date_value, date_time_value, decimal_value,
arr, arr2, arr3)
select 123456, 'awerqwerqwer', 'rweerwrrewr', '2022-08-25', '2022-08-25 02:00:01', '123.1234',
['aaa','bbb'],['2022-08-22','2022-08-23'],[1,2,3,4]`
).toPromise();
expect(result2).to.be.ok();
});
});
describe('response codes', () => {
@@ -728,7 +874,7 @@ describe('compatibility with Sequelize ORM', () => {
describe('Constructor options', () => {
(extConfig? describe.skip : describe)('Constructor options', () => {
const addConfigs = [
{
url: 'localhost',
@@ -965,6 +1111,15 @@ describe('Select and WITH TOTALS statement', () => {
expect(result.rows).to.be(LIMIT_COUNT);
expect(result).to.have.key('statistics');
});
it('start with WITH', async() => {
const r = await clickhouse.query(`
WITH x as (SELECT 1) SELECT * FROM x
`).toPromise();
expect(r).to.be.ok();
expect(r[0]).to.be.eql({1: 1});
});
});
describe('Abort query', () => {