{"_id":"clickhouse-orm","_rev":"18-24f862359003ffe5eee21df367ee1610","name":"clickhouse-orm","dist-tags":{"beta":"3.0.2-alpha1","latest":"3.0.2"},"versions":{"1.0.0":{"name":"clickhouse-orm","version":"1.0.0","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts"},"dependencies":{"clickhouse":"^2.4.0","colors":"^1.4.0","ts-node":"^10.4.0"},"devDependencies":{"dayjs":"^1.10.7","typescript":"^4.3.5"},"main":"dist/lib/index.js","types":"dist/lib/index.d.ts","gitHead":"43e517a31c3735ee4bc3003d348535e3f7b99b37","_id":"clickhouse-orm@1.0.0","_nodeVersion":"14.7.0","_npmVersion":"7.12.0","dist":{"integrity":"sha512-xB8KVwHS5mlyNPAB5szFUE8jDCyh/72pIKfk2NIVTRMI6xFluKHNMHHgcQKCCKh+PBVZUjCYiFyFUe0HVxKLSA==","shasum":"2614c2ca8a91eed3969c3414a538b343db5a842a","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-1.0.0.tgz","fileCount":35,"unpackedSize":49561,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJh/pxACRA9TVsSAnZWagAAcUIP/0hYE9dqjiEo0O8n/d1W\nxqveSIbQ24ORwxyGk4tVZJu0Z1yjz/zYAxNkv3eGmGeu6/0wM5yU1kr+NfTn\nMuNmV9B/zWqF+CILp4Xss4/HSJdtXDMlwRrr6WaBqgs9EQvAE0cSgZiVzOWV\nNwu6G8wavTEesWIufp/wtzDK7HyXqNEtdTWAOGJSMme9zRxAIq0TAxqIVDR1\nXC4Bt4eRrSVrHb7fUjOc2BkfyTGMz6vxy404c8WyqzQ7OsUuV2Bapj/DWz1p\nR/PIOWoBZLb++eQW1U8eq1TwxsN92nHAlAv2w6Z390XmAUnRV/JjxLTPvhOT\nvbcF2QQ4w6X8McMxxGVKosUcpHe1W2WBaUyHLAPdCVWR+B1eqM2rjJQ3wHL4\nDEdjFsBt3z3g1+zvHH+LoWWGsEhUdKEO0AXCmYpX5YKpwdZyeBjxPeZ4EGze\nn5SSHawWM2vp87hcdN3eXxEkgPmyexAJzhjnQcPX6DsyfD09g+IOB6mWOjDi\n56jpdGu9/geZu5mXSxRgEFlAxPTxAKq2MNPIMz69WCMhNWnMozbk50t2PD6u\nPq9xUVjDbOOJFwG526ZTYI00EAQFiUw0ECki7MyXkbAPXK5GnyqPAv7SdOwY\nQF62hNXBS688WbJiUSFv/TNe6hxaUs7YmmPsgEaO03iu1rfwapR8UE4k88OY\n5Ibk\r\n=bIgz\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCz0KP0vEW8BjyWI8XMgXUsd28MHOMC07S74LFmMKZCpQIhAJIfiXzoogq9yQoXtbNPkqyIGsh/kcCjeGggZuVtmk6E"}]},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_1.0.0_1644076096014_0.699157893909214"},"_hasShrinkwrap":false},"1.0.1":{"name":"clickhouse-orm","version":"1.0.1","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts"},"dependencies":{"clickhouse":"^2.4.0","colors":"^1.4.0"},"devDependencies":{"dayjs":"^1.10.7","typescript":"^4.3.5","ts-node":"^10.4.0"},"main":"dist/lib/index.js","types":"dist/lib/index.d.ts","gitHead":"42efffe335ec45717463253632a54691a95c2977","_id":"clickhouse-orm@1.0.1","_nodeVersion":"14.7.0","_npmVersion":"7.12.0","dist":{"integrity":"sha512-ubdmtpGq8dSAbW+CPdjK/kf8tb5pWa/413Axwtxzj/1He+Ukm5eMIhJ8hpWM0M3e52OlsyPUqllx/m66EeYc8w==","shasum":"ae6412cbe6484943527e3737cdbc9aa4c05cae7e","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-1.0.1.tgz","fileCount":35,"unpackedSize":51409,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJiBQQCCRA9TVsSAnZWagAAj2YP/AvMrQm+rSw4a2oS3gMC\nb5+DX2zR2t/5FCXmI5IAm6Df6sFIWQ7FmibAI50rUtNzHThMYhikmpQ1HfNu\nreKR4agBzNhBb/2tMhN3/2cfsy1LCHMIJIAqGOLkfPruJMiuN3lLSU3rQIVh\nEFACVRlfHHYfQjefrwSJ3gd7KJAMIAVz1dE+kyDN0mBQxbYwoFOmOTUiA3Js\nzofNr2FUr4xsltpb98n3TZmR3Gnp2yIyRiMAGtqldtRHQ1gaUk39meL7Fjbj\nrLzRBfFx14tQx+cbhjOYg5VRX5LfLKjYMKK0vnbJPr0KKrLRwV3uhVdkGbmX\n2UK1j56465JCcEh4R6a331a2bYcDku/zQub7u9cJyURk18qVIpp1eCoXqegx\npzZlXF93Gst6yjV9hPaSu6E0MH0w0XQ46QKQnXAEMQAPMgTcxx5jX1fCBSge\nDz5UY0xVxMJYAQwQ4rGzxe7jIGiHqObnMsxAZtFoKP6Blz4Bztqcs9SW2nd+\nAJCivkNJiAq/d2OnMYbsR9IxCHhEc53VxVIA2IXmmp4p3Cfp/CUX+wPfKZZX\nsOnHNRYIR2ZZKjK0wmPBMMikkK+zsau109XKRyiy7dTFG2bosu4+JK7HN0yr\nXln0PX+FRM1C0dhxrdpHqJxcjSrKoaM0FWAy3/XOw+hFxBUaghH+2HQbgI6c\nMu2k\r\n=5EaX\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIGGgZw027CifhOktVcZ2WfChPnrb9T+ZtCPKWUHTXWprAiBORME3gKLTkgGvz1ypJCD7O7k2WT05zuPkTYGl4F4uug=="}]},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_1.0.1_1644495874653_0.5209020618124705"},"_hasShrinkwrap":false},"2.0.0-alpha.0":{"name":"clickhouse-orm","version":"2.0.0-alpha.0","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts"},"dependencies":{"clickhouse":"^2.4.0","colors":"^1.4.0"},"devDependencies":{"dayjs":"^1.10.7","typescript":"^4.3.5","ts-node":"^10.4.0"},"main":"dist/lib/index.js","types":"dist/lib/index.d.ts","readme":"<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://img.shields.io/npm/v/clickhouse-orm.svg\"></a>\n<a href=\"https://npms.io/search?q=clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://badges.npms.io/clickhouse-orm.svg\"></a>\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM total downloads\"><img src=\"https://img.shields.io/npm/dt/clickhouse-orm.svg\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github stars\"><img src=\"https://img.shields.io/github/stars/zimv/node-clickhouse-orm.svg?style=social&label=Star\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github forks\"><img src=\"https://img.shields.io/github/forks/zimv/node-clickhouse-orm.svg?style=social&label=Fork\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github contributors\"><img src=\"https://img.shields.io/github/contributors/zimv/node-clickhouse-orm.svg\"></a>\n# clickhouse-orm\nClickhouse ORM for Nodejs. Send query over HTTP interface. Using [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n# Install:\n\n``` \nnpm i clickhouse-orm \n``` \n\n# Usage\n\n**Create instance：**\n\n\n```javascript\n\nconst { ClickhouseOrm, DATA_TYPE, setLogService} = require('clickhouse-orm');\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: 'orm_test',\n  },\n  debug: true,\n  client: {\n    url: 'localhost',\n    port: '8123',\n    basicAuth: {\n      username: 'default',\n      password: '',\n    },\n    debug: false,\n    isUseGzip: true,\n    format: 'json', // \"json\" || \"csv\" || \"tsv\"\n  },\n});\n\n```\n\n**Define Schema：**\n```javascript\nconst table1Schema = {\n  // table name\n  tableName: 'table1',\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n}\n```\n\n**create / build + save / find：**\n```javascript\nconst doDemo = async ()=>{\n  // create database 'orm_test'\n  await chOrm.createDatabase();\n  \n  // register schema and create [if] table\n  const Table1Model = await chOrm.model(table1Schema);\n    \n  // new data model\n  const data = Table1Model.build({status:2});\n    \n  // set value\n  data.time = new Date();\n  data.browser = 'chrome';\n  data.browser_v = '90.0.1.21';\n    \n  // do save\n  const res = await data.save();\n  // SQL: INSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":2,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\n  console.log('save:', res);\n\n  // create === build + save \n  const resCreate = await Table1Model.create({\n      status: 1,\n      time: new Date(),\n      browser: 'chrome',\n      browser_v: '90.0.1.21'\n  })\n  console.log('create:', resCreate);\n  \n  // do find\n  Table1Model.find({\n      select: '*',\n      limit: 3\n  }).then((res)=>{\n      // SQL: SELECT * from orm_test.table1    LIMIT 3\n      console.log('find:', res);\n  });\n}\n\ndoDemo();\n```\n\nMore in [Basic Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/basic.js).\n\n# Overview\n`Note`: '?' is a Optional\n### ClickhouseOrm\n`db` : object<{name:string, engine?:string}>\n> name: database name\n\n> engine: database engine\n\n`debug` : boolean\n> Default: false\n\n`client` : object\n> Drive configuration. More in [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n### Schema\n`tableName` : string\n> It is the table name.\n\n`schema` :  { [column]: { type?, default? } } \n> The `type` will be verified, The `default` is the default value for column.\n\n`createTable` : string\n> It is the SQL for creating tables.When model is executed, this SQL will be executed. It is suggested to add 'IF NOT EXISTS'.\n\n\n\nWatch out !!! >>>>> If the table already exists and you want to modify it. You need to execute the modification sql through other clients（Such as Remote terminal） and update the code of the Schema!!!\n\n\n```javascript\nconst table1Schema = {\n  // table name\n  tableName: 'table1',\n  // define column\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n}\n\n// register schema and create [if] table\nconst Table1Model = await chOrm.model(table1Schema);\n```\n\n### DATA_TYPE\nThe clickhouse data types. Some types are defined here.\n\nColumns with defined types will be verified. It only checks the basic type of data, not the most standard value. They are `number | string | boolean | date`. \n\n\n\n```javascript\nexport enum DATA_TYPE {\n  UInt8 = 'number',\n  UInt16 = 'number',\n  UInt32 = 'number',\n  UInt64 = 'number',\n  UInt128 = 'number',\n  UInt256 = 'number',\n  Int8 = 'number',\n  Int16 = 'number',\n  Int32 = 'number',\n  Int64 = 'number',\n  Int128 = 'number',\n  Int256 = 'number',\n  Float32 = 'number',\n  Float64 = 'number',\n  Boolean = 'boolean',\n  String = 'string',\n  UUID = 'string',\n  Date = 'date|string|number',\n  Date32 = 'date|string|number',\n  DateTime = 'date|string|number',\n  DateTime64 = 'date|string|number',\n}\n```\n\n```javascript\nschema: {\n  time: { type: DATA_TYPE.DateTime, default: Date },\n  [column]: { type?, default? }\n}\n```\n\n### Log\nThe **setLogService** is a global configuration method and will affect all instances.\n\n\n```Default: console.log```\n\n\nCustom example:  **[winston](https://github.com/winstonjs/winston)**\n\n```javascript\nconst { setLogService } = require('clickhouse-orm');\nconst winston = require('winston');\nconst logger = winston.createLogger();\n\nsetLogService(logger.info);\n```\n\n\n### Use SQL directly：\n```javascript\nchOrm.client.query(`select * from orm_test.table1 limit 3`).toPromise().then(res=>{\n  console.log('Use sql:', res);\n});\n```\n\nThe `chOrm.client` is the [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse) instance.\n\n\n\n# [More Examples](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/more.ts)\n### Find\n\n```javascript\nimport * as dayjs from 'dayjs';\n\nqueryExample1({\n  Model: Table1Model,\n  status: 1,\n  beginTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),\n  endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),\n}).then(res=>{\n  console.log('queryExample1:', res);\n});\n\nconst queryExample1 = ({\n  Model,\n  status,\n  beginTime,\n  endTime\n}) => {\n  let wheres=[],where;\n  if(status) wheres.push(`status='${status}'`);\n  if(beginTime) wheres.push(`time>='${beginTime}'`);\n  if(endTime) wheres.push(`time<='${endTime}'`);\n  if(wheres.length>0) where = wheres.join(' and ');\n\n  return Model.find({\n    where,\n    select: `*`,\n    orderBy: 'time ASC',\n    limit: 5,\n  })\n}\n```\nFinal executed SQL:\n```sql\nSELECT * from orm_test.table1 where status='1' and time>='2022-02-04 15:34:22' and time<='2022-02-05 15:34:22'  ORDER BY time ASC LIMIT 5\n```\n\n### Count\n\n```javascript\ncountExample1({\n  Model: Table1Model,\n}).then(res=>{\n  console.log('countExample1:', res);\n});\n  \nconst countExample1 = ({\n  Model,\n}) => {\n  return Model.find({\n    select: `count(*) AS total`,\n  })\n}\n```\nFinal executed SQL:\n```sql\nSELECT count(*) AS total from orm_test.table1\n```\n\n### GroupBy\n\n```javascript\nTable1Model.find({\n  select: `status,browser`,\n  groupBy: 'status,browser',\n})\n```\n\nFinal executed SQL:\n```sql\nSELECT status,browser from orm_test.table1  GROUP BY status,browser\n```\n\n### Nested Queries\n\n\n```javascript\nTable1Model.find([\n  {\n    select: `browser`,\n    groupBy: 'browser',\n  },\n  {\n    select: `count() as browserTotal`,\n  },\n])\n```\n\nFinal executed SQL:\n```sql\nSELECT count() as browserTotal from (SELECT browser from orm_test.table1  GROUP BY browser  )\n```\n\n### save\n```javascript\n// new data model\nconst data = Table1Model.build();\n\n// set value\ndata.time = new _Date_();\ndata.status = 1;\ndata.browser = 'chrome';\ndata.browser_v = '90.0.1.21';\n\n// do save \ndata.save().then((res)=>{\n  console.log('save:', res);\n});\n```\nFinal executed SQL:\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### create\n```javascript\n//do create\nawait Table1Model.create({\n    status: 1,\n    time: new Date(),\n    browser: 'chrome',\n    browser_v: '90.0.1.21'\n})\n```\nFinal executed SQL:\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### InsertMany\n\n```javascript\nconst list = [\n  { status: 2, browser: 'IE', browser_v: '10.0.1.21' },\n  { status: 2, browser: 'FF', browser_v: '2.0.3' },\n  { status: 3, browser: 'IE', browser_v: '1.1.1' },\n];\n\nTable1Model.insertMany(list)\n// or\nTable1Model.insertMany(\n  list.map(item=>{\n    const data = Table1Model.build();\n    // set value\n    data.time = new Date();\n    data.status = item.status;\n    data.browser = item.browser;\n    data.browser_v = item.browser_v;\n    return data;\n  })\n)\n```\nFinal executed SQL:\n```sql\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"IE\",\"browser_v\":\"10.0.1.21\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"FF\",\"browser_v\":\"2.0.3\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":3,\"browser\":\"IE\",\"browser_v\":\"1.1.1\"}]\n```\n\n# Wechat Discussion\n[Click to join](https://github.com/zimv/node-clickhouse-orm/issues/3)\n\n","readmeFilename":"README.md","gitHead":"48b65abbea83d376324ca9ce1bf14e50007bb9b6","_id":"clickhouse-orm@2.0.0-alpha.0","_nodeVersion":"14.7.0","_npmVersion":"7.12.0","dist":{"integrity":"sha512-rIH+hOpkdiFIkK3AvMYNifKTW8ZcrVOEwguc0EkaGcEkk43Y1HTci4c5UHQOyjCYCzHgRW0VsSn/EYQpqYA9ag==","shasum":"3f1bd489abb2e1734c7c8f887269395e365903c2","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-2.0.0-alpha.0.tgz","fileCount":38,"unpackedSize":57238,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJiE2gwACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmrs8A//TsJ9CkZpOpRlzo0cXNzGd//81dW8bbNlbeYF48G2fXyDVidr\r\nOtweWrnAztAPFQpiHhj6vddn0m5vf9CrMUCSqBwqnttKk41rj+4zKVh88TNV\r\n43MvWucDL5cG4AP78CgAZdphoqQHvT5HKp90KpZm/SbytuOLtrk68GoFleXZ\r\ncK3NM5k0SO6tK72a1PPFzYUyggor4EfeCQS76xvGl/bv1cobCPD9959jkrs9\r\n4LRXbxGTvaHmvyVWeRgQG1pDrZIkg8Ldy78YoxJXQkuklpgcOGqepMSLGeFw\r\nFa5WT1BJnElO1ggO+lZ9CZxJh99ZwpKCZP5GSvfWndkgeY3t0bIWm16xpcRq\r\nb3vyMqm46Z0LQsMnRs2DY3S6ZAdBSuDB2bJA4tboWnrAx6yMytpWcLzeTyjt\r\nZU+njqy+0i3olh7uUQaZm2K3JK/HFjsKWvVqGast9s+r6h77PofL2c1l9QxE\r\n2sbkjm1DZCU98h4TgHas269eL6ckpEYjsxBPiFmyIUUc/5i2t3omWgl+a9jc\r\ncPdmU3vwTDI51p9Iuf2H+7x20YwsDpRDXQjtieg7gOJqekWrgXZKkYl4DZ9Y\r\nwf+/HkzyehhnDhd3uviifvgAe2I/nosWpzyv4EP8BFnTFska03rrGRPJAfyX\r\n3f+r7+xPHEkCnulTDaCO3LkCMemw61fEMjQ=\r\n=ys8U\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQD0YCjX7EzUBtgwC+uR7mKKzI89HUXToycJIlFG/mbFrQIhAJVCVzZgjb0SAXfeyjj0ugqq3k+HfTbaiH5IskWiMl3m"}]},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_2.0.0-alpha.0_1645439024014_0.6577395333375571"},"_hasShrinkwrap":false},"2.0.0":{"name":"clickhouse-orm","version":"2.0.0","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts"},"dependencies":{"clickhouse":"^2.4.0","colors":"^1.4.0"},"devDependencies":{"dayjs":"^1.10.7","typescript":"^4.3.5","ts-node":"^10.4.0"},"main":"dist/lib/index.js","types":"dist/lib/index.d.ts","gitHead":"b09d925c82a740d38018df786b30447ebc9b2aa3","_id":"clickhouse-orm@2.0.0","_nodeVersion":"14.7.0","_npmVersion":"7.12.0","dist":{"integrity":"sha512-48GyLpSa9lknO3TGzfUOe15qfBYY+HswDmoa8FCtT1J+GmMFYOAPFJs4NrJT9h4yG3+Vv8sztyrNq2R9oftbLQ==","shasum":"de75ef06daa216b332781d3a63dede04c6434c10","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-2.0.0.tgz","fileCount":38,"unpackedSize":58895,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJiFvAbACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmr/fQ/+ICuo33M1uFhDVd+zhN5ZBijNgAPAAdRplaaMk8u9Rb2QeeuR\r\nHVACFMwg4qetUz0xCsNAylv1pDTpM86Vi4SMDEnm1Erzv3PNHEklyxwyhzKO\r\nKBNel+htja0WxeegeqcCeP2iPbrNW5Klw0tkBKyrFG1X1kscFAodxSqxwEKt\r\nRI4QSs+le7w4KFn0wtQyf5XEXAlqs8pbgFkI+K/dh/p64tvSW0Hz7KKLAVb1\r\nyAmGGQgp9CUjvGwNcpqCewP291bTQKNZY2m66g2EH3zdTheVcUgg71aoVeEM\r\n6a13TF+iCHL062qOLeJccFfu+GFTeE4UIsUijHFkC9QTY3Y833iV0kBeryBB\r\no/HUevar6SbyWCd8QAcHnSfDApgYr7zlrTgANcH123iIR4AqyTgGSOk3S5r9\r\nMWnGtZkZVXyzPyLT1DzNKLpTQkCpxZzjn2dqR/ZJQG3fa8gnwP0yUeE0QH0d\r\niw3zWFHMo2US5RKb24cTZ0EUibMZeJmJOKIFibW65hOsYitUaSeEKXI/CBJD\r\nYAhIqQr3q+enjUy583ps8pqEk0rAoBreOPeHpUXKOEjtA9mb2n6/9V4TOwOA\r\nGyx2WOM//lSkx/VaJsjaV6KrAiB3ZO8+7/VkRYBe4P3g1mIFm88Z/MUPEV+e\r\nPHKd/3YvfemwDBq63WFicOsWpem/W/ww3hg=\r\n=KLCu\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIFnHugg/wkCYIN04n/0wZAwY8iFlMeOcwiCouEnhkrAnAiBCvYHpYjuxr9ju4N+2mLHvt1l1Zw4DUpNzreYo80hj8Q=="}]},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_2.0.0_1645670427846_0.27199884190653734"},"_hasShrinkwrap":false},"2.0.1-alpha.0":{"name":"clickhouse-orm","version":"2.0.1-alpha.0","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","test":"jest --coverage"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/lib/index.js","types":"dist/lib/index.d.ts","readme":"<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://img.shields.io/npm/v/clickhouse-orm.svg\"></a>\n<a href=\"https://npms.io/search?q=clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://badges.npms.io/clickhouse-orm.svg\"></a>\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM total downloads\"><img src=\"https://img.shields.io/npm/dt/clickhouse-orm.svg\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github stars\"><img src=\"https://img.shields.io/github/stars/zimv/node-clickhouse-orm.svg?style=social&label=Star\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github forks\"><img src=\"https://img.shields.io/github/forks/zimv/node-clickhouse-orm.svg?style=social&label=Fork\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github contributors\"><img src=\"https://img.shields.io/github/contributors/zimv/node-clickhouse-orm.svg\"></a>\n\n# clickhouse-orm\n\nClickhouse ORM for Nodejs. Send query over HTTP interface. Using [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n# Install:\n\n```\nnpm i clickhouse-orm\n```\n\n# Usage\n\n**Create instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_test\",\n  },\n  debug: true,\n  client: {\n    url: \"localhost\",\n    port: \"8123\",\n    basicAuth: {\n      username: \"default\",\n      password: \"\",\n    },\n    debug: false,\n    isUseGzip: true,\n    format: \"json\", // \"json\" || \"csv\" || \"tsv\"\n  },\n});\n```\n\n**Define Schema：**\n\n```javascript\nconst table1Schema = {\n  // table name\n  tableName: \"table1\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n```\n\n**create / build + save / find：**\n\n```javascript\nconst doDemo = async () => {\n  // create database 'orm_test'\n  // SQL: CREATE DATABASE IF NOT EXISTS orm_test\n  await chOrm.createDatabase();\n\n  // register schema and create [if] table\n  // createTable() SQL: CREATE TABLE IF NOT EXISTS orm_test.table1...\n  const Table1Model = await chOrm.model(table1Schema);\n\n  // new data model\n  const data = Table1Model.build({ status: 2 });\n\n  // set value\n  data.time = new Date();\n  data.browser = \"chrome\";\n  data.browser_v = \"90.0.1.21\";\n\n  // do save\n  const res = await data.save();\n  // SQL: INSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":2,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\n  console.log(\"save:\", res);\n\n  // create === build + save\n  const resCreate = await Table1Model.create({\n    status: 1,\n    time: new Date(),\n    browser: \"chrome\",\n    browser_v: \"90.0.1.21\",\n  });\n  console.log(\"create:\", resCreate);\n\n  // do find\n  Table1Model.find({\n    select: \"*\",\n    limit: 3,\n  }).then((res) => {\n    // SQL: SELECT * from orm_test.table1    LIMIT 3\n    console.log(\"find:\", res);\n  });\n};\n\ndoDemo();\n```\n\nMore in [Basic Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/basic.js).\n\n# Overview\n\n`Note`: '?' is a Optional\n\n### ClickhouseOrm\n\n`db` : object<{name:string, engine?:string, cluster?:string}>\n\n> name: database name\n\n> engine?: database engine\n\n> cluster?: cluster name\n\n`debug` : boolean\n\n> Default: false\n\n`client` : object\n\n> Drive configuration. More in [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n### Schema\n\n`tableName` : string\n\n> It is the table name.\n\n`schema` : { [column]: { type?, default? } }\n\n> The `type` will be verified, The `default` is the default value for column.\n\n`createTable` : string\n\n> It is the SQL for creating tables.When model is executed, this SQL will be executed. It is suggested to add 'IF NOT EXISTS'.\n\nWatch out !!! >>>>> If the table already exists and you want to modify it. You need to execute the modification sql through other clients（Such as Remote terminal） and update the code of the Schema!!!\n\n```javascript\nconst table1Schema = {\n  // table name\n  tableName: \"table1\",\n  // define column\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n\n// register schema and create [if] table\nconst Table1Model = await chOrm.model(table1Schema);\n```\n\n### DATA_TYPE\n\nThe clickhouse data types. Some types are defined here.\n\nColumns with defined types will be verified. It only checks the basic type of data, not the most standard value. They are `number | string | boolean | date`.\n\n```javascript\nexport enum DATA_TYPE {\n  UInt8 = 'number',\n  UInt16 = 'number',\n  UInt32 = 'number',\n  UInt64 = 'number',\n  UInt128 = 'number',\n  UInt256 = 'number',\n  Int8 = 'number',\n  Int16 = 'number',\n  Int32 = 'number',\n  Int64 = 'number',\n  Int128 = 'number',\n  Int256 = 'number',\n  Float32 = 'number',\n  Float64 = 'number',\n  Boolean = 'boolean',\n  String = 'string',\n  UUID = 'string',\n  Date = 'date|string|number',\n  Date32 = 'date|string|number',\n  DateTime = 'date|string|number',\n  DateTime64 = 'date|string|number',\n}\n```\n\n```javascript\nschema: {\n  time: { type: DATA_TYPE.DateTime, default: Date },\n  [column]: { type?, default? }\n}\n```\n\n### Log\n\nThe **setLogService** is a global configuration method and will affect all instances.\n\n`Default: console.log`\n\nCustom example: **[winston](https://github.com/winstonjs/winston)**\n\n```javascript\nconst { setLogService } = require(\"clickhouse-orm\");\nconst winston = require(\"winston\");\nconst logger = winston.createLogger();\n\nsetLogService(logger.info);\n```\n\n### Use SQL directly：\n\n```javascript\nchOrm.client\n  .query(`select * from orm_test.table1 limit 3`)\n  .toPromise()\n  .then((res) => {\n    console.log(\"Use sql:\", res);\n  });\n```\n\nThe `chOrm.client` is the [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse) instance.\n\n# [More Examples](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/more.ts)\n\n### Find\n\n```javascript\nimport * as dayjs from \"dayjs\";\n\nqueryExample1({\n  Model: Table1Model,\n  status: 1,\n  beginTime: dayjs().subtract(1, \"day\").format(\"YYYY-MM-DD HH:mm:ss\"),\n  endTime: dayjs().format(\"YYYY-MM-DD HH:mm:ss\"),\n}).then((res) => {\n  console.log(\"queryExample1:\", res);\n});\n\nconst queryExample1 = ({ Model, status, beginTime, endTime }) => {\n  let wheres = [],\n    where;\n  if (status) wheres.push(`status='${status}'`);\n  if (beginTime) wheres.push(`time>='${beginTime}'`);\n  if (endTime) wheres.push(`time<='${endTime}'`);\n  if (wheres.length > 0) where = wheres.join(\" and \");\n\n  return Model.find({\n    where,\n    select: `*`,\n    orderBy: \"time ASC\",\n    limit: 5,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT * from orm_test.table1 where status='1' and time>='2022-02-04 15:34:22' and time<='2022-02-05 15:34:22'  ORDER BY time ASC LIMIT 5\n```\n\n### Count\n\n```javascript\ncountExample1({\n  Model: Table1Model,\n}).then((res) => {\n  console.log(\"countExample1:\", res);\n});\n\nconst countExample1 = ({ Model }) => {\n  return Model.find({\n    select: `count(*) AS total`,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count(*) AS total from orm_test.table1\n```\n\n### GroupBy\n\n```javascript\nTable1Model.find({\n  select: `status,browser`,\n  groupBy: \"status,browser\",\n});\n```\n\nFinal executed SQL:\n\n```sql\nSELECT status,browser from orm_test.table1  GROUP BY status,browser\n```\n\n### Nested Queries\n\n```javascript\nTable1Model.find([\n  {\n    select: `browser`,\n    groupBy: \"browser\",\n  },\n  {\n    select: `count() as browserTotal`,\n  },\n]);\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count() as browserTotal from (SELECT browser from orm_test.table1  GROUP BY browser  )\n```\n\n### save\n\n```javascript\n// new data model\nconst data = Table1Model.build();\n\n// set value\ndata.time = new _Date_();\ndata.status = 1;\ndata.browser = \"chrome\";\ndata.browser_v = \"90.0.1.21\";\n\n// do save\ndata.save().then((res) => {\n  console.log(\"save:\", res);\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### create\n\n```javascript\n//do create\nawait Table1Model.create({\n  status: 1,\n  time: new Date(),\n  browser: \"chrome\",\n  browser_v: \"90.0.1.21\",\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### InsertMany\n\n```javascript\nconst list = [\n  { status: 2, browser: \"IE\", browser_v: \"10.0.1.21\" },\n  { status: 2, browser: \"FF\", browser_v: \"2.0.3\" },\n  { status: 3, browser: \"IE\", browser_v: \"1.1.1\" },\n];\n\nTable1Model.insertMany(list);\n// or\nTable1Model.insertMany(\n  list.map((item) => {\n    const data = Table1Model.build();\n    // set value\n    data.time = new Date();\n    data.status = item.status;\n    data.browser = item.browser;\n    data.browser_v = item.browser_v;\n    return data;\n  })\n);\n```\n\nFinal executed SQL:\n\n```sql\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"IE\",\"browser_v\":\"10.0.1.21\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"FF\",\"browser_v\":\"2.0.3\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":3,\"browser\":\"IE\",\"browser_v\":\"1.1.1\"}]\n```\n\n## cluster\n\n**Create a cluster instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_cluster_test\",\n    cluster: \"default_cluster\",\n  },\n  // ...other\n});\nconst table2Schema = {\n  // table name\n  tableName: \"table2\",\n  // create table sql\n  createTable: (dbTableName, db) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table2)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName} ON CLUSTER ${db.cluster}\n      ...other`;\n  },\n  ...other,\n};\n\n// create database 'orm_cluster_test'\n// SQL: CREATE DATABASE IF NOT EXISTS orm_cluster_test ON CLUSTER default_cluster\nawait chOrm.createDatabase();\n\n// register schema and create [if] table\n// createTable() SQL: CREATE TABLE IF NOT EXISTS orm_cluster_test.table2 ON CLUSTER default_cluster...\nconst Table1Model = await chOrm.model(table2Schema);\n```\n\n# Wechat Discussion\n\n[Click to join](https://github.com/zimv/node-clickhouse-orm/issues/3)\n","readmeFilename":"README.md","gitHead":"363ba5b46cfd0f59ffd0812ee07a07a8725cb491","_id":"clickhouse-orm@2.0.1-alpha.0","_nodeVersion":"16.15.1","_npmVersion":"7.12.0","dist":{"integrity":"sha512-dJv7aKZ34ozXiD/0HoYfcgLpCiHhLGAEKCe/6lccYVBD+TK/Ez+Vy48bBGINabL/Kd0bAvbwNVy7i5jTgqZhlg==","shasum":"61adee490acb68b76c4207293b4f3a85108f04d2","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-2.0.1-alpha.0.tgz","fileCount":50,"unpackedSize":72164,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQD46Bf4jKRXR5C7xJlxXxZsiJ7nYVSKbDzGChx12/IXvgIgEM2ZMz8n5zIn+/fOB+G3ULMWPKkE1tDh7VFlyWVVzfk="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjRAszACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmrN+Q//blwtJ+1vYXl5+QMKMEey4mGrghcXbOql5fXNCVTPHhfx7oII\r\naHEGizIbN4aCxu+SDiUV1ky5yADfajofh2eMs+sI2xE8DCPhKSaBdIsNjNHs\r\nPFCvkiehmBK+OoVYItsbpR/6DoFnOogq2VXE/IXI30moN7EZY1lPgcjmx/Js\r\ncRSsv3Sdihb2ptSKkPC+Mj0R79DE4bw193KbB4/bMbfutRi9VsRBj30S2d47\r\nvzjma6ExuXm06WCH6950t7LS/RTdBxAEFIVohT3nuxvmSqtzTLfgJ0bImbtr\r\ngg2uE9e56cuan1PTgeYx6wE9b+j4YvRfbEjtAd/domQLPgkFTJRccV/yjR6j\r\nyNdgg8y2AQRxn75wacXckqIxxPVSG7H+c7MNfcshs0w2sIN/0Zs0SJYpc+dC\r\nFYSNWm+Fko51vZK9HFA9Ft9pEw/Pp4EInpnWxIR8PANx7v332Xl6lJWAgR6Y\r\ngfFGpzyleOOxhP1EfrUDxkrzvc6l/J9GMBQ/sL+MaESmfVynjR6gf9DRu/U7\r\nZe3x4tWKYl7YPkOFz0PW5DRDu1jc9Ub9VPFnyA/aATEHRLnNmsXG3DAFbInc\r\n20kTzEmZ3NlROgzAjGkThaOynYBAovchT9PZOmjx11UtmmUbhN3bA7KF1XSf\r\nxnYCZpJXl+oearsF1ipuqdUrgb9eT0VSBiE=\r\n=tHdU\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_2.0.1-alpha.0_1665403698867_0.6763615043040365"},"_hasShrinkwrap":false},"2.0.1-alpha.1":{"name":"clickhouse-orm","version":"2.0.1-alpha.1","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","test":"jest --coverage"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/lib/index.js","types":"dist/lib/index.d.ts","readme":"<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://img.shields.io/npm/v/clickhouse-orm.svg\"></a>\n<a href=\"https://npms.io/search?q=clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://badges.npms.io/clickhouse-orm.svg\"></a>\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM total downloads\"><img src=\"https://img.shields.io/npm/dt/clickhouse-orm.svg\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github stars\"><img src=\"https://img.shields.io/github/stars/zimv/node-clickhouse-orm.svg?style=social&label=Star\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github forks\"><img src=\"https://img.shields.io/github/forks/zimv/node-clickhouse-orm.svg?style=social&label=Fork\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github contributors\"><img src=\"https://img.shields.io/github/contributors/zimv/node-clickhouse-orm.svg\"></a>\n\n# clickhouse-orm\n\nClickhouse ORM for Nodejs. Send query over HTTP interface. Using [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n# Install:\n\n```\nnpm i clickhouse-orm\n```\n\n# Usage\n\n**Create instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_test\",\n  },\n  debug: true,\n  client: {\n    url: \"localhost\",\n    port: \"8123\",\n    basicAuth: {\n      username: \"default\",\n      password: \"\",\n    },\n    debug: false,\n    isUseGzip: true,\n    format: \"json\", // \"json\" || \"csv\" || \"tsv\"\n  },\n});\n```\n\n**Define Schema：**\n\n```javascript\nconst table1Schema = {\n  // table name\n  tableName: \"table1\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n```\n\n**create / build + save / find：**\n\n```javascript\nconst doDemo = async () => {\n  // create database 'orm_test'\n  // SQL: CREATE DATABASE IF NOT EXISTS orm_test\n  await chOrm.createDatabase();\n\n  // register schema and create [if] table\n  // createTable() SQL: CREATE TABLE IF NOT EXISTS orm_test.table1...\n  const Table1Model = await chOrm.model(table1Schema);\n\n  // new data model\n  const data = Table1Model.build({ status: 2 });\n\n  // set value\n  data.time = new Date();\n  data.browser = \"chrome\";\n  data.browser_v = \"90.0.1.21\";\n\n  // do save\n  const res = await data.save();\n  // SQL: INSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":2,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\n  console.log(\"save:\", res);\n\n  // create === build + save\n  const resCreate = await Table1Model.create({\n    status: 1,\n    time: new Date(),\n    browser: \"chrome\",\n    browser_v: \"90.0.1.21\",\n  });\n  console.log(\"create:\", resCreate);\n\n  // do find\n  Table1Model.find({\n    select: \"*\",\n    limit: 3,\n  }).then((res) => {\n    // SQL: SELECT * from orm_test.table1    LIMIT 3\n    console.log(\"find:\", res);\n  });\n};\n\ndoDemo();\n```\n\nMore in [Basic Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/basic.js).\n\n# Overview\n\n`Note`: '?' is a Optional\n\n### ClickhouseOrm\n\n`db` : object<{name:string, engine?:string, cluster?:string}>\n\n> name: database name\n\n> engine?: database engine\n\n> cluster?: cluster name\n\n`debug` : boolean\n\n> Default: false\n\n`client` : object\n\n> Drive configuration. More in [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n### Schema\n\n`tableName` : string\n\n> It is the table name.\n\n`schema` : { [column]: { type?, default? } }\n\n> The `type` will be verified, The `default` is the default value for column.\n\n`createTable` : string\n\n> It is the SQL for creating tables.When model is executed, this SQL will be executed. It is suggested to add 'IF NOT EXISTS'.\n\nWatch out !!! >>>>> If the table already exists and you want to modify it. You need to execute the modification sql through other clients（Such as Remote terminal） and update the code of the Schema!!!\n\n```javascript\nconst table1Schema = {\n  // table name\n  tableName: \"table1\",\n  // define column\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n\n// register schema and create [if] table\nconst Table1Model = await chOrm.model(table1Schema);\n```\n\n### DATA_TYPE\n\nThe clickhouse data types. Some types are defined here.\n\nColumns with defined types will be verified. It only checks the basic type of data, not the most standard value. They are `number | string | boolean | date`.\n\n```javascript\nexport enum DATA_TYPE {\n  UInt8 = 'number',\n  UInt16 = 'number',\n  UInt32 = 'number',\n  UInt64 = 'number',\n  UInt128 = 'number',\n  UInt256 = 'number',\n  Int8 = 'number',\n  Int16 = 'number',\n  Int32 = 'number',\n  Int64 = 'number',\n  Int128 = 'number',\n  Int256 = 'number',\n  Float32 = 'number',\n  Float64 = 'number',\n  Boolean = 'boolean',\n  String = 'string',\n  UUID = 'string',\n  Date = 'date|string|number',\n  Date32 = 'date|string|number',\n  DateTime = 'date|string|number',\n  DateTime64 = 'date|string|number',\n}\n```\n\n```javascript\nschema: {\n  time: { type: DATA_TYPE.DateTime, default: Date },\n  [column]: { type?, default? }\n}\n```\n\n### Log\n\nThe **setLogService** is a global configuration method and will affect all instances.\n\n`Default: console.log`\n\nCustom example: **[winston](https://github.com/winstonjs/winston)**\n\n```javascript\nconst { setLogService } = require(\"clickhouse-orm\");\nconst winston = require(\"winston\");\nconst logger = winston.createLogger();\n\nsetLogService(logger.info);\n```\n\n### Use SQL directly：\n\n```javascript\nchOrm.client\n  .query(`select * from orm_test.table1 limit 3`)\n  .toPromise()\n  .then((res) => {\n    console.log(\"Use sql:\", res);\n  });\n```\n\nThe `chOrm.client` is the [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse) instance.\n\n# [More Examples](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/more.ts)\n\n### Find\n\n```javascript\nimport * as dayjs from \"dayjs\";\n\nqueryExample1({\n  Model: Table1Model,\n  status: 1,\n  beginTime: dayjs().subtract(1, \"day\").format(\"YYYY-MM-DD HH:mm:ss\"),\n  endTime: dayjs().format(\"YYYY-MM-DD HH:mm:ss\"),\n}).then((res) => {\n  console.log(\"queryExample1:\", res);\n});\n\nconst queryExample1 = ({ Model, status, beginTime, endTime }) => {\n  let wheres = [],\n    where;\n  if (status) wheres.push(`status='${status}'`);\n  if (beginTime) wheres.push(`time>='${beginTime}'`);\n  if (endTime) wheres.push(`time<='${endTime}'`);\n  if (wheres.length > 0) where = wheres.join(\" and \");\n\n  return Model.find({\n    where,\n    select: `*`,\n    orderBy: \"time ASC\",\n    limit: 5,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT * from orm_test.table1 where status='1' and time>='2022-02-04 15:34:22' and time<='2022-02-05 15:34:22'  ORDER BY time ASC LIMIT 5\n```\n\n### Count\n\n```javascript\ncountExample1({\n  Model: Table1Model,\n}).then((res) => {\n  console.log(\"countExample1:\", res);\n});\n\nconst countExample1 = ({ Model }) => {\n  return Model.find({\n    select: `count(*) AS total`,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count(*) AS total from orm_test.table1\n```\n\n### GroupBy\n\n```javascript\nTable1Model.find({\n  select: `status,browser`,\n  groupBy: \"status,browser\",\n});\n```\n\nFinal executed SQL:\n\n```sql\nSELECT status,browser from orm_test.table1  GROUP BY status,browser\n```\n\n### Nested Queries\n\n```javascript\nTable1Model.find([\n  {\n    select: `browser`,\n    groupBy: \"browser\",\n  },\n  {\n    select: `count() as browserTotal`,\n  },\n]);\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count() as browserTotal from (SELECT browser from orm_test.table1  GROUP BY browser  )\n```\n\n### save\n\n```javascript\n// new data model\nconst data = Table1Model.build();\n\n// set value\ndata.time = new _Date_();\ndata.status = 1;\ndata.browser = \"chrome\";\ndata.browser_v = \"90.0.1.21\";\n\n// do save\ndata.save().then((res) => {\n  console.log(\"save:\", res);\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### create\n\n```javascript\n//do create\nawait Table1Model.create({\n  status: 1,\n  time: new Date(),\n  browser: \"chrome\",\n  browser_v: \"90.0.1.21\",\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### InsertMany\n\n```javascript\nconst list = [\n  { status: 2, browser: \"IE\", browser_v: \"10.0.1.21\" },\n  { status: 2, browser: \"FF\", browser_v: \"2.0.3\" },\n  { status: 3, browser: \"IE\", browser_v: \"1.1.1\" },\n];\n\nTable1Model.insertMany(list);\n// or\nTable1Model.insertMany(\n  list.map((item) => {\n    const data = Table1Model.build();\n    // set value\n    data.time = new Date();\n    data.status = item.status;\n    data.browser = item.browser;\n    data.browser_v = item.browser_v;\n    return data;\n  })\n);\n```\n\nFinal executed SQL:\n\n```sql\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"IE\",\"browser_v\":\"10.0.1.21\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"FF\",\"browser_v\":\"2.0.3\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":3,\"browser\":\"IE\",\"browser_v\":\"1.1.1\"}]\n```\n\n## cluster\n\n**Create a cluster instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_cluster_test\",\n    cluster: \"default_cluster\",\n  },\n  // ...other\n});\nconst table2Schema = {\n  // table name\n  tableName: \"table2\",\n  // create table sql\n  createTable: (dbTableName, db) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table2)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName} ON CLUSTER ${db.cluster}\n      ...other`;\n  },\n  ...other,\n};\n\n// create database 'orm_cluster_test'\n// SQL: CREATE DATABASE IF NOT EXISTS orm_cluster_test ON CLUSTER default_cluster\nawait chOrm.createDatabase();\n\n// register schema and create [if] table\n// createTable() SQL: CREATE TABLE IF NOT EXISTS orm_cluster_test.table2 ON CLUSTER default_cluster...\nconst Table1Model = await chOrm.model(table2Schema);\n```\n\n# Wechat Discussion\n\n[Click to join](https://github.com/zimv/node-clickhouse-orm/issues/3)\n","readmeFilename":"README.md","gitHead":"363ba5b46cfd0f59ffd0812ee07a07a8725cb491","_id":"clickhouse-orm@2.0.1-alpha.1","_nodeVersion":"16.15.1","_npmVersion":"7.12.0","dist":{"integrity":"sha512-CEezFXfen52HAAtMURtp1yA/AijPXM9LP72PP1syP0Pl1mkJqjuWzOrG7zZzOunKrkddfNJdQpkEt+3gmo0nBw==","shasum":"e7b21dc4a61981c94b5df51109ae415bfc973edf","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-2.0.1-alpha.1.tgz","fileCount":70,"unpackedSize":89467,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQC4j+nDEvgm7A5b0A6MNB0iE8mAkCkLgoZ9nSnOdE90EAIhAI0hyX09ncMRAS2WKJCmoh7aFFLvDZw02n4Ps2KZyimA"}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjRAtMACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmomXA//fBp2b6O7hN7KeClJm2NprNMehfBQZbGyN2I9S5zcr8B/F/Mc\r\n4TKy4/qJfu+NuG1q8zaknWtg2b4h0GsKvuMoCW8Oh7iZHECcFkjCMAraUG9U\r\noQyPxv46TRvQIivmoRHMjGN+fBypvrlb4glytS/9hO6beViHlmkNK0is92+K\r\nj3hZUx1JHKWKc1WmgBSqiNJIFORj/cXiN/tNJ2lVJgHBNbY466D5+1NpjVDx\r\nxSZmX9zdS6ttwDCSb5RIlc0A/pqfRRVcDlO058OJLmh+CxbGzFZwLKMCa2j7\r\n2kFoSiqNjgsFOt1w7zEeObtQSjTvL03151EO4YkZnNZccHSsKCHl+7dgbkIf\r\npTI5l2zAFZ9QCiXJWGI8zaCfBmfrssdks40GtI1zuMWfCx4lpir/zbgi/Ycv\r\naH5clzfbyssDbqNcFXa64ZZbJGmU6pxdoZSCxE4dORt2kv58T66274JyXXq4\r\noSkJdD2rfMb+Le6PIC6nlLwmL5j6PWUm5epanCOemZzFGox7ZEr3CR38iPAa\r\n3RjpyBfvhEUuWwJR+8gOpJbQXj0oEYV7OLOdklUHTp02v6oID7Uksq8KV2Mi\r\nAqjQ6nVzs/V4dKv/IwXIcpzgDdjNNwWSOWUZo6XyltlJttkaXdvC+9V3e/1Z\r\nT0THsW7waHdTRx1wMr4Np2Tl65eKO8kglG4=\r\n=238K\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_2.0.1-alpha.1_1665403723986_0.8121333342985817"},"_hasShrinkwrap":false},"2.0.1":{"name":"clickhouse-orm","version":"2.0.1","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","test":"jest --coverage"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/lib/index.js","types":"dist/lib/index.d.ts","gitHead":"82e5970a9bf2992405e9fc1826128b0ab165df53","_id":"clickhouse-orm@2.0.1","_nodeVersion":"16.15.1","_npmVersion":"7.12.0","dist":{"integrity":"sha512-9pYoZF9AMh1cnQnKtLddLAOwhzLbjRiqRilzdGJZg3YBZM0oCqsuIL44wHj5SrwvkRIGxu+uwP8pC2nNIkfDvw==","shasum":"db693eaa67c4ad03ad8bb37615684a8c34d9c09c","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-2.0.1.tgz","fileCount":70,"unpackedSize":89459,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDdi3gO9GRrYK/EArm8lFlTEtH0ac74nIq3FeThHd5+AwIhAO2kr+Klq/pSfGD/0ZBwh1w8/EHHWxsyirJNH59jQW3J"}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjRn0FACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmrDhw//XBN7C/BaSJ0DqfitmOYs5JNHp2U3pM/yjI8xOMywkrEOUz+n\r\n55Eo4eFejbHUgEuFQLMfrOW5w3oxMTAQFBJBB11LHBmaKiZ1VVMvE8ul2maH\r\nl/CxBLbunH0GZJDrTHxdc4VT16hTcJ9j4RjNcr8iUxvwEToX2asPWp1mLB0o\r\nBUvo0gaJvfs+CaN1dlo0WN583Er4Z8BFMj7QcaXiRVltQignxQy3SV8pggSZ\r\n4B+/2YgXHCpuuAK9ygfr3XDpjAVokfH3dLxsJTLe/ZuIgh+T3k1Vw6wiEy1H\r\njuFlc6M4n7KHoM52e/ugXEtRVeOftmp+5z7/Si0L8ilEi6IxVskeGxI+yKZE\r\nf55pGw41DYfm7KwoQjmAWOzmVZPCygHlGf9EmvpZPq3LIHOdLam6hHO9T4+A\r\nJl5hYdyZmUfDcu9CAewI6JkiBW8z0M2VJYDpCsk8ypkmPnygwS49iq19HUXH\r\nN6R7YSpw5f/FltMFFVWOBXodv5+v7Ydwlca5SOI+5zYBgY0B2o9wvNXV0XZk\r\nW9WhXNC7INsuv60o+oF3BtI8u3DJo+3CAg7wPSXH7mNvHCTvIVeA1BK7Sif5\r\nN+EmWFPQVy+DYdvZo9U1kxUJqe6sPbz8ttOccwhF+HBlp1VM/rLUnjcVRvmG\r\n5eX5h0tnTWBJiYspzxOL2ENwRJlFKkH+U2M=\r\n=Znnm\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_2.0.1_1665563909043_0.2438866838043956"},"_hasShrinkwrap":false},"2.0.2-beta":{"name":"clickhouse-orm","version":"2.0.2-beta","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","test":"jest --coverage"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/lib/index.js","types":"dist/lib/index.d.ts","readme":"<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://img.shields.io/npm/v/clickhouse-orm.svg\"></a>\n<a href=\"https://npms.io/search?q=clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://badges.npms.io/clickhouse-orm.svg\"></a>\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM total downloads\"><img src=\"https://img.shields.io/npm/dt/clickhouse-orm.svg\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github stars\"><img src=\"https://img.shields.io/github/stars/zimv/node-clickhouse-orm.svg?style=social&label=Star\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github forks\"><img src=\"https://img.shields.io/github/forks/zimv/node-clickhouse-orm.svg?style=social&label=Fork\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github contributors\"><img src=\"https://img.shields.io/github/contributors/zimv/node-clickhouse-orm.svg\"></a>\n\n# clickhouse-orm\n\n[![Join the chat at https://gitter.im/zimv/node-clickhouse-orm](https://badges.gitter.im/zimv/node-clickhouse-orm.svg)](https://gitter.im/zimv/node-clickhouse-orm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n\nClickhouse ORM for Nodejs. Send query over HTTP interface. Using [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n# Install:\n\n```\nnpm i clickhouse-orm\n```\n\n# Usage\n\n**Create instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_test\",\n  },\n  debug: true,\n  client: {\n    url: \"localhost\",\n    port: \"8123\",\n    basicAuth: {\n      username: \"default\",\n      password: \"\",\n    },\n    debug: false,\n    isUseGzip: true,\n    format: \"json\", // \"json\" || \"csv\" || \"tsv\"\n  },\n});\n```\n\n**Define Schema：**\n\n```javascript\nconst table1Schema = {\n  // table name\n  tableName: \"table1\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n```\n\n**create / build + save / find：**\n\n```javascript\nconst doDemo = async () => {\n  // create database 'orm_test'\n  // SQL: CREATE DATABASE IF NOT EXISTS orm_test\n  await chOrm.createDatabase();\n\n  // register schema and create [if] table\n  // createTable() SQL: CREATE TABLE IF NOT EXISTS orm_test.table1...\n  const Table1Model = await chOrm.model(table1Schema);\n\n  // new data model\n  const data = Table1Model.build({ status: 2 });\n\n  // set value\n  data.time = new Date();\n  data.browser = \"chrome\";\n  data.browser_v = \"90.0.1.21\";\n\n  // do save\n  const res = await data.save();\n  // SQL: INSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":2,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\n  console.log(\"save:\", res);\n\n  // create === build + save\n  const resCreate = await Table1Model.create({\n    status: 1,\n    time: new Date(),\n    browser: \"chrome\",\n    browser_v: \"90.0.1.21\",\n  });\n  console.log(\"create:\", resCreate);\n\n  // do find\n  Table1Model.find({\n    select: \"*\",\n    limit: 3,\n  }).then((res) => {\n    // SQL: SELECT * from orm_test.table1    LIMIT 3\n    console.log(\"find:\", res);\n  });\n};\n\ndoDemo();\n```\n\nMore in [Basic Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/basic.js).\n\n# Overview\n\n`Note`: '?' is a Optional\n\n### ClickhouseOrm\n\n`db` : object<{name:string, engine?:string, cluster?:string}>\n\n> name: database name\n\n> engine?: database engine\n\n> cluster?: cluster name\n\n`debug` : boolean\n\n> Default: false\n\n`client` : object\n\n> Drive configuration. More in [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n### Schema\n\n`tableName` : string\n\n> It is the table name.\n\n`schema` : { [column]: { type?, default? } }\n\n> The `type` will be verified, The `default` is the default value for column.\n\n`createTable` : string\n\n> It is the SQL for creating tables.When model is executed, this SQL will be executed. It is suggested to add 'IF NOT EXISTS'.\n\nWatch out !!! >>>>> If the table already exists and you want to modify it. You need to execute the modification sql through other clients（Such as Remote terminal） and update the code of the Schema!!!\n\n```javascript\nconst table1Schema = {\n  // table name\n  tableName: \"table1\",\n  // define column\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n\n// register schema and create [if] table\nconst Table1Model = await chOrm.model(table1Schema);\n```\n\n### DATA_TYPE\n\nThe clickhouse data types. Some types are defined here.\n\nColumns with defined types will be verified. It only checks the basic type of data, not the most standard value. They are `number | string | boolean | date`.\n\n```javascript\nexport enum DATA_TYPE {\n  UInt8 = 'number',\n  UInt16 = 'number',\n  UInt32 = 'number',\n  UInt64 = 'number',\n  UInt128 = 'number',\n  UInt256 = 'number',\n  Int8 = 'number',\n  Int16 = 'number',\n  Int32 = 'number',\n  Int64 = 'number',\n  Int128 = 'number',\n  Int256 = 'number',\n  Float32 = 'number',\n  Float64 = 'number',\n  Boolean = 'boolean',\n  String = 'string',\n  UUID = 'string',\n  Date = 'date|string|number',\n  Date32 = 'date|string|number',\n  DateTime = 'date|string|number',\n  DateTime64 = 'date|string|number',\n}\n```\n\n```javascript\nschema: {\n  time: { type: DATA_TYPE.DateTime, default: Date },\n  [column]: { type?, default? }\n}\n```\n\n### Log\n\nThe **setLogService** is a global configuration method and will affect all instances.\n\n`Default: console.log`\n\nCustom example: **[winston](https://github.com/winstonjs/winston)**\n\n```javascript\nconst { setLogService } = require(\"clickhouse-orm\");\nconst winston = require(\"winston\");\nconst logger = winston.createLogger();\n\nsetLogService(logger.info);\n```\n\n### Use SQL directly：\n\n```javascript\nchOrm.client\n  .query(`select * from orm_test.table1 limit 3`)\n  .toPromise()\n  .then((res) => {\n    console.log(\"Use sql:\", res);\n  });\n```\n\nThe `chOrm.client` is the [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse) instance.\n\n# [More Examples](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/more.ts)\n\n### Find\n\n```javascript\nimport * as dayjs from \"dayjs\";\n\nqueryExample1({\n  Model: Table1Model,\n  status: 1,\n  beginTime: dayjs().subtract(1, \"day\").format(\"YYYY-MM-DD HH:mm:ss\"),\n  endTime: dayjs().format(\"YYYY-MM-DD HH:mm:ss\"),\n}).then((res) => {\n  console.log(\"queryExample1:\", res);\n});\n\nconst queryExample1 = ({ Model, status, beginTime, endTime }) => {\n  let wheres = [],\n    where;\n  if (status) wheres.push(`status='${status}'`);\n  if (beginTime) wheres.push(`time>='${beginTime}'`);\n  if (endTime) wheres.push(`time<='${endTime}'`);\n  if (wheres.length > 0) where = wheres.join(\" and \");\n\n  return Model.find({\n    where,\n    select: `*`,\n    orderBy: \"time ASC\",\n    limit: 5,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT * from orm_test.table1 where status='1' and time>='2022-02-04 15:34:22' and time<='2022-02-05 15:34:22'  ORDER BY time ASC LIMIT 5\n```\n\n### Count\n\n```javascript\ncountExample1({\n  Model: Table1Model,\n}).then((res) => {\n  console.log(\"countExample1:\", res);\n});\n\nconst countExample1 = ({ Model }) => {\n  return Model.find({\n    select: `count(*) AS total`,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count(*) AS total from orm_test.table1\n```\n\n### GroupBy\n\n```javascript\nTable1Model.find({\n  select: `status,browser`,\n  groupBy: \"status,browser\",\n});\n```\n\nFinal executed SQL:\n\n```sql\nSELECT status,browser from orm_test.table1  GROUP BY status,browser\n```\n\n### Nested Queries\n\n```javascript\nTable1Model.find([\n  {\n    select: `browser`,\n    groupBy: \"browser\",\n  },\n  {\n    select: `count() as browserTotal`,\n  },\n]);\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count() as browserTotal from (SELECT browser from orm_test.table1  GROUP BY browser  )\n```\n\n### save\n\n```javascript\n// new data model\nconst data = Table1Model.build();\n\n// set value\ndata.time = new _Date_();\ndata.status = 1;\ndata.browser = \"chrome\";\ndata.browser_v = \"90.0.1.21\";\n\n// do save\ndata.save().then((res) => {\n  console.log(\"save:\", res);\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### create\n\n```javascript\n//do create\nawait Table1Model.create({\n  status: 1,\n  time: new Date(),\n  browser: \"chrome\",\n  browser_v: \"90.0.1.21\",\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### InsertMany\n\n```javascript\nconst list = [\n  { status: 2, browser: \"IE\", browser_v: \"10.0.1.21\" },\n  { status: 2, browser: \"FF\", browser_v: \"2.0.3\" },\n  { status: 3, browser: \"IE\", browser_v: \"1.1.1\" },\n];\n\nTable1Model.insertMany(list);\n// or\nTable1Model.insertMany(\n  list.map((item) => {\n    const data = Table1Model.build();\n    // set value\n    data.time = new Date();\n    data.status = item.status;\n    data.browser = item.browser;\n    data.browser_v = item.browser_v;\n    return data;\n  })\n);\n```\n\nFinal executed SQL:\n\n```sql\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"IE\",\"browser_v\":\"10.0.1.21\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"FF\",\"browser_v\":\"2.0.3\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":3,\"browser\":\"IE\",\"browser_v\":\"1.1.1\"}]\n```\n\n### delete\n\n```javascript\n\nTable1Model.delete({\n  where: `browser='Chrome'`,\n})\n```\n\nFinal executed SQL:\n\n```sql\nALTER TABLE orm_test.table1  DELETE  WHERE browser='Chrome'\n```\n\n## cluster\n\n**Create a cluster instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_cluster_test\",\n    cluster: \"default_cluster\",\n  },\n  // ...other\n});\nconst table2Schema = {\n  // table name\n  tableName: \"table2\",\n  // create table sql\n  createTable: (dbTableName, db) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table2)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName} ON CLUSTER ${db.cluster}\n      ...other`;\n  },\n  ...other,\n};\n\n// create database 'orm_cluster_test'\n// SQL: CREATE DATABASE IF NOT EXISTS orm_cluster_test ON CLUSTER default_cluster\nawait chOrm.createDatabase();\n\n// register schema and create [if] table\n// createTable() SQL: CREATE TABLE IF NOT EXISTS orm_cluster_test.table2 ON CLUSTER default_cluster...\nconst Table2Model = await chOrm.model(table2Schema);\n```\n\n# Wechat Discussion\n\n[Click to join](https://github.com/zimv/node-clickhouse-orm/issues/3)\n","readmeFilename":"README.md","gitHead":"6822c793931f06e84e74f9a13adb7f6f2af48156","_id":"clickhouse-orm@2.0.2-beta","_nodeVersion":"16.15.1","_npmVersion":"9.2.0","dist":{"integrity":"sha512-9aOERPe0zQ1PsJfRMa33Tb9w/S9M0q+DvP0DgF6QxTEsHkDqjVYMr9bjHINLy9+OtAu22Qf5pa5vUANjyZocTw==","shasum":"394cf3d3e54e835158c09f57ebdbec29901b20a6","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-2.0.2-beta.tgz","fileCount":54,"unpackedSize":76651,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICrn8Wu/8r67w6GOqvTBeRh9buUP9irT49t/JZ7NEE+4AiB0WfqJhai6sHjEkwU2LV2ewFGK6CTEHSGhAzdxlKCT3A=="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjrAtCACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmqEFw/+Jaxu4hitm3f0AWXGTVSyE1QMcVo2Ngd9zIYvjavC5pZt+mxm\r\nOMQOKTX2r/qsKHqkbd9v2rqrqu2+LsWwYyzKNaUZjp7/G8U0ArYUsDfRE6yn\r\nzAK5Kbsc3M3LA76ICG9qjxghw3xBbzV85dbTMmHPLwDBFaCRwvebTelX/j/P\r\nMs6WOCt/MxA4TSHvmKVTZLMEv7k33zSEhnYJJ/tWKJSV3D+WXEkH7V6M02yQ\r\n99BtQHGc1FwCDBxBmt9BrCowVRXNp7wewCrxtnCTh4mAXva+ZMMmcrifJVFN\r\nf/13eKBNzfBPGkztG8rXmrZFsTExtOzeMGntNMWKG+k0ynCYIyJjugLFtZLl\r\n0ZC8T0qftXwehcgXirdluDxgFBFB45NymJGt9V88dwPloTJX4ykvygy2p2X+\r\nOpN0kfW9UwK3anah/LgNofW/QpsH7Voj05c6X7ViLcgvVfDQYFyAAiMWzTOy\r\nCUkFRSMBuD3hGR1e8rNmtYhlIqqxWKZrf8jTRF3foHhKtuxuMzjkyollqTJ/\r\nc9ZfhtH3uiJcBUrKN1fgvPn6LNkvRLHLn28y396zNjmXKTlGCQkZq+AysS1e\r\npv+vQjedLsjIDA/TkLbNClRKMySBEZZy6P3ME/DWPpaNh5woN2qGBOqnMS06\r\nPe+9Mv5bpjeQhlUGITGzZXAtnOfvLgIWDeg=\r\n=N6RT\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_2.0.2-beta_1672219457958_0.7705821005174991"},"_hasShrinkwrap":false},"2.0.2":{"name":"clickhouse-orm","version":"2.0.2","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","test":"jest --coverage"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/lib/index.js","types":"dist/lib/index.d.ts","gitHead":"59b9a236f83af74704fa10e0f8bb017d7b512d5a","_id":"clickhouse-orm@2.0.2","_nodeVersion":"16.15.1","_npmVersion":"9.2.0","dist":{"integrity":"sha512-lgRaiRFyu4D3KkjgTuYyCjIenlUCO92WxSIE93usiC9/EfM4pE+VWsPgjxVgUAUd+9W+b5jPLkaFebH2IheIUw==","shasum":"9eecd778254585385ca3496006830b01b877d049","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-2.0.2.tgz","fileCount":54,"unpackedSize":76646,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIDQNt7USGGrikUbgf1KrUhrfs80QRhD9r1N+/xjXuv21AiEAi2Uya/MyxFa2gl4BT5CE7OaKkm8sMYzTPSN2Zb1DoHk="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjrBEBACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmpAJhAAj0DRHLqGkh+J1IBKS4hJsyhv5lC7UUkchDUSQDCEGr/oa0Lm\r\nFW9mv+b0tlLlYylVYknQbUs5yEH2W1ib/ITjS3PVGulaE/rgVY+Sr0kSUiSB\r\nJOsqsZ65Haakw7jPiiQ9BJ2rN64mcDPfx1YYXh6TWzBhjKhvkwmz76H9ZJOx\r\n+dDG3WD9y7qsVShrdTuH99kR/QqRMI3t1hPO5btgO4qXIfmrTdQc7mhdOzQ7\r\n5TTMHOu2DqkYwkK3zYGzkx/vJaMfCkrtnsaPwSQSLFEY8boerjbkyLEWAtxp\r\nCa2EEGXW38Q5ADvzLVNnzh+P5i1r1uaZ39Yf6vWuu/+viJqgW8kjIiv7vd4o\r\noCK07pBc2cvUAQhH4oD9hwA47A5wMspmu2NO0N0bG09aBZ6lMmyeqReP66ut\r\nSJ/9LWXjM7ydCULR1M7OWOenogV5ECWgc+nUZlR+nX3EAKxAmuk8ddHNNQz0\r\nsgM10WValGqsI0WH4OcSXPffBw3Qe/3zc+nWKGmVnI9VAB77hbINSVx+93H1\r\nQ8y0RDUw7r/xNeeNZv/7rjSH9SPYWIkLglCPtyG8Vk0bKlNaJMGisQyQbwF/\r\n8Iv6m1R7veqdyK9U+SGhCd513+h0Yncclsuus5W+o7rOHq42GhsSH964l/Lo\r\niL8gi00Wu4eS6+hN5ZohPvpbONAV6n8hEKk=\r\n=0nGe\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_2.0.2_1672220929587_0.6972709947913012"},"_hasShrinkwrap":false},"3.0.0-alpha":{"name":"clickhouse-orm","version":"3.0.0-alpha","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","build":"rm -rf ./dist & npm run tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","ts-full":"ts-node ./examples/full-datatype.ts","ts-sync":"ts-node ./examples/sync-table.ts","test":"jest --coverage"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/lib/index.js","types":"dist/lib/index.d.ts","readme":"<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://img.shields.io/npm/v/clickhouse-orm.svg\"></a>\n<a href=\"https://npms.io/search?q=clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://badges.npms.io/clickhouse-orm.svg\"></a>\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM total downloads\"><img src=\"https://img.shields.io/npm/dt/clickhouse-orm.svg\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github stars\"><img src=\"https://img.shields.io/github/stars/zimv/node-clickhouse-orm.svg?style=social&label=Star\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github forks\"><img src=\"https://img.shields.io/github/forks/zimv/node-clickhouse-orm.svg?style=social&label=Fork\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github contributors\"><img src=\"https://img.shields.io/github/contributors/zimv/node-clickhouse-orm.svg\"></a>\n\n# clickhouse-orm\n\n[![Join the chat at https://gitter.im/zimv/node-clickhouse-orm](https://badges.gitter.im/zimv/node-clickhouse-orm.svg)](https://gitter.im/zimv/node-clickhouse-orm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n\nClickhouse ORM for Nodejs. Send query over HTTP interface. Using [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n# Install:\n\n```\nnpm i clickhouse-orm\n```\n\n# Usage\n\n**Create instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_test\",\n  },\n  debug: true,\n  client: {\n    url: \"localhost\",\n    port: \"8123\",\n    basicAuth: {\n      username: \"default\",\n      password: \"\",\n    },\n    debug: false,\n    isUseGzip: true,\n    format: \"json\", // \"json\" || \"csv\" || \"tsv\"\n  },\n});\n```\n\n**Define Schema：**\n\n```javascript\nconst table1Schema = {\n  // table name\n  tableName: \"table1\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n```\n\n**create / build + save / find：**\n\n```javascript\nconst doDemo = async () => {\n  // create database 'orm_test'\n  // SQL: CREATE DATABASE IF NOT EXISTS orm_test\n  await chOrm.createDatabase();\n\n  // register schema and create [if] table\n  // createTable() SQL: CREATE TABLE IF NOT EXISTS orm_test.table1...\n  const Table1Model = await chOrm.model(table1Schema);\n\n  // new data model\n  const data = Table1Model.build({ status: 2 });\n\n  // set value\n  data.time = new Date();\n  data.browser = \"chrome\";\n  data.browser_v = \"90.0.1.21\";\n\n  // do save\n  const res = await data.save();\n  // SQL: INSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":2,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\n  console.log(\"save:\", res);\n\n  // create === build + save\n  const resCreate = await Table1Model.create({\n    status: 1,\n    time: new Date(),\n    browser: \"chrome\",\n    browser_v: \"90.0.1.21\",\n  });\n  console.log(\"create:\", resCreate);\n\n  // do find\n  Table1Model.find({\n    select: \"*\",\n    limit: 3,\n  }).then((res) => {\n    // SQL: SELECT * from orm_test.table1    LIMIT 3\n    console.log(\"find:\", res);\n  });\n};\n\ndoDemo();\n```\n\nMore in [Basic Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/basic.js).\n\n# Overview\n\n`Note`: '?' is a Optional\n\n### ClickhouseOrm\n\n`db` : object<{name:string, engine?:string, cluster?:string}>\n\n> name: database name\n\n> engine?: database engine\n\n> cluster?: cluster name\n\n`debug` : boolean\n\n> Default: false\n\n`client` : object\n\n> Drive configuration. More in [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n### Schema\n\n`tableName` : string\n\n> It is the table name.\n\n`schema` : { [column]: { type?, default? } }\n\n> The `type` will be verified, The `default` is the default value for column.\n\n`createTable` : string\n\n> It is the SQL for creating tables.When model is executed, this SQL will be executed. It is suggested to add 'IF NOT EXISTS'.\n\nWatch out !!! >>>>> If the table already exists and you want to modify it. You need to execute the modification sql through other clients（Such as Remote terminal） and update the code of the Schema!!!\n\n```javascript\nconst table1Schema = {\n  // table name\n  tableName: \"table1\",\n  // define column\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n\n// register schema and create [if] table\nconst Table1Model = await chOrm.model(table1Schema);\n```\n\n### DATA_TYPE\n\nThe clickhouse data types. Some types are defined here.\n\nColumns with defined types will be verified. It only checks the basic type of data, not the most standard value. They are `number | string | boolean | date`.\n\n```javascript\nexport enum DATA_TYPE {\n  UInt8 = 'number',\n  UInt16 = 'number',\n  UInt32 = 'number',\n  UInt64 = 'number',\n  UInt128 = 'number',\n  UInt256 = 'number',\n  Int8 = 'number',\n  Int16 = 'number',\n  Int32 = 'number',\n  Int64 = 'number',\n  Int128 = 'number',\n  Int256 = 'number',\n  Float32 = 'number',\n  Float64 = 'number',\n  Boolean = 'boolean',\n  String = 'string',\n  UUID = 'string',\n  Date = 'date|string|number',\n  Date32 = 'date|string|number',\n  DateTime = 'date|string|number',\n  DateTime64 = 'date|string|number',\n}\n```\n\n```javascript\nschema: {\n  time: { type: DATA_TYPE.DateTime, default: Date },\n  [column]: { type?, default? }\n}\n```\n\n### Log\n\nThe **setLogService** is a global configuration method and will affect all instances.\n\n`Default: console.log`\n\nCustom example: **[winston](https://github.com/winstonjs/winston)**\n\n```javascript\nconst { setLogService } = require(\"clickhouse-orm\");\nconst winston = require(\"winston\");\nconst logger = winston.createLogger();\n\nsetLogService(logger.info);\n```\n\n### Use SQL directly：\n\n```javascript\nchOrm.client\n  .query(`select * from orm_test.table1 limit 3`)\n  .toPromise()\n  .then((res) => {\n    console.log(\"Use sql:\", res);\n  });\n```\n\nThe `chOrm.client` is the [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse) instance.\n\n# [More Examples](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/more.ts)\n\n### Find\n\n```javascript\nimport * as dayjs from \"dayjs\";\n\nqueryExample1({\n  Model: Table1Model,\n  status: 1,\n  beginTime: dayjs().subtract(1, \"day\").format(\"YYYY-MM-DD HH:mm:ss\"),\n  endTime: dayjs().format(\"YYYY-MM-DD HH:mm:ss\"),\n}).then((res) => {\n  console.log(\"queryExample1:\", res);\n});\n\nconst queryExample1 = ({ Model, status, beginTime, endTime }) => {\n  let wheres = [],\n    where;\n  if (status) wheres.push(`status='${status}'`);\n  if (beginTime) wheres.push(`time>='${beginTime}'`);\n  if (endTime) wheres.push(`time<='${endTime}'`);\n  if (wheres.length > 0) where = wheres.join(\" and \");\n\n  return Model.find({\n    where,\n    select: `*`,\n    orderBy: \"time ASC\",\n    limit: 5,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT * from orm_test.table1 where status='1' and time>='2022-02-04 15:34:22' and time<='2022-02-05 15:34:22'  ORDER BY time ASC LIMIT 5\n```\n\n### Count\n\n```javascript\ncountExample1({\n  Model: Table1Model,\n}).then((res) => {\n  console.log(\"countExample1:\", res);\n});\n\nconst countExample1 = ({ Model }) => {\n  return Model.find({\n    select: `count(*) AS total`,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count(*) AS total from orm_test.table1\n```\n\n### GroupBy\n\n```javascript\nTable1Model.find({\n  select: `status,browser`,\n  groupBy: \"status,browser\",\n});\n```\n\nFinal executed SQL:\n\n```sql\nSELECT status,browser from orm_test.table1  GROUP BY status,browser\n```\n\n### Nested Queries\n\n```javascript\nTable1Model.find([\n  {\n    select: `browser`,\n    groupBy: \"browser\",\n  },\n  {\n    select: `count() as browserTotal`,\n  },\n]);\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count() as browserTotal from (SELECT browser from orm_test.table1  GROUP BY browser  )\n```\n\n### save\n\n```javascript\n// new data model\nconst data = Table1Model.build();\n\n// set value\ndata.time = new _Date_();\ndata.status = 1;\ndata.browser = \"chrome\";\ndata.browser_v = \"90.0.1.21\";\n\n// do save\ndata.save().then((res) => {\n  console.log(\"save:\", res);\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### create\n\n```javascript\n//do create\nawait Table1Model.create({\n  status: 1,\n  time: new Date(),\n  browser: \"chrome\",\n  browser_v: \"90.0.1.21\",\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### InsertMany\n\n```javascript\nconst list = [\n  { status: 2, browser: \"IE\", browser_v: \"10.0.1.21\" },\n  { status: 2, browser: \"FF\", browser_v: \"2.0.3\" },\n  { status: 3, browser: \"IE\", browser_v: \"1.1.1\" },\n];\n\nTable1Model.insertMany(list);\n// or\nTable1Model.insertMany(\n  list.map((item) => {\n    const data = Table1Model.build();\n    // set value\n    data.time = new Date();\n    data.status = item.status;\n    data.browser = item.browser;\n    data.browser_v = item.browser_v;\n    return data;\n  })\n);\n```\n\nFinal executed SQL:\n\n```sql\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"IE\",\"browser_v\":\"10.0.1.21\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"FF\",\"browser_v\":\"2.0.3\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":3,\"browser\":\"IE\",\"browser_v\":\"1.1.1\"}]\n```\n\n### delete\n\n```javascript\n\nTable1Model.delete({\n  where: `browser='Chrome'`,\n})\n```\n\nFinal executed SQL:\n\n```sql\nALTER TABLE orm_test.table1  DELETE  WHERE browser='Chrome'\n```\n\n## cluster\n\n**Create a cluster instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_cluster_test\",\n    cluster: \"default_cluster\",\n  },\n  // ...other\n});\nconst table2Schema = {\n  // table name\n  tableName: \"table2\",\n  // create table sql\n  createTable: (dbTableName, db) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table2)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName} ON CLUSTER ${db.cluster}\n      ...other`;\n  },\n  ...other,\n};\n\n// create database 'orm_cluster_test'\n// SQL: CREATE DATABASE IF NOT EXISTS orm_cluster_test ON CLUSTER default_cluster\nawait chOrm.createDatabase();\n\n// register schema and create [if] table\n// createTable() SQL: CREATE TABLE IF NOT EXISTS orm_cluster_test.table2 ON CLUSTER default_cluster...\nconst Table2Model = await chOrm.model(table2Schema);\n```\n\n# Wechat Discussion\n\n[Click to join](https://github.com/zimv/node-clickhouse-orm/issues/3)\n","readmeFilename":"README.md","gitHead":"135fb0fe9193fac7776804fe465a27b795098bae","_id":"clickhouse-orm@3.0.0-alpha","_nodeVersion":"14.18.3","_npmVersion":"9.2.0","dist":{"integrity":"sha512-+5NcQWgDnHIwfNPsPBrQovdH1AUFRvFQS+dKTDIhQYEBWW6fZ2se9skXwmA28nECkIuurT0VYF0T+MbsyBwXXQ==","shasum":"9e1de92cd0eeafea75d1f1882c2e1a2b9205dd71","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-3.0.0-alpha.tgz","fileCount":26,"unpackedSize":65766,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDjkFcGmjSP7YiVrzveIqhkXtomZrjVnqkXD9C2kKrANAIhALsKuJbUC3Ms2WN33ACZUwTGm1cGR5WZk9vJfqJCNbgs"}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjtro/ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmrjeg//fosuitXSXjQ4j+7QYc/FFMvST/hVX66pn+ctVHPZp9TcCPn+\r\nMyqUdSGY81JAE+/3aLTtizRcGXlVX/w3IAJ2SudAXJqwjJeFh5KnR0ZXmp+2\r\nvVZP19oU7mY/m3qEpah04lulfqN2B0Pzl6zMqrkYWptbL/IZfTzkgUCJUW82\r\nRyY3DAq3+Pt6JTBlRexCElOesTDdrbVJVLBcNEnbmTkfqflZXLShF21nkDeP\r\nNxomHL1EZ4zLN6yXwThHHLjD/A8nKKRAI89/04V1h8fZEQRJjTfS9dwv4QA5\r\nONkJ4TlVFVU4X6pvn3sHR8JFxLtzoevGv1Pzd6CrwKQadIIcjqhjCbQia/B+\r\n7mQBXopWIlCdk9PJKkYolQRGNJmDGPisW/2jj1eB0ho5MoOSoPHoL0v/5C3z\r\nrJIRYWGhoFZQrDgACPC8V1PlY9WTZgUz7RjCJFvGeb2XKH99NoItj9jaAsTP\r\n8Da4aku3M9PJjo1q4ENQaLCeUMMCm5RrZaWh8FPUFkD7FJ6UDBu7sgYsTUIq\r\n5aCA2/y8DGrspYi2TACnsFEPFshLRn07hOP/ktPigc0E12/mCmT5/O8iesCG\r\nXs+rvL2nkPlx0CMUqtNLjgY3oyXHqWBhUM+9WcNOi+28p4LKeLMU8DAxDxwy\r\nSTFYeMvOn7vH/meg9Bm8hKvzSn5wBXSHysM=\r\n=Jyp2\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_3.0.0-alpha_1672919615410_0.6113583523705892"},"_hasShrinkwrap":false},"3.0.0-alpha2":{"name":"clickhouse-orm","version":"3.0.0-alpha2","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","build":"rm -rf ./dist & npm run tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","ts-full":"ts-node ./examples/full-datatype.ts","ts-sync":"ts-node ./examples/sync-table.ts","test":"jest --coverage"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/index.js","types":"dist/index.d.ts","readme":"<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://img.shields.io/npm/v/clickhouse-orm.svg\"></a>\n<a href=\"https://npms.io/search?q=clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://badges.npms.io/clickhouse-orm.svg\"></a>\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM total downloads\"><img src=\"https://img.shields.io/npm/dt/clickhouse-orm.svg\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github stars\"><img src=\"https://img.shields.io/github/stars/zimv/node-clickhouse-orm.svg?style=social&label=Star\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github forks\"><img src=\"https://img.shields.io/github/forks/zimv/node-clickhouse-orm.svg?style=social&label=Fork\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github contributors\"><img src=\"https://img.shields.io/github/contributors/zimv/node-clickhouse-orm.svg\"></a>\n\n# clickhouse-orm\n\n[![Join the chat at https://gitter.im/zimv/node-clickhouse-orm](https://badges.gitter.im/zimv/node-clickhouse-orm.svg)](https://gitter.im/zimv/node-clickhouse-orm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n\nClickhouse ORM for Nodejs. Send query over HTTP interface. Using [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n# Install:\n\n```\nnpm i clickhouse-orm\n```\n\n# Usage\n\n**Create instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_test\",\n  },\n  debug: true,\n  client: {\n    url: \"localhost\",\n    port: \"8123\",\n    basicAuth: {\n      username: \"default\",\n      password: \"\",\n    },\n    debug: false,\n    isUseGzip: true,\n    format: \"json\", // \"json\" || \"csv\" || \"tsv\"\n  },\n});\n```\n\n**Define Schema：**\n\n```javascript\nconst table1Schema = {\n  // table name\n  tableName: \"table1\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n```\n\n**create / build + save / find：**\n\n```javascript\nconst doDemo = async () => {\n  // create database 'orm_test'\n  // SQL: CREATE DATABASE IF NOT EXISTS orm_test\n  await chOrm.createDatabase();\n\n  // register schema and create [if] table\n  // createTable() SQL: CREATE TABLE IF NOT EXISTS orm_test.table1...\n  const Table1Model = await chOrm.model(table1Schema);\n\n  // new data model\n  const data = Table1Model.build({ status: 2 });\n\n  // set value\n  data.time = new Date();\n  data.browser = \"chrome\";\n  data.browser_v = \"90.0.1.21\";\n\n  // do save\n  const res = await data.save();\n  // SQL: INSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":2,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\n  console.log(\"save:\", res);\n\n  // create === build + save\n  const resCreate = await Table1Model.create({\n    status: 1,\n    time: new Date(),\n    browser: \"chrome\",\n    browser_v: \"90.0.1.21\",\n  });\n  console.log(\"create:\", resCreate);\n\n  // do find\n  Table1Model.find({\n    select: \"*\",\n    limit: 3,\n  }).then((res) => {\n    // SQL: SELECT * from orm_test.table1    LIMIT 3\n    console.log(\"find:\", res);\n  });\n};\n\ndoDemo();\n```\n\nMore in [Basic Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/basic.js).\n\n# Overview\n\n`Note`: '?' is a Optional\n\n### ClickhouseOrm\n\n`db` : object<{name:string, engine?:string, cluster?:string}>\n\n> name: database name\n\n> engine?: database engine\n\n> cluster?: cluster name\n\n`debug` : boolean\n\n> Default: false\n\n`client` : object\n\n> Drive configuration. More in [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n### Schema\n\n`tableName` : string\n\n> It is the table name.\n\n`schema` : { [column]: { type?, default? } }\n\n> The `type` will be verified, The `default` is the default value for column.\n\n`createTable` : string\n\n> It is the SQL for creating tables.When model is executed, this SQL will be executed. It is suggested to add 'IF NOT EXISTS'.\n\nWatch out !!! >>>>> If the table already exists and you want to modify it. You need to execute the modification sql through other clients（Such as Remote terminal） and update the code of the Schema!!!\n\n```javascript\nconst table1Schema = {\n  // table name\n  tableName: \"table1\",\n  // define column\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n\n// register schema and create [if] table\nconst Table1Model = await chOrm.model(table1Schema);\n```\n\n### DATA_TYPE\n\nThe clickhouse data types. Some types are defined here.\n\nColumns with defined types will be verified. It only checks the basic type of data, not the most standard value. They are `number | string | boolean | date`.\n\n```javascript\nexport enum DATA_TYPE {\n  UInt8 = 'number',\n  UInt16 = 'number',\n  UInt32 = 'number',\n  UInt64 = 'number',\n  UInt128 = 'number',\n  UInt256 = 'number',\n  Int8 = 'number',\n  Int16 = 'number',\n  Int32 = 'number',\n  Int64 = 'number',\n  Int128 = 'number',\n  Int256 = 'number',\n  Float32 = 'number',\n  Float64 = 'number',\n  Boolean = 'boolean',\n  String = 'string',\n  UUID = 'string',\n  Date = 'date|string|number',\n  Date32 = 'date|string|number',\n  DateTime = 'date|string|number',\n  DateTime64 = 'date|string|number',\n}\n```\n\n```javascript\nschema: {\n  time: { type: DATA_TYPE.DateTime, default: Date },\n  [column]: { type?, default? }\n}\n```\n\n### Log\n\nThe **setLogService** is a global configuration method and will affect all instances.\n\n`Default: console.log`\n\nCustom example: **[winston](https://github.com/winstonjs/winston)**\n\n```javascript\nconst { setLogService } = require(\"clickhouse-orm\");\nconst winston = require(\"winston\");\nconst logger = winston.createLogger();\n\nsetLogService(logger.info);\n```\n\n### Use SQL directly：\n\n```javascript\nchOrm.client\n  .query(`select * from orm_test.table1 limit 3`)\n  .toPromise()\n  .then((res) => {\n    console.log(\"Use sql:\", res);\n  });\n```\n\nThe `chOrm.client` is the [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse) instance.\n\n# [More Examples](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/more.ts)\n\n### Find\n\n```javascript\nimport * as dayjs from \"dayjs\";\n\nqueryExample1({\n  Model: Table1Model,\n  status: 1,\n  beginTime: dayjs().subtract(1, \"day\").format(\"YYYY-MM-DD HH:mm:ss\"),\n  endTime: dayjs().format(\"YYYY-MM-DD HH:mm:ss\"),\n}).then((res) => {\n  console.log(\"queryExample1:\", res);\n});\n\nconst queryExample1 = ({ Model, status, beginTime, endTime }) => {\n  let wheres = [],\n    where;\n  if (status) wheres.push(`status='${status}'`);\n  if (beginTime) wheres.push(`time>='${beginTime}'`);\n  if (endTime) wheres.push(`time<='${endTime}'`);\n  if (wheres.length > 0) where = wheres.join(\" and \");\n\n  return Model.find({\n    where,\n    select: `*`,\n    orderBy: \"time ASC\",\n    limit: 5,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT * from orm_test.table1 where status='1' and time>='2022-02-04 15:34:22' and time<='2022-02-05 15:34:22'  ORDER BY time ASC LIMIT 5\n```\n\n### Count\n\n```javascript\ncountExample1({\n  Model: Table1Model,\n}).then((res) => {\n  console.log(\"countExample1:\", res);\n});\n\nconst countExample1 = ({ Model }) => {\n  return Model.find({\n    select: `count(*) AS total`,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count(*) AS total from orm_test.table1\n```\n\n### GroupBy\n\n```javascript\nTable1Model.find({\n  select: `status,browser`,\n  groupBy: \"status,browser\",\n});\n```\n\nFinal executed SQL:\n\n```sql\nSELECT status,browser from orm_test.table1  GROUP BY status,browser\n```\n\n### Nested Queries\n\n```javascript\nTable1Model.find([\n  {\n    select: `browser`,\n    groupBy: \"browser\",\n  },\n  {\n    select: `count() as browserTotal`,\n  },\n]);\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count() as browserTotal from (SELECT browser from orm_test.table1  GROUP BY browser  )\n```\n\n### save\n\n```javascript\n// new data model\nconst data = Table1Model.build();\n\n// set value\ndata.time = new _Date_();\ndata.status = 1;\ndata.browser = \"chrome\";\ndata.browser_v = \"90.0.1.21\";\n\n// do save\ndata.save().then((res) => {\n  console.log(\"save:\", res);\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### create\n\n```javascript\n//do create\nawait Table1Model.create({\n  status: 1,\n  time: new Date(),\n  browser: \"chrome\",\n  browser_v: \"90.0.1.21\",\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### InsertMany\n\n```javascript\nconst list = [\n  { status: 2, browser: \"IE\", browser_v: \"10.0.1.21\" },\n  { status: 2, browser: \"FF\", browser_v: \"2.0.3\" },\n  { status: 3, browser: \"IE\", browser_v: \"1.1.1\" },\n];\n\nTable1Model.insertMany(list);\n// or\nTable1Model.insertMany(\n  list.map((item) => {\n    const data = Table1Model.build();\n    // set value\n    data.time = new Date();\n    data.status = item.status;\n    data.browser = item.browser;\n    data.browser_v = item.browser_v;\n    return data;\n  })\n);\n```\n\nFinal executed SQL:\n\n```sql\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"IE\",\"browser_v\":\"10.0.1.21\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"FF\",\"browser_v\":\"2.0.3\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":3,\"browser\":\"IE\",\"browser_v\":\"1.1.1\"}]\n```\n\n### delete\n\n```javascript\n\nTable1Model.delete({\n  where: `browser='Chrome'`,\n})\n```\n\nFinal executed SQL:\n\n```sql\nALTER TABLE orm_test.table1  DELETE  WHERE browser='Chrome'\n```\n\n## cluster\n\n**Create a cluster instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_cluster_test\",\n    cluster: \"default_cluster\",\n  },\n  // ...other\n});\nconst table2Schema = {\n  // table name\n  tableName: \"table2\",\n  // create table sql\n  createTable: (dbTableName, db) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table2)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName} ON CLUSTER ${db.cluster}\n      ...other`;\n  },\n  ...other,\n};\n\n// create database 'orm_cluster_test'\n// SQL: CREATE DATABASE IF NOT EXISTS orm_cluster_test ON CLUSTER default_cluster\nawait chOrm.createDatabase();\n\n// register schema and create [if] table\n// createTable() SQL: CREATE TABLE IF NOT EXISTS orm_cluster_test.table2 ON CLUSTER default_cluster...\nconst Table2Model = await chOrm.model(table2Schema);\n```\n\n# Wechat Discussion\n\n[Click to join](https://github.com/zimv/node-clickhouse-orm/issues/3)\n","readmeFilename":"README.md","gitHead":"135fb0fe9193fac7776804fe465a27b795098bae","_id":"clickhouse-orm@3.0.0-alpha2","_nodeVersion":"14.18.3","_npmVersion":"9.2.0","dist":{"integrity":"sha512-iG5cGwuxMhes77TDnVWUZlmPLHLA6WccdRBUDF/N5tGSJhXUHWaMHtHGBKrFki/klJFHFrvGXC4wLpCBGlWg1Q==","shasum":"c24a6cdd362e4b1e7e8251e5f6c9bb1f1cc835af","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-3.0.0-alpha2.tgz","fileCount":26,"unpackedSize":65759,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCWnREV4DwFpKrUKrPFJtxQ7bsk192xJGHI4VRqPiE/AgIhAOOqaIeE4zHYpqd8mhKtnznnI4vDZGFm6OI1xwGEpXB8"}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjtrydACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmq6jBAAh+PwDi4sxy2tmv5mVDVCyqeVgEcJ77qEHqlql/h2KnYnYh3r\r\nSKe2dO4VQt13M6784wauDOinK7LiYxrGEk2oRZSmOXSusi9Di9UifVw4xQ41\r\nTqiOTU+4XYplVnI/vi8jEBqiHryKpEKH2JJDm8zHabCvWoUyxCwLcqie96p2\r\n4JAP50ngA6C8VpQbsaEP5moEwEFQ/0e6ehRpO4Qg/gXkJMmVYUqu/hYUDd9o\r\npa5naRIs9onsIGnIotUbBHiBkGqFwBNney+9bzKoNEm/AQVT/B99/OyQ4K66\r\nUYTUfAxQqi9kyB6sjq3oPctdCM2myz/mHNTnYU6LpoOE4SDrTYoYOYRyceEb\r\nVhod4BzGWqsm59YKVRw0C5no0/Q1/FT5G2l9uDaBvwvPAnkcIY9e4c89/U1W\r\ne68MBreUHd53oxoRlZ5zN3xGUWP/E8ZL32w7o2h6I6J1bMmhEbVZwQt1YbGs\r\nY7MeIvrRpQ5PcXBVPIc64S9loNjjK2cEAgFBF1xHoJTBy7ttnXT7UEVLkOQD\r\nFM7dYH3CiuK82mNNK+wPb8Cw6pxAew2gr5UNzc15MLBNMhz1IsCcRhzrTB8R\r\nJatvsPA8ZymsLPSYpIFYxbTcLgR/etjlAHW0tt8zjKGVOm9/mVvuLHWkPwXt\r\nmYhB+Yv5+i8ZXIwTuq0pq8vM7BK2nRvy2/g=\r\n=RXzl\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_3.0.0-alpha2_1672920221687_0.36186148299513854"},"_hasShrinkwrap":false},"3.0.0-alpha3":{"name":"clickhouse-orm","version":"3.0.0-alpha3","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","build":"rm -rf ./dist & npm run tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","ts-datatype":"ts-node ./examples/datatype.ts","ts-sync":"ts-node ./examples/syncTable.ts","test":"jest --coverage"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/index.js","types":"dist/index.d.ts","readme":"<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/05ad3e5cb52b4c149b47362377505916~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://npms.io/search?q=clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/bb03631752ce4ccf89445f94a4a02d97~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM total downloads\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4cb1a7ae1bf14cda804c0b3db0d50252~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github stars\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a5df26c796d14e53a63f4f08afcd630f~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github forks\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/57da9f95623043dbb052d873ebeac981~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github contributors\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ab0ae120764e474db09c743634b102f9~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n\n# clickhouse-orm\n\n[![Join the chat at https://gitter.im/zimv/node-clickhouse-orm](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/8230cfb055bc4f1699e1749b6a7a3421~tplv-k3u1fbpfcp-zoom-1.image)](https://gitter.im/zimv/node-clickhouse-orm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n\nClickhouse ORM for Nodejs. Send query over HTTP interface. Using [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n# Install:\n\n```\nnpm i clickhouse-orm\n```\n\n# Usage\n\n**Create instance：**\n\n```typescript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_test\",\n  },\n  debug: true,\n  client: {\n    url: \"localhost\",\n    port: \"8123\",\n    basicAuth: {\n      username: \"default\",\n      password: \"\",\n    },\n    debug: false,\n    isUseGzip: true,\n    format: \"json\", // \"json\" || \"csv\" || \"tsv\"\n  },\n});\n```\n\n**Define Model：**\n* ModelConfig\n\n```typescript\n\nimport { DATA_TYPE, ModelSqlCreateTableConfig } from 'clickhouse-orm';\nconst xxxSchema: ModelSqlCreateTableConfig = {\n  // table name\n  tableName: \"xxx\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n};\n```\n\n* ModelSyncTableConfig\n\nAuto create table and sync table\n\n```typescript\n\nimport { DATA_TYPE, ModelSyncTableConfig } from 'clickhouse-orm';\nconst oldSchema: ModelSyncTableConfig = {\n  tableName: \"xxx\",\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    will_typeChanged: { type: DATA_TYPE.Int16 },\n    will_deleted: { type: DATA_TYPE.String },\n  },\n  options: `ENGINE = MergeTree\n  PARTITION BY toYYYYMM(time)\n  ORDER BY time`,\n  autoCreate: true,\n  autoSync: true,\n};\n```\nSync table structure(just schema column) when Model create\n```typescript\nconst newSchema = {\n  ...oldSchema,\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    will_typeChanged: { type: DATA_TYPE.Int32 },\n    add_column: { type: DATA_TYPE.String },\n  }\n}\nchOrm.model(newSchema)\n```\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  DROP COLUMN will_deleted \n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  ADD COLUMN add_column String \n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  MODIFY COLUMN will_typeChanged Int32\n\n**More in [SyncTable Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/syncTable.ts).**\n* ModelSqlCreateTableConfig\n\ncustom create table sql, auto create table\n\n```typescript\n\nimport { DATA_TYPE, ModelSqlCreateTableConfig } from 'clickhouse-orm';\nconst xxxSchema: ModelSqlCreateTableConfig = {\n  // table name\n  tableName: \"xxx\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n```\n**create / build + save / find：**\n\n```javascript\nconst doDemo = async () => {\n  // create database 'orm_test'\n  // SQL: CREATE DATABASE IF NOT EXISTS orm_test\n  await chOrm.createDatabase();\n\n  // register schema and create [if] table\n  // createTable() SQL: CREATE TABLE IF NOT EXISTS orm_test.table1...\n  const Table1Model = await chOrm.model(table1Schema);\n\n  // new data model\n  const data = Table1Model.build({ status: 2 });\n\n  // set value\n  data.time = new Date();\n  data.browser = \"chrome\";\n  data.browser_v = \"90.0.1.21\";\n\n  // do save\n  const res = await data.save();\n  // SQL: INSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":2,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\n  console.log(\"save:\", res);\n\n  // create === build + save\n  const resCreate = await Table1Model.create({\n    status: 1,\n    time: new Date(),\n    browser: \"chrome\",\n    browser_v: \"90.0.1.21\",\n  });\n  console.log(\"create:\", resCreate);\n\n  // do find\n  Table1Model.find({\n    select: \"*\",\n    limit: 3,\n  }).then((res) => {\n    // SQL: SELECT * from orm_test.table1    LIMIT 3\n    console.log(\"find:\", res);\n  });\n};\n\ndoDemo();\n```\n\n**More in [Basic Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/basic.js).**\n\n# Overview\n\n`Note`: '?' is a Optional\n\n### ClickhouseOrm\n\n\n\n`db` : object<{name:string, engine?:string, cluster?:string}>\n\n> name: database name\n\n> engine?: database engine\n\n> cluster?: cluster name\n\n`debug` : boolean\n\n> Default: false\n\n`client` : object\n\n> Drive configuration. More in [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n### ModelConfig\n* ModelConfig\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type?, default? } } | The `type` will be verified, The `default` is the default value for column.|\n\n\n* ModelSyncTableConfig\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type?, default? } } | The `type` will be verified, The `default` is the default value for column.|\n| options | true | string | Create table setting |\n| autoCreate | true | boolean | Auto create table |\n| autoSync | false | boolean | Auto sync table structure |\n\n* ModelSqlCreateTableConfig\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type?, default? } } | The `type` will be verified, The `default` is the default value for column.|\n| createTable | true | string | It is the SQL for creating tables.When model is executed, this SQL will be executed. It is suggested to add 'IF NOT EXISTS'. <br> Watch out !!! >>>>> If the table already exists and you want to modify it. You need to execute the modification sql through other clients（Such as Remote terminal） and update the code of the Schema!!!|\n\n\n\n### DATA_TYPE\n\nThe clickhouse data types. Some types are defined here.\n\nSome defined data types will be verified. It only checks the basic type of data and not the most standard value. They are `number | string | boolean | date`.\n\n```typescript\n  UInt8;\n  UInt16;\n  UInt32;\n  UInt64;\n  UInt128;\n  UInt256;\n  Int8;\n  Int16;\n  Int32;\n  Int64;\n  Int128;\n  Int256;\n  Float32;\n  Float64;\n  Boolean;\n  String;\n  UUID;\n  Date;\n  Date32;\n  DateTime;\n  DateTime64;\n  /**\n   *\n   * @param Number\n   * @example DATA_TYPE.FixedString(3)\n   */\n  FixedString;\n  /**\n   *\n   * @param DATA_TYPE\n   * @example DATA_TYPE.LowCardinality(DATA_TYPE.String)\n   */\n  LowCardinality;\n  /**\n   *\n   * @param string\n   * @example DATA_TYPE.Enum8(`'hello' = 1, 'world' = 2`)\n   * @desc number [-128, 127]\n   */\n  Enum8:;\n  /**\n   *\n   * @param string\n   * @example DATA_TYPE.Enum16(`'hello' = 3000, 'world' = 3500`)\n   * @desc number [-32768, 32767]\n   */\n  Enum16;\n  /**\n   *\n   * @param columnType\n   * Clickhouse dataTypes: Array(T), JSON, Map(key, value), IPv4, Nullable(), more...\n   * @example DATA_TYPE.Other('Array(String)') , DATA_TYPE.Other('Int8')\n   * @desc No `INSERT` data validation provided\n   */\n  Other;\n```\n**More in [Datatype Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/datatype.ts).**\n### Log\n\nThe **setLogService** is a global configuration method and will affect all instances.\n\n`Default: console.log`\n\nCustom example: **[winston](https://github.com/winstonjs/winston)**\n\n```javascript\nconst { setLogService } = require(\"clickhouse-orm\");\nconst winston = require(\"winston\");\nconst logger = winston.createLogger();\n\nsetLogService(logger.info);\n```\n\n### Use SQL directly：\n\n```javascript\nchOrm.client\n  .query(`select * from orm_test.table1 limit 3`)\n  .toPromise()\n  .then((res) => {\n    console.log(\"Use sql:\", res);\n  });\n```\n\nThe `chOrm.client` is the [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse) instance.\n\n# [More Examples](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/more.ts)\n\n### Find\n\n```javascript\nimport * as dayjs from \"dayjs\";\n\nqueryExample1({\n  Model: Table1Model,\n  status: 1,\n  beginTime: dayjs().subtract(1, \"day\").format(\"YYYY-MM-DD HH:mm:ss\"),\n  endTime: dayjs().format(\"YYYY-MM-DD HH:mm:ss\"),\n}).then((res) => {\n  console.log(\"queryExample1:\", res);\n});\n\nconst queryExample1 = ({ Model, status, beginTime, endTime }) => {\n  let wheres = [],\n    where;\n  if (status) wheres.push(`status='${status}'`);\n  if (beginTime) wheres.push(`time>='${beginTime}'`);\n  if (endTime) wheres.push(`time<='${endTime}'`);\n  if (wheres.length > 0) where = wheres.join(\" and \");\n\n  return Model.find({\n    where,\n    select: `*`,\n    orderBy: \"time ASC\",\n    limit: 5,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT * from orm_test.table1 where status='1' and time>='2022-02-04 15:34:22' and time<='2022-02-05 15:34:22'  ORDER BY time ASC LIMIT 5\n```\n\n### Count\n\n```javascript\ncountExample1({\n  Model: Table1Model,\n}).then((res) => {\n  console.log(\"countExample1:\", res);\n});\n\nconst countExample1 = ({ Model }) => {\n  return Model.find({\n    select: `count(*) AS total`,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count(*) AS total from orm_test.table1\n```\n\n### GroupBy\n\n```javascript\nTable1Model.find({\n  select: `status,browser`,\n  groupBy: \"status,browser\",\n});\n```\n\nFinal executed SQL:\n\n```sql\nSELECT status,browser from orm_test.table1  GROUP BY status,browser\n```\n\n### Nested Queries\n\n```javascript\nTable1Model.find([\n  {\n    select: `browser`,\n    groupBy: \"browser\",\n  },\n  {\n    select: `count() as browserTotal`,\n  },\n]);\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count() as browserTotal from (SELECT browser from orm_test.table1  GROUP BY browser  )\n```\n\n### save\n\n```javascript\n// new data model\nconst data = Table1Model.build();\n\n// set value\ndata.time = new _Date_();\ndata.status = 1;\ndata.browser = \"chrome\";\ndata.browser_v = \"90.0.1.21\";\n\n// do save\ndata.save().then((res) => {\n  console.log(\"save:\", res);\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### create\n\n```javascript\n//do create\nawait Table1Model.create({\n  status: 1,\n  time: new Date(),\n  browser: \"chrome\",\n  browser_v: \"90.0.1.21\",\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### InsertMany\n\n```javascript\nconst list = [\n  { status: 2, browser: \"IE\", browser_v: \"10.0.1.21\" },\n  { status: 2, browser: \"FF\", browser_v: \"2.0.3\" },\n  { status: 3, browser: \"IE\", browser_v: \"1.1.1\" },\n];\n\nTable1Model.insertMany(list);\n// or\nTable1Model.insertMany(\n  list.map((item) => {\n    const data = Table1Model.build();\n    // set value\n    data.time = new Date();\n    data.status = item.status;\n    data.browser = item.browser;\n    data.browser_v = item.browser_v;\n    return data;\n  })\n);\n```\n\nFinal executed SQL:\n\n```sql\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"IE\",\"browser_v\":\"10.0.1.21\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"FF\",\"browser_v\":\"2.0.3\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":3,\"browser\":\"IE\",\"browser_v\":\"1.1.1\"}]\n```\n\n### delete\n\n```javascript\n\nTable1Model.delete({\n  where: `browser='Chrome'`,\n})\n```\n\nFinal executed SQL:\n\n```sql\nALTER TABLE orm_test.table1  DELETE  WHERE browser='Chrome'\n```\n\n## cluster\n\n**Create a cluster instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_cluster_test\",\n    cluster: \"default_cluster\",\n  },\n  // ...other\n});\nconst table2Schema = {\n  // table name\n  tableName: \"table2\",\n  ...other,\n};\n\n// create database 'orm_cluster_test'\n// SQL: CREATE DATABASE IF NOT EXISTS orm_cluster_test ON CLUSTER default_cluster\nawait chOrm.createDatabase();\n\n// register schema and create [if] table\n// createTable() SQL: CREATE TABLE IF NOT EXISTS orm_cluster_test.table2 ON CLUSTER default_cluster...\nconst Table2Model = await chOrm.model(table2Schema);\n```\n\n# Wechat Discussion\n\n[Click to join](https://github.com/zimv/node-clickhouse-orm/issues/3)\n","readmeFilename":"README.md","gitHead":"96bd3945d97cf74aa2ae121a8d77b74535e64212","_id":"clickhouse-orm@3.0.0-alpha3","_nodeVersion":"16.15.1","_npmVersion":"9.2.0","dist":{"integrity":"sha512-fKCi/XOp8HrChEHV9Knjt5p1mOUkcV/MyMYr6U/B8RD4eyAdbtQiiSpqWaKPiETLK3yHKVnEcsqmvJRA+0dNpA==","shasum":"11147b8224fedf52ecf7f961ab13de38a2cdd3dc","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-3.0.0-alpha3.tgz","fileCount":26,"unpackedSize":70178,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDrJTp5ei3BdHC4mjLYyKDP1LxpqOc/qPwJChWhVbcKnAiB7MaVtoCYruF9GdaHg83FGY6FAtFtxcch+VCVRp2HDjw=="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjt8WqACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmoF7RAAk3KGM9g/dn0Zmxtsh60FIZfe2DeeLdu7qACvrG6PTDj3H+VC\r\nqsYxgfG20TG+t1h+gapbObj+vXDceZ/rHm9awsdZGC/A8gJi/CVyfdEkVXbd\r\n2JhEVbFm2DRdUodLUsmH019LiW9HKDp4gQ7pwr8ioXx7IuCRGsjfQ1qu1ask\r\nh1uoXxDToQ3oGIwUA7YM9gW0E7Ouiw2ZF3vVY2lEDKD2jcGJ1KBI8s5ljCRk\r\nryiGBlo+IedkbsWSi8/9B5+Ea3MLw8c/NmGUzqizqAkZug3eyENr1Ksn/PZ0\r\nyQNrHMVUBBp5Nd6WqLD0mdzES42ccYci9CCYaEw4A2zdK8qHGysCq6ymYzcL\r\nVG2EDhKo3Y/e1k+x1UCB4mOMbGShPOsotT0SV54kBSuM7GrYpr3ChsLgSwKN\r\nnN/i+xLEF+JRzaRQlvKmKbtfvizTtTYCN0vKqxYIBHyIwfU+8KgoOZ5MjhtQ\r\nUsJy5/RnOTlFAJCwx9VuB4LjquUtFAAEjvuFFEBax2rgLwJkYM2ARK9aZ2yI\r\nPHwQ4Q5Gm98SmqZoy5WK1J66lo0G9bGMI1D7qrJW62fJJe5Kcgw6kmtb3QNP\r\n11222vKSUsxt/I2/Wt2WEaOYUiMVTetKspyNrxrQ4h2WnTOytkuTu8DN7f9b\r\nr9BtoeZTGUiF/lRPrFR1GKeETl0nRQTDDKs=\r\n=DZ4u\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_3.0.0-alpha3_1672988074332_0.1079750206471013"},"_hasShrinkwrap":false},"3.0.0-alpha4":{"name":"clickhouse-orm","version":"3.0.0-alpha4","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","build":"rm -rf ./dist & npm run tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","ts-datatype":"ts-node ./examples/datatype.ts","ts-sync":"ts-node ./examples/syncTable.ts","test":"jest --coverage"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/index.js","types":"dist/index.d.ts","readme":"<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/05ad3e5cb52b4c149b47362377505916~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://npms.io/search?q=clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/bb03631752ce4ccf89445f94a4a02d97~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM total downloads\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4cb1a7ae1bf14cda804c0b3db0d50252~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github stars\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a5df26c796d14e53a63f4f08afcd630f~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github forks\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/57da9f95623043dbb052d873ebeac981~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github contributors\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ab0ae120764e474db09c743634b102f9~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n\n# clickhouse-orm  [(中文 README)](https://github.com/zimv/node-clickhouse-orm/blob/main/README-zh.md)\n\n[![Join the chat at https://gitter.im/zimv/node-clickhouse-orm](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/8230cfb055bc4f1699e1749b6a7a3421~tplv-k3u1fbpfcp-zoom-1.image)](https://gitter.im/zimv/node-clickhouse-orm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n\nClickhouse ORM for Nodejs. Send query over HTTP interface. Using [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n# Install:\n\n```\nnpm i clickhouse-orm\n```\n\n# Usage\n\n**Create instance：**\n\n```typescript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_test\",\n  },\n  debug: true,\n  client: {\n    url: \"localhost\",\n    port: \"8123\",\n    basicAuth: {\n      username: \"default\",\n      password: \"\",\n    },\n    debug: false,\n    isUseGzip: true,\n    format: \"json\", // \"json\" || \"csv\" || \"tsv\"\n  },\n});\n```\n\n**Define Model：**\n* ModelConfig\n\n```typescript\nimport { DATA_TYPE, ModelSqlCreateTableConfig } from 'clickhouse-orm';\nconst xxxSchema: ModelSqlCreateTableConfig = {\n  // table name\n  tableName: \"xxx\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n};\n```\n----\n* ModelSyncTableConfig\n\nAutomatically create tables and automatically synchronize table field structures\n\n```typescript\nimport { DATA_TYPE, ModelSyncTableConfig } from 'clickhouse-orm';\nconst oldSchema: ModelSyncTableConfig = {\n  tableName: \"xxx\",\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    will_typeChanged: { type: DATA_TYPE.Int16 },\n    will_deleted: { type: DATA_TYPE.String },\n  },\n  options: `ENGINE = MergeTree\n  PARTITION BY toYYYYMM(time)\n  ORDER BY time`,\n  autoCreate: true,\n  autoSync: true,\n};\n```\nSynchronize the table structure (just the field columns) when creating the model. When the model is created, the field structure of the remote database table will be pulled for comparison with the schema in the current code. Finally, the ORM will automatically execute (add, delete, and modify) statements.\n\n\n```typescript\nconst newSchema = {\n  ...oldSchema,\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    will_typeChanged: { type: DATA_TYPE.Int32 },\n    add_column: { type: DATA_TYPE.String },\n  }\n}\nchOrm.model(newSchema)\n```\n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  DROP COLUMN will_deleted \n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  ADD COLUMN add_column String \n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  MODIFY COLUMN will_typeChanged Int32\n\nUnrecognized field name modification! The following configuration will delete **column1** and add **column2**.\n\n```typescript\noldSchema = {\n  column1: { type: DATA_TYPE.String },\n}\nnewSchema = {\n  column2: { type: DATA_TYPE.String },\n}\n```\n\n**More in [SyncTable Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/syncTable.ts).**\n\n----\n* ModelSqlCreateTableConfig\n\nCustomized table creation statement, and the table will be created automatically when the model is created\n\n```typescript\n\nimport { DATA_TYPE, ModelSqlCreateTableConfig } from 'clickhouse-orm';\nconst xxxSchema: ModelSqlCreateTableConfig = {\n  // table name\n  tableName: \"xxx\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: {},\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n```\n**create / build + save / find：**\n\n```javascript\nconst doDemo = async () => {\n  // create database 'orm_test'\n  // SQL: CREATE DATABASE IF NOT EXISTS orm_test\n  await chOrm.createDatabase();\n\n  // register schema and create [if] table\n  // createTable() SQL: CREATE TABLE IF NOT EXISTS orm_test.table1...\n  const Table1Model = await chOrm.model(table1Schema);\n\n  // new data model\n  const data = Table1Model.build({ status: 2 });\n\n  // set value\n  data.time = new Date();\n  data.browser = \"chrome\";\n  data.browser_v = \"90.0.1.21\";\n\n  // do save\n  const res = await data.save();\n  // SQL: INSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":2,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\n  console.log(\"save:\", res);\n\n  // create === build + save\n  const resCreate = await Table1Model.create({\n    status: 1,\n    time: new Date(),\n    browser: \"chrome\",\n    browser_v: \"90.0.1.21\",\n  });\n  console.log(\"create:\", resCreate);\n\n  // do find\n  Table1Model.find({\n    select: \"*\",\n    limit: 3,\n  }).then((res) => {\n    // SQL: SELECT * from orm_test.table1    LIMIT 3\n    console.log(\"find:\", res);\n  });\n};\n\ndoDemo();\n```\n\n**More in [Basic Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/basic.js).**\n\n# Overview\n\n`Note`: '?' is a Optional\n\n### ClickhouseOrm\n\n\n\n`db` : object<{name:string, engine?:string, cluster?:string}>\n\n> name: database name\n\n> engine?: database engine\n\n> cluster?: cluster name\n\n`debug` : boolean\n\n> Default: false\n\n`client` : object\n\n> Drive configuration. More in [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n### ModelConfig\n* ModelConfig\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type?, default? } } | `Type` defines the data type, and `default` sets the default value |\n\n----\n* ModelSyncTableConfig\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type?, default? } } | `Type` defines the data type, and `default` sets the default value |\n| options | true | string | Create table setting |\n| autoCreate | true | boolean | Auto create table |\n| autoSync | false | boolean | Auto sync table structure`(Careful use)` |\n\n----\n* ModelSqlCreateTableConfig\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type?, default? } } | `Type` defines the data type, and `default` sets the default value |\n| createTable | true | string | It is the SQL for creating tables.When model is executed, this SQL will be executed. It is suggested to add 'IF NOT EXISTS'. <br> Watch out !!! >>>>> If the table already exists and you want to modify it. You need to execute the modification sql through other clients（Such as Remote terminal） and update the code of the Schema!!!|\n\n\n\n### DATA_TYPE\n\nClickhouse data type. Most of the following data will be validated by ORM, but only the basic data type `number | string | boolean | date` will be validated, not the most standard data type. For example, in `Int8`, ORM only verifies the `number` type.\n\n\n```typescript\n  UInt8;\n  UInt16;\n  UInt32;\n  UInt64;\n  UInt128;\n  UInt256;\n  Int8;\n  Int16;\n  Int32;\n  Int64;\n  Int128;\n  Int256;\n  Float32;\n  Float64;\n  Boolean;\n  String;\n  UUID;\n  Date;\n  Date32;\n  DateTime;\n  DateTime64;\n  /**\n   *\n   * @param Number\n   * @example DATA_TYPE.FixedString(3)\n   */\n  FixedString;\n  /**\n   *\n   * @param DATA_TYPE\n   * @example DATA_TYPE.LowCardinality(DATA_TYPE.String)\n   */\n  LowCardinality;\n  /**\n   *\n   * @param string\n   * @example DATA_TYPE.Enum8(`'hello' = 1, 'world' = 2`)\n   * @desc number [-128, 127]\n   */\n  Enum8:;\n  /**\n   *\n   * @param string\n   * @example DATA_TYPE.Enum16(`'hello' = 3000, 'world' = 3500`)\n   * @desc number [-32768, 32767]\n   */\n  Enum16;\n  /**\n   *\n   * @param columnType\n   * Clickhouse dataTypes: Array(T), JSON, Map(key, value), IPv4, Nullable(), more...\n   * @example DATA_TYPE.Other('Array(String)') , DATA_TYPE.Other('Int8')\n   * @desc No `INSERT` data validation provided\n   */\n  Other;\n```\n**More in [Datatype Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/datatype.ts).**\n### Log\n\nThe **setLogService** is a global configuration method and will affect all instances.\n\n`Default: console.log`\n\nCustom example: **[winston](https://github.com/winstonjs/winston)**\n\n```javascript\nconst { setLogService } = require(\"clickhouse-orm\");\nconst winston = require(\"winston\");\nconst logger = winston.createLogger();\n\nsetLogService(logger.info);\n```\n\n### Use SQL directly：\n\n```javascript\nchOrm.client\n  .query(`select * from orm_test.table1 limit 3`)\n  .toPromise()\n  .then((res) => {\n    console.log(\"Use sql:\", res);\n  });\n```\n\nThe `chOrm.client` is the [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse) instance.\n\n# [More Examples](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/more.ts)\n\n### Find\n\n```javascript\nimport * as dayjs from \"dayjs\";\n\nqueryExample1({\n  Model: Table1Model,\n  status: 1,\n  beginTime: dayjs().subtract(1, \"day\").format(\"YYYY-MM-DD HH:mm:ss\"),\n  endTime: dayjs().format(\"YYYY-MM-DD HH:mm:ss\"),\n}).then((res) => {\n  console.log(\"queryExample1:\", res);\n});\n\nconst queryExample1 = ({ Model, status, beginTime, endTime }) => {\n  let wheres = [],\n    where;\n  if (status) wheres.push(`status='${status}'`);\n  if (beginTime) wheres.push(`time>='${beginTime}'`);\n  if (endTime) wheres.push(`time<='${endTime}'`);\n  if (wheres.length > 0) where = wheres.join(\" and \");\n\n  return Model.find({\n    where,\n    select: `*`,\n    orderBy: \"time ASC\",\n    limit: 5,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT * from orm_test.table1 where status='1' and time>='2022-02-04 15:34:22' and time<='2022-02-05 15:34:22'  ORDER BY time ASC LIMIT 5\n```\n\n### Count\n\n```javascript\ncountExample1({\n  Model: Table1Model,\n}).then((res) => {\n  console.log(\"countExample1:\", res);\n});\n\nconst countExample1 = ({ Model }) => {\n  return Model.find({\n    select: `count(*) AS total`,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count(*) AS total from orm_test.table1\n```\n\n### GroupBy\n\n```javascript\nTable1Model.find({\n  select: `status,browser`,\n  groupBy: \"status,browser\",\n});\n```\n\nFinal executed SQL:\n\n```sql\nSELECT status,browser from orm_test.table1  GROUP BY status,browser\n```\n\n### Nested Queries\n\n```javascript\nTable1Model.find([\n  {\n    select: `browser`,\n    groupBy: \"browser\",\n  },\n  {\n    select: `count() as browserTotal`,\n  },\n]);\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count() as browserTotal from (SELECT browser from orm_test.table1  GROUP BY browser  )\n```\n\n### save\n\n```javascript\n// new data model\nconst data = Table1Model.build();\n\n// set value\ndata.time = new _Date_();\ndata.status = 1;\ndata.browser = \"chrome\";\ndata.browser_v = \"90.0.1.21\";\n\n// do save\ndata.save().then((res) => {\n  console.log(\"save:\", res);\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### create\n\n```javascript\n//do create\nawait Table1Model.create({\n  status: 1,\n  time: new Date(),\n  browser: \"chrome\",\n  browser_v: \"90.0.1.21\",\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### InsertMany\n\n```javascript\nconst list = [\n  { status: 2, browser: \"IE\", browser_v: \"10.0.1.21\" },\n  { status: 2, browser: \"FF\", browser_v: \"2.0.3\" },\n  { status: 3, browser: \"IE\", browser_v: \"1.1.1\" },\n];\n\nTable1Model.insertMany(list);\n// or\nTable1Model.insertMany(\n  list.map((item) => {\n    const data = Table1Model.build();\n    // set value\n    data.time = new Date();\n    data.status = item.status;\n    data.browser = item.browser;\n    data.browser_v = item.browser_v;\n    return data;\n  })\n);\n```\n\nFinal executed SQL:\n\n```sql\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"IE\",\"browser_v\":\"10.0.1.21\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"FF\",\"browser_v\":\"2.0.3\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":3,\"browser\":\"IE\",\"browser_v\":\"1.1.1\"}]\n```\n\n### delete\n\n```javascript\n\nTable1Model.delete({\n  where: `browser='Chrome'`,\n})\n```\n\nFinal executed SQL:\n\n```sql\nALTER TABLE orm_test.table1  DELETE  WHERE browser='Chrome'\n```\n\n## cluster\n\n**Create a cluster instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_cluster_test\",\n    cluster: \"default_cluster\",\n  },\n  // ...other\n});\nconst table2Schema = {\n  // table name\n  tableName: \"table2\",\n  ...other,\n};\n\n// create database 'orm_cluster_test'\n// SQL: CREATE DATABASE IF NOT EXISTS orm_cluster_test ON CLUSTER default_cluster\nawait chOrm.createDatabase();\n\n// register schema and create [if] table\n// createTable() SQL: CREATE TABLE IF NOT EXISTS orm_cluster_test.table2 ON CLUSTER default_cluster...\nconst Table2Model = await chOrm.model(table2Schema);\n```\n\n# Wechat Discussion\n\n[Click to join](https://github.com/zimv/node-clickhouse-orm/issues/3)\n","readmeFilename":"README.md","gitHead":"96bd3945d97cf74aa2ae121a8d77b74535e64212","_id":"clickhouse-orm@3.0.0-alpha4","_nodeVersion":"16.15.1","_npmVersion":"9.2.0","dist":{"integrity":"sha512-SMo15fqz5hkfSj1z9jCajzD2sjp+PEsvxBqDOfa4FPtSxtCIBd0nX5zOawfCFmQ4qB1jjkqV4cHIsSkakxo8xg==","shasum":"3a2705d533c36f03d4aef118c49606f3ea8571ca","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-3.0.0-alpha4.tgz","fileCount":26,"unpackedSize":70915,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICwr8U22PoMpaTnWXZ9+PxpZTZLLe4EHEbSpCWSRso3gAiBoh0SV6OXnFpX/EqcjXQNdUKkcBQSHFzFSMm85epq/Qg=="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjt9QUACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmpe0RAAoS6b99SzX/9pr6YL2eo+6MM4tBI19Pq0WLe/9yzEDG3mIXbe\r\n8As2FkT71epvB/aN1cn8wO3EBrClncO13N/00iDQgMQSpiME8ONiGmK1guMO\r\nr6Zfg0Zg4NPTmCbF746KVSCDANK+mCbmZI3WMRJdO+FPV+aU9YfVNH3eo51w\r\nZBNZQTM6x+Gy4sowa+T27bcCKsqTZbh+oMoQIrFvlgSn0ClXcx77bq4FskzR\r\ne+GOXTprlm+ErdXEPojtSq/+7lCTJzWwwq1JcmbH2VZO3lNrYdp+XFT+fjGu\r\nVvL8/mSTXKonQ2jsZFdSn5xgJ/YwVOYV9IC7VOIrHn1/LhgIKRl+qMWpCjlL\r\nGNVknxVg6DXOdUlt2zmlwF0J9Go8djnbwWSp77R6cSv7dJwb3W40lGKCEo91\r\nj1Sm9RH3lRyK2+WExHmSf0d3OBGUUEfiGPJQ8arNBdwk1t4Ny1bstSM1Op8Z\r\n11X1aBxOVrhnS1+0NA4Q+r3vYiMXEPN3bZNpc6c7tGZMJ8IHmLiMG4Tlbu0l\r\nnUcGTBHoPDRotbu1RAq0tVONQ/IlQZkcv9Rgvb5FO+LSIhfAm0wZtjd3FIbF\r\nyfivm5jwtX2hkRmNznHG4f4T46+7ah5VTUpIZNJZ+6Yc7CIpdpIeFpsPYabC\r\nE8Nq2JxrVNrTkhtwLuBZPgS/XKTo9JUh2eo=\r\n=/KUq\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_3.0.0-alpha4_1672991763799_0.13733555789260898"},"_hasShrinkwrap":false},"3.0.0-alpha5":{"name":"clickhouse-orm","version":"3.0.0-alpha5","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","build":"rm -rf ./dist & npm run tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","ts-datatype":"ts-node ./examples/datatype.ts","ts-sync":"ts-node ./examples/syncTable.ts","test":"jest --coverage","coveralls":"jest --coverage --coverageReporters=text-lcov | coveralls"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","coveralls":"^3.1.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/index.js","types":"dist/index.d.ts","readme":"[![Coverage Status](https://coveralls.io/repos/github/zimv/node-clickhouse-orm/badge.svg?branch=feature/3.0)](https://coveralls.io/github/zimv/node-clickhouse-orm?branch=feature/3.0)\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/05ad3e5cb52b4c149b47362377505916~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://npms.io/search?q=clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/bb03631752ce4ccf89445f94a4a02d97~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM total downloads\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4cb1a7ae1bf14cda804c0b3db0d50252~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github stars\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a5df26c796d14e53a63f4f08afcd630f~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github forks\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/57da9f95623043dbb052d873ebeac981~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github contributors\"><img src=\"https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ab0ae120764e474db09c743634b102f9~tplv-k3u1fbpfcp-zoom-1.image\"></a>\n\n# clickhouse-orm  [(中文 README)](https://github.com/zimv/node-clickhouse-orm/blob/main/README-zh.md)\n\n[![Join the chat at https://gitter.im/zimv/node-clickhouse-orm](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/8230cfb055bc4f1699e1749b6a7a3421~tplv-k3u1fbpfcp-zoom-1.image)](https://gitter.im/zimv/node-clickhouse-orm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n\nClickhouse ORM for Nodejs. Send query over HTTP interface. Using [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n# Install:\n\n```\nnpm i clickhouse-orm\n```\n\n# Usage\n\n**Create instance：**\n\n```typescript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_test\",\n  },\n  debug: true,\n  client: {\n    url: \"localhost\",\n    port: \"8123\",\n    basicAuth: {\n      username: \"default\",\n      password: \"\",\n    },\n    debug: false,\n    isUseGzip: true,\n    format: \"json\", // \"json\" || \"csv\" || \"tsv\"\n  },\n});\n```\n\n**Define Model：**\n* ModelConfig\n\n```typescript\nimport { DATA_TYPE, ModelSqlCreateTableConfig } from 'clickhouse-orm';\nconst xxxSchema: ModelSqlCreateTableConfig = {\n  // table name\n  tableName: \"xxx\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.LowCardinality(DATA_TYPE.String) },\n    browser_v: { type: DATA_TYPE.String  }\n  },\n};\n```\n----\n* ModelSyncTableConfig **(Recommended)**\n\nAutomatically create tables and automatically synchronize table field structures\n\n```typescript\nimport { DATA_TYPE, ModelSyncTableConfig } from 'clickhouse-orm';\nconst oldSchema: ModelSyncTableConfig = {\n  tableName: \"xxx\",\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    will_typeChanged: { type: DATA_TYPE.Int16 },\n    will_deleted: { type: DATA_TYPE.String },\n  },\n  options: `ENGINE = MergeTree\n  PARTITION BY toYYYYMM(time)\n  ORDER BY time`,\n  autoCreate: true,\n  autoSync: true,\n};\n```\nSynchronize the table structure (just the field columns) when creating the model. When the model is created, the field structure of the remote database table will be pulled for comparison with the schema in the current code. Finally, the ORM will automatically execute (add, delete, and modify) statements.\n\n\n```typescript\nconst newSchema = {\n  ...oldSchema,\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    will_typeChanged: { type: DATA_TYPE.Int32 },\n    add_column: { type: DATA_TYPE.String },\n  }\n}\nchOrm.model(newSchema)\n```\n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  DROP COLUMN will_deleted \n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  ADD COLUMN add_column String \n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  MODIFY COLUMN will_typeChanged Int32\n\nUnrecognized field name modification! The following configuration will delete **column1** and add **column2**.\n\n```typescript\noldSchema = {\n  column1: { type: DATA_TYPE.String },\n}\nnewSchema = {\n  column2: { type: DATA_TYPE.String },\n}\n```\n\n**More in [SyncTable Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/syncTable.ts).**\n\n----\n* ModelSqlCreateTableConfig\n\nCustomized table creation statement, and the table will be created automatically when the model is created\n\n```typescript\n\nimport { DATA_TYPE, ModelSqlCreateTableConfig } from 'clickhouse-orm';\nconst xxxSchema: ModelSqlCreateTableConfig = {\n  // table name\n  tableName: \"xxx\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.LowCardinality(DATA_TYPE.String) },\n    browser_v: { type: DATA_TYPE.String  }\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n```\n**create / build + save / find：**\n\n```javascript\nconst doDemo = async () => {\n  // create database 'orm_test'\n  // SQL: CREATE DATABASE IF NOT EXISTS orm_test\n  await chOrm.createDatabase();\n\n  // register schema and create [if] table\n  // createTable() SQL: CREATE TABLE IF NOT EXISTS orm_test.table1...\n  const Table1Model = await chOrm.model(table1Schema);\n\n  // new data model\n  const data = Table1Model.build({ status: 2 });\n\n  // set value\n  data.time = new Date();\n  data.browser = \"chrome\";\n  data.browser_v = \"90.0.1.21\";\n\n  // do save\n  const res = await data.save();\n  // SQL: INSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":2,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\n  console.log(\"save:\", res);\n\n  // create === build + save\n  const resCreate = await Table1Model.create({\n    status: 1,\n    time: new Date(),\n    browser: \"chrome\",\n    browser_v: \"90.0.1.21\",\n  });\n  console.log(\"create:\", resCreate);\n\n  // do find\n  Table1Model.find({\n    select: \"*\",\n    limit: 3,\n  }).then((res) => {\n    // SQL: SELECT * from orm_test.table1    LIMIT 3\n    console.log(\"find:\", res);\n  });\n};\n\ndoDemo();\n```\n\n**More in [Basic Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/basic.js).**\n\n# Overview\n\n`Note`: '?' is a Optional\n\n### ClickhouseOrm\n\n\n\n`db` : object<{name:string, engine?:string, cluster?:string}>\n\n> name: database name\n\n> engine?: database engine\n\n> cluster?: cluster name\n\n`debug` : boolean\n\n> Default: false\n\n`client` : object\n\n> Drive configuration. More in [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n### ModelConfig\n* ModelConfig\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type?, default? } } | `Type` defines the data type, and `default` sets the default value |\n\n----\n* ModelSyncTableConfig\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type?, default? } } | `Type` defines the data type, and `default` sets the default value |\n| options | true | string | Create table setting |\n| autoCreate | true | boolean | Auto create table |\n| autoSync | false | boolean | Auto sync table structure`(Careful use)` |\n\n----\n* ModelSqlCreateTableConfig\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type?, default? } } | `Type` defines the data type, and `default` sets the default value |\n| createTable | true | string | It is the SQL for creating tables.When model is executed, this SQL will be executed. It is suggested to add 'IF NOT EXISTS'. <br> Watch out !!! >>>>> If the table already exists and you want to modify it. You need to execute the modification sql through other clients（Such as Remote terminal） and update the code of the Schema!!!|\n\n\n\n### DATA_TYPE\n\nClickhouse data type. Most of the following data will be validated by ORM, but only the basic data type `number | string | boolean | date` will be validated, not the most standard data type. For example, in `Int8`, ORM only verifies the `number` type.\n\n\n```typescript\n  UInt8;\n  UInt16;\n  UInt32;\n  UInt64;\n  Int8;\n  Int16;\n  Int32;\n  Int64;\n  Float32;\n  Float64;\n  Boolean;\n  String;\n  UUID;\n  Date;\n  Date32;\n  DateTime;\n  DateTime64;\n  /**\n   *\n   * @param Number\n   * @example DATA_TYPE.FixedString(3)\n   */\n  FixedString;\n  /**\n   *\n   * @param DATA_TYPE\n   * @example DATA_TYPE.LowCardinality(DATA_TYPE.String)\n   */\n  LowCardinality;\n  /**\n   *\n   * @param string\n   * @example DATA_TYPE.Enum8(`'hello' = 1, 'world' = 2`)\n   * @desc number [-128, 127]\n   */\n  Enum8:;\n  /**\n   *\n   * @param string\n   * @example DATA_TYPE.Enum16(`'hello' = 3000, 'world' = 3500`)\n   * @desc number [-32768, 32767]\n   */\n  Enum16;\n  /**\n   *\n   * @param columnType\n   * Clickhouse dataTypes: Array(T), JSON, Map(key, value), IPv4, Nullable(), more...\n   * @example DATA_TYPE.Other('Array(String)') , DATA_TYPE.Other('Int8')\n   * @desc No `INSERT` data validation provided\n   */\n  Other;\n```\n**More in [Datatype Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/datatype.ts).**\n### Log\n\nThe **setLogService** is a global configuration method and will affect all instances.\n\n`Default: console.log`\n\nCustom example: **[winston](https://github.com/winstonjs/winston)**\n\n```javascript\nconst { setLogService } = require(\"clickhouse-orm\");\nconst winston = require(\"winston\");\nconst logger = winston.createLogger();\n\nsetLogService(logger.info);\n```\n\n### Use SQL directly：\n\n```javascript\nchOrm.client\n  .query(`select * from orm_test.table1 limit 3`)\n  .toPromise()\n  .then((res) => {\n    console.log(\"Use sql:\", res);\n  });\n```\n\nThe `chOrm.client` is the [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse) instance.\n\n# [More Examples](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/more.ts)\n\n### Find\n\n```javascript\nimport * as dayjs from \"dayjs\";\n\nqueryExample1({\n  Model: Table1Model,\n  status: 1,\n  beginTime: dayjs().subtract(1, \"day\").format(\"YYYY-MM-DD HH:mm:ss\"),\n  endTime: dayjs().format(\"YYYY-MM-DD HH:mm:ss\"),\n}).then((res) => {\n  console.log(\"queryExample1:\", res);\n});\n\nconst queryExample1 = ({ Model, status, beginTime, endTime }) => {\n  let wheres = [],\n    where;\n  if (status) wheres.push(`status='${status}'`);\n  if (beginTime) wheres.push(`time>='${beginTime}'`);\n  if (endTime) wheres.push(`time<='${endTime}'`);\n  if (wheres.length > 0) where = wheres.join(\" and \");\n\n  return Model.find({\n    where,\n    select: `*`,\n    orderBy: \"time ASC\",\n    limit: 5,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT * from orm_test.table1 where status='1' and time>='2022-02-04 15:34:22' and time<='2022-02-05 15:34:22'  ORDER BY time ASC LIMIT 5\n```\n\n### Count\n\n```javascript\ncountExample1({\n  Model: Table1Model,\n}).then((res) => {\n  console.log(\"countExample1:\", res);\n});\n\nconst countExample1 = ({ Model }) => {\n  return Model.find({\n    select: `count(*) AS total`,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count(*) AS total from orm_test.table1\n```\n\n### GroupBy\n\n```javascript\nTable1Model.find({\n  select: `status,browser`,\n  groupBy: \"status,browser\",\n});\n```\n\nFinal executed SQL:\n\n```sql\nSELECT status,browser from orm_test.table1  GROUP BY status,browser\n```\n\n### Nested Queries\n\n```javascript\nTable1Model.find([\n  {\n    select: `browser`,\n    groupBy: \"browser\",\n  },\n  {\n    select: `count() as browserTotal`,\n  },\n]);\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count() as browserTotal from (SELECT browser from orm_test.table1  GROUP BY browser  )\n```\n\n### save\n\n```javascript\n// new data model\nconst data = Table1Model.build();\n\n// set value\ndata.time = new _Date_();\ndata.status = 1;\ndata.browser = \"chrome\";\ndata.browser_v = \"90.0.1.21\";\n\n// do save\ndata.save().then((res) => {\n  console.log(\"save:\", res);\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### create\n\n```javascript\n//do create\nawait Table1Model.create({\n  status: 1,\n  time: new Date(),\n  browser: \"chrome\",\n  browser_v: \"90.0.1.21\",\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### InsertMany\n\n```javascript\nconst list = [\n  { status: 2, browser: \"IE\", browser_v: \"10.0.1.21\" },\n  { status: 2, browser: \"FF\", browser_v: \"2.0.3\" },\n  { status: 3, browser: \"IE\", browser_v: \"1.1.1\" },\n];\n\nTable1Model.insertMany(list);\n// or\nTable1Model.insertMany(\n  list.map((item) => {\n    const data = Table1Model.build();\n    // set value\n    data.time = new Date();\n    data.status = item.status;\n    data.browser = item.browser;\n    data.browser_v = item.browser_v;\n    return data;\n  })\n);\n```\n\nFinal executed SQL:\n\n```sql\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"IE\",\"browser_v\":\"10.0.1.21\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"FF\",\"browser_v\":\"2.0.3\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":3,\"browser\":\"IE\",\"browser_v\":\"1.1.1\"}]\n```\n\n### delete\n\n```javascript\n\nTable1Model.delete({\n  where: `browser='Chrome'`,\n})\n```\n\nFinal executed SQL:\n\n```sql\nALTER TABLE orm_test.table1  DELETE  WHERE browser='Chrome'\n```\n\n## cluster\n\n**Create a cluster instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_cluster_test\",\n    cluster: \"default_cluster\",\n  },\n  // ...other\n});\nconst table2Schema = {\n  // table name\n  tableName: \"table2\",\n  ...other,\n};\n\n// create database 'orm_cluster_test'\n// SQL: CREATE DATABASE IF NOT EXISTS orm_cluster_test ON CLUSTER default_cluster\nawait chOrm.createDatabase();\n\n// register schema and create [if] table\n// createTable() SQL: CREATE TABLE IF NOT EXISTS orm_cluster_test.table2 ON CLUSTER default_cluster...\nconst Table2Model = await chOrm.model(table2Schema);\n```\n\n# Wechat Discussion\n\n[Click to join](https://github.com/zimv/node-clickhouse-orm/issues/3)\n","readmeFilename":"README.md","gitHead":"c31aa30932893850753a04b4ea85bcd974814084","_id":"clickhouse-orm@3.0.0-alpha5","_nodeVersion":"16.15.1","_npmVersion":"9.2.0","dist":{"integrity":"sha512-Ds8QRfyNcj/hK+GsMi0+4ekd8p8l2hqZVgh6e2CJc61k5i95LGumdenv/ykezjsbt2pWntd/wEodxQEMV11iwA==","shasum":"6552598e9008e0d2ac7976bb200543950e954749","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-3.0.0-alpha5.tgz","fileCount":26,"unpackedSize":70813,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDT2wGe+Hv6TcvdlQBPZrWuAfA7giiv96Pa5t6qMvDcPQIhAN8MyLI0lqr3lLS4jYoOVuk7H57t2E1lU0np6IuS73XL"}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJju89VACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmoWeg/9G9gT8SG1RDx3dlzgTfK30CtP5gZNN1fCRyP3/Z8nBEuapeBf\r\nHa+O1yMjwMg6oJHuyBKKw6+irbQlZiO0gzhDLUwNj5d9ydqdatjlCTuZhjS7\r\njhFdCbkXtmICJbZ9oJtXIiBdkXirpLeBgcgxAljW3LFdfpVjwrGPxjh25U8w\r\ng3+HsXGtz2Ju8ehXQskMD+UX9krt92Ynir1U5O6QPtFOcz9efrxg3fzsbwwu\r\nohzv45u/zkJCriHeYB2+aotXUa41TBld53qEs8GpoqP0s3x+5S8Rm4Q1BvR7\r\n6niaWafmcIoeZW62y0sD2ffChSxKP24MhOuNJ20LRhEqd4vDvwNBClKwgs8+\r\nEbNfxZ+zjHJIHMrYfs4BsPXbz3UMbxg2JERpYCtGqtAhQdwQzqfpPWysPhUt\r\nJBcwE9EhshWHHFD3+LCbjKwcfgLlGdQJeJuxDoltCNdqtQjIWH6uwMjoji9H\r\nZk45YsLQ5/XXmYYM+KAlydSGqKv7JlAn6uQVx2tg1FfW4pArARR2trCqyVJk\r\n5S34gnUXiCv55n/gYPiOTHvnUrlPuFcgOhEDRCqmqAYj3fBSdGolSK1VRZIP\r\nj3HuCjD+KTf2QRr5qj6X2IGb4HJSa37R8tz1FhwMNFxTNz9I2xLPnlQ0fRTr\r\nkVcz6fGxTluUQXqcPUTucf7tCvtd2TNnvIc=\r\n=7OKK\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_3.0.0-alpha5_1673252692920_0.020504779333218925"},"_hasShrinkwrap":false},"3.0.0":{"name":"clickhouse-orm","version":"3.0.0","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","build":"rm -rf ./dist & npm run tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","ts-datatype":"ts-node ./examples/datatype.ts","ts-sync":"ts-node ./examples/syncTable.ts","test":"jest --coverage","coveralls":"jest --coverage --coverageReporters=text-lcov | coveralls"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","coveralls":"^3.1.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"180577a92a30bdcd17482c2cb7b6e0a6640d409a","_id":"clickhouse-orm@3.0.0","_nodeVersion":"16.15.1","_npmVersion":"9.2.0","dist":{"integrity":"sha512-RXOu6KEj9a2BPCDs9FjXEuWHVZSfBFHJ0vjXPgk6MrY5MIgtrSw6pHWF6uuHgd3We1Z4J2gt9w7I9kqewgnDCQ==","shasum":"72a7c6e391143587a87e374ea21581281f3d0d7d","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-3.0.0.tgz","fileCount":26,"unpackedSize":71046,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDU22msQHfkAFT3T+ioXbz4jCQV5mTJBqFvrfd2xnv8CQIhALqixM14YYJLjo5dfUl6YmN7Eq0SEjELt+jl6jhD5A0n"}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjvmOOACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmp+1w//RAXc8UsUuIGlSJVGSwdwXP0taGYAC+6bRl9KFYNQk0fhZJte\r\nU4EUPfCo3Xq9sdDAIF6m5ewrHYvNPNYT2pdgg2hUAiiFzeGNyHH1nTSl2Ynu\r\nq7DIPUbv79eFnwNyrXu0bSzWY6vtlz4TbNqCZaN5ryzn4PCVRdROMP71ljQq\r\nAQq7h0I56wSbKhXRWZZ59dGJCppDC2O7BmBRiusJ2lR7xfOdEfWs3HJn0uDN\r\nghh/z83W+c2Y/+IWtgTF3RMu4uH0lO7IxLpTXdZVQuRl4wu0x7VVIDjngZDE\r\nQ8XkFWM6GkfXu/Zg/c15SdiF9fg7xlVimrMQB0G45Ai22naqnP+sRedBl/qa\r\n+16YVWJctdJtEI0aWXtGTkjbIlcmBwZAEMh82XFMyHEVaIx8QkSp3EUiQvzr\r\nmyyy3Ww4MkQefTl+gAr3ksa8kPTOgchssH3cH5UW4KJqudQ9uKX80EA94AVn\r\nE6NfazUGDpJFHK2k/UJBfb6e6m6DPc9WtlB+a9I74bkrVcyo5bylaIoN4W4a\r\nDOvq/miQClbD1EACEPcRd2b8CvtVYJr52FR68DlewFrZAZDVUgzq3IAZ45iS\r\ngLIST2sFt/TfN1sRtIvSqDLZOpIlVPa44wS1pcQ0Tjs3EBrYuyO4T+8rZq/W\r\n9zpJAaRrCNfmCLpHMq55BEE0CQYu/9hi998=\r\n=8rhb\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_3.0.0_1673421710020_0.4159295971092756"},"_hasShrinkwrap":false},"3.0.1":{"name":"clickhouse-orm","version":"3.0.1","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","build":"rm -rf ./dist & npm run tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","ts-datatype":"ts-node ./examples/datatype.ts","ts-sync":"ts-node ./examples/syncTable.ts","test":"jest --coverage","coveralls":"jest --coverage --coverageReporters=text-lcov | coveralls"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","coveralls":"^3.1.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"c559c8a988c1773c8382e8a29155fff8dcca5030","_id":"clickhouse-orm@3.0.1","_nodeVersion":"16.15.1","_npmVersion":"9.2.0","dist":{"integrity":"sha512-dQZ4PuNp1ojIIR3MqK7V7WLynbnrUPWyxdn2Trrr0S8xjTHmU28Poc1xxQs4OW2ijrLRTYQnDemS6iiPdvdNEA==","shasum":"c81cccb7e1f43c63a6a42f432693448442272316","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-3.0.1.tgz","fileCount":26,"unpackedSize":70721,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIBOkirYXXr3RXDaVWr+havlMAWmdbaoO6MN6oUNpo+ZRAiEA1QusEoN/YYhTWol8rwn7GxqiN1X4Nit0JsOvNQhGaNQ="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjvmpxACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmojgxAAhisRKa2Qs/CTtRGiJdKQBgS58gpE8SOsZXyGMnSgEdU1KMl2\r\niakpZqA8Bhikmqt3A4U+5oL9qmIf5epCz9zlmNd1pLktxoI2v5jro2kmhGDV\r\npQRwoI7pTgDZyrL/0i6oXt0s2zAwx/9dKV1JudFuCbKRqCx4P4gAJ/69fsDX\r\nNY7W+tQkLBeQU1Rg87sTdLW9uSKplJ+o90G2dNENRj30kW2im7FNmqW+oYXH\r\nwZZKWoUagCojuvjjCnl3URcJOfOFwpGIT480CLBBL/HGylagDbQnZ7zpysRU\r\nwGrz2+bdiq39xPFWnUhzCQf6A+anxQgCCStwO0x9zW330Yke99kFxWkTWn+o\r\nqRzqgzb+w3705rHyRr7l8dQ3lYrJDUUxGC4ZyfCdevNRLdJDaOtZ8QnOhXe1\r\n0MwvaximFLyxnhliRDTo2Kjfoj/VP9PQ6mQxdX4ZHYo6kPj0ot4VHtqyQohE\r\nZkDAa3X7BwlCVfm4SsqMhyUxF62m1wbJIGAhDFxZ959XZ4qP5JOOrdJCHeTr\r\nMxc6gzwIdZF2Kr/Okav7sDqwfzEMDNTUiB5p6y9Ndn+kBfc4Bz+elguJ2W+5\r\n4nFVyAvIE9LLSR6PLk2vfNZZIlAdsrJfTJSsqRwOwZ47VhuU4bYLylMbv2nE\r\nsdXqHdD8YaTudGlVP/E/1xjhRuO4KE2BLIs=\r\n=DrMs\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_3.0.1_1673423473803_0.28878860054910027"},"_hasShrinkwrap":false},"3.0.2-alpha1":{"name":"clickhouse-orm","version":"3.0.2-alpha1","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","build":"rm -rf ./dist & npm run tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","ts-datatype":"ts-node ./examples/datatype.ts","ts-sync":"ts-node ./examples/syncTable.ts","test":"jest --coverage","coveralls":"jest --coverage --coverageReporters=text-lcov | coveralls"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","coveralls":"^3.1.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/index.js","types":"dist/index.d.ts","readme":"[![Coverage Status](https://coveralls.io/repos/github/zimv/node-clickhouse-orm/badge.svg?branch=main)](https://coveralls.io/github/zimv/node-clickhouse-orm?branch=main)\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://img.shields.io/npm/v/clickhouse-orm.svg\"></a>\n<a href=\"https://npms.io/search?q=clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://badges.npms.io/clickhouse-orm.svg\"></a>\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM total downloads\"><img src=\"https://img.shields.io/npm/dt/clickhouse-orm.svg\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github stars\"><img src=\"https://img.shields.io/github/stars/zimv/node-clickhouse-orm.svg?style=social&label=Star\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github forks\"><img src=\"https://img.shields.io/github/forks/zimv/node-clickhouse-orm.svg?style=social&label=Fork\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github contributors\"><img src=\"https://img.shields.io/github/contributors/zimv/node-clickhouse-orm.svg\"></a>\n\n# clickhouse-orm  [(中文 README)](https://github.com/zimv/node-clickhouse-orm/blob/main/README-zh.md)\n\n[![Join the chat at https://gitter.im/zimv/node-clickhouse-orm](https://badges.gitter.im/zimv/node-clickhouse-orm.svg)](https://gitter.im/zimv/node-clickhouse-orm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n\nClickhouse ORM for Nodejs. Send query over HTTP interface. Using [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n# Install:\n\n```\nnpm i clickhouse-orm\n```\n\n# Usage\n\n**Create instance：**\n\n```typescript\nconst { ClickhouseOrm } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_test\",\n  },\n  debug: true,\n  client: {\n    url: \"localhost\",\n    port: \"8123\",\n    basicAuth: {\n      username: \"default\",\n      password: \"\",\n    },\n    debug: false,\n    isUseGzip: true,\n    format: \"json\", // \"json\" || \"csv\" || \"tsv\"\n  },\n});\n```\n\n**Define Model：**\n```typescript\nimport { DATA_TYPE, ModelSyncTableConfig } from 'clickhouse-orm';\nconst table1Schema: ModelSyncTableConfig<{\n  status?: number;\n  time: Date;\n  browser?: string;\n  browser_v?: string;\n}> = {\n  tableName: \"table1\",\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: { type: DATA_TYPE.String },\n  },\n  options: `ENGINE = MergeTree\n  PARTITION BY toYYYYMM(time)\n  ORDER BY time`,\n  autoCreate: true,\n  autoSync: true,\n};\n```\n\n**Create data / Find：**\n\n```typescript\n// create database 'orm_test'\nawait chOrm.createDatabase();\n// register schema and create [if] table\nconst Table1Model = await chOrm.model(table1Schema);\n\n// create data\nconst resCreate = await Table1Model.create({\n  status: 1,\n  time: new Date(),\n  browser: \"chrome\",\n  browser_v: \"90.0.1.21\",\n});\nconsole.log(\"create:\", resCreate);\n\n// find\nTable1Model.find({\n  select: \"*\",\n  limit: 3,\n}).then((res) => {\n  // SQL: SELECT * from orm_test.table1 LIMIT 3\n  console.log(\"find:\", res);\n});\n```\n\n**More in [Basic Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/basic.js).**\n\n# Document\n\n`Note`: '?' is a Optional\n\n### ClickhouseOrm\n\n\n\n`db` : object<{name:string, engine?:string, cluster?:string}>\n\n> name: database name\n\n> engine?: database engine\n\n> cluster?: cluster name\n\n`debug` : boolean\n\n> Default: false\n\n`client` : object\n\n> Drive configuration. More in [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n### Model config params\n**1. ModelConfig**\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type, default? } } | `Type` defines the data type, and `default` sets the default value |\n\n\n```typescript\nimport { DATA_TYPE, ModelConfig } from 'clickhouse-orm';\nconst xxxSchema: ModelConfig<{\n  status?: number;\n  time: Date;\n  browser?: string;\n  browser_v?: string;\n}> = {\n  // table name\n  tableName: \"xxx\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.LowCardinality(DATA_TYPE.String) },\n    browser_v: { type: DATA_TYPE.String  }\n  },\n};\n```\n----\n\n\n**2. ModelSyncTableConfig** (Recommended)\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type, default? } } | `Type` defines the data type, and `default` sets the default value |\n| options | true | string | Create table setting |\n| autoCreate | true | boolean | Auto create table |\n| autoSync | false | boolean | Auto sync table structure`(Careful use)` |\n \n\nAutomatically create tables and automatically synchronize table field structures\n\n```typescript\nimport { DATA_TYPE, ModelSyncTableConfig } from 'clickhouse-orm';\nconst oldSchema: ModelSyncTableConfig<{\n    time: Date;\n    will_typeChanged?: number;\n    will_deleted?: string;\n  }> = {\n  tableName: \"xxx\",\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    will_typeChanged: { type: DATA_TYPE.Int16 },\n    will_deleted: { type: DATA_TYPE.String },\n  },\n  options: `ENGINE = MergeTree\n  PARTITION BY toYYYYMM(time)\n  ORDER BY time`,\n  autoCreate: true,\n  autoSync: true,\n};\n```\nSynchronize the table structure (just the field columns) when creating the model. When the model is created, the field structure of the remote database table will be pulled for comparison with the schema in the current code. Finally, the ORM will automatically execute (add, delete, and modify) statements.\n\n\n```typescript\nconst newSchema = {\n  ...oldSchema,\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    will_typeChanged: { type: DATA_TYPE.Int32 },\n    add_column: { type: DATA_TYPE.String },\n  }\n}\nchOrm.model(newSchema)\n```\n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  DROP COLUMN will_deleted \n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  ADD COLUMN add_column String \n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  MODIFY COLUMN will_typeChanged Int32\n\nUnrecognized field name modification! The following configuration will delete **column1** and add **column2**.\n\n```typescript\noldSchema = {\n  column1: { type: DATA_TYPE.String },\n}\nnewSchema = {\n  column2: { type: DATA_TYPE.String },\n}\n```\n\n**More in [SyncTable Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/syncTable.ts).**\n\n----\n**3. ModelSqlCreateTableConfig**\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type, default? } } | `Type` defines the data type, and `default` sets the default value |\n| createTable | true | string | It is the SQL for creating tables.When model is executed, this SQL will be executed. It is suggested to add 'IF NOT EXISTS'. <br> Watch out !!! >>>>> If the table already exists and you want to modify it. You need to execute the modification sql through other clients（Such as Remote terminal） and update the code of the Schema!!!|\n\n\nCustomized table creation statement, and the table will be created automatically when the model is created\n\n```typescript\nimport { DATA_TYPE, ModelSqlCreateTableConfig } from 'clickhouse-orm';\nconst xxxSchema: ModelSqlCreateTableConfig<{\n    status?: number;\n    time: Date;\n    browser?: string;\n    browser_v?: string;\n  }> = {\n  // table name\n  tableName: \"xxx\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.LowCardinality(DATA_TYPE.String) },\n    browser_v: { type: DATA_TYPE.String  }\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n```\n\n### DATA_TYPE\n\nClickHouse data type. Most of the following data will be validated by ORM, but only the basic data type `number | string | boolean | date` will be validated, not the most standard data type. For example, in `Int8`, ORM only verifies the `number` type.\n\n\n```typescript\n  UInt8;\n  UInt16;\n  UInt32;\n  UInt64;\n  Int8;\n  Int16;\n  Int32;\n  Int64;\n  Float32;\n  Float64;\n  Boolean;\n  String;\n  UUID;\n  Date;\n  Date32;\n  DateTime;\n  DateTime64;\n  /**\n   *\n   * @param Number\n   * @example DATA_TYPE.FixedString(3)\n   */\n  FixedString;\n  /**\n   *\n   * @param DATA_TYPE\n   * @example DATA_TYPE.LowCardinality(DATA_TYPE.String)\n   */\n  LowCardinality;\n  /**\n   *\n   * @param string\n   * @example DATA_TYPE.Enum8(`'hello' = 1, 'world' = 2`)\n   * @desc number [-128, 127]\n   */\n  Enum8;\n  /**\n   *\n   * @param string\n   * @example DATA_TYPE.Enum16(`'hello' = 3000, 'world' = 3500`)\n   * @desc number [-32768, 32767]\n   */\n  Enum16;\n  /**\n   *\n   * @param columnType\n   * Clickhouse dataTypes: Array(T), JSON, Map(key, value), IPv4, Nullable(), more...\n   * @example DATA_TYPE.Other('Array(String)') , DATA_TYPE.Other('Int8')\n   * @desc No `INSERT` data validation provided\n   */\n  Other;\n```\n**More in [Datatype Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/datatype.ts).**\n### Log\n\nThe **setLogService** is a global configuration method and will affect all instances.\n\n`Default: console.log`\n\nCustom example: **[winston](https://github.com/winstonjs/winston)**\n\n```javascript\nconst { setLogService } = require(\"clickhouse-orm\");\nconst winston = require(\"winston\");\nconst logger = winston.createLogger();\n\nsetLogService(logger.info);\n```\n\n### Use SQL directly：\n\n```javascript\nchOrm.client\n  .query(`select * from orm_test.table1 limit 3`)\n  .toPromise()\n  .then((res) => {\n    console.log(\"Use sql:\", res);\n  });\n```\n\nThe `chOrm.client` is the [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse) instance.\n\n# [More Examples](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/more.ts)\n\n### Find\n\n```javascript\nimport * as dayjs from \"dayjs\";\n\nqueryExample1({\n  Model: Table1Model,\n  status: 1,\n  beginTime: dayjs().subtract(1, \"day\").format(\"YYYY-MM-DD HH:mm:ss\"),\n  endTime: dayjs().format(\"YYYY-MM-DD HH:mm:ss\"),\n}).then((res) => {\n  console.log(\"queryExample1:\", res);\n});\n\nconst queryExample1 = ({ Model, status, beginTime, endTime }) => {\n  let wheres = [],\n    where;\n  if (status) wheres.push(`status='${status}'`);\n  if (beginTime) wheres.push(`time>='${beginTime}'`);\n  if (endTime) wheres.push(`time<='${endTime}'`);\n  if (wheres.length > 0) where = wheres.join(\" and \");\n\n  return Model.find({\n    where,\n    select: `*`,\n    orderBy: \"time ASC\",\n    limit: 5,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT * from orm_test.table1 where status='1' and time>='2022-02-04 15:34:22' and time<='2022-02-05 15:34:22'  ORDER BY time ASC LIMIT 5\n```\n\n### Count\n\n```javascript\ncountExample1({\n  Model: Table1Model,\n}).then((res) => {\n  console.log(\"countExample1:\", res);\n});\n\nconst countExample1 = ({ Model }) => {\n  return Model.find({\n    select: `count(*) AS total`,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count(*) AS total from orm_test.table1\n```\n\n### GroupBy\n\n```javascript\nTable1Model.find({\n  select: `status,browser`,\n  groupBy: \"status,browser\",\n});\n```\n\nFinal executed SQL:\n\n```sql\nSELECT status,browser from orm_test.table1  GROUP BY status,browser\n```\n\n### Nested Queries\n\n```javascript\nTable1Model.find([\n  {\n    select: `browser`,\n    groupBy: \"browser\",\n  },\n  {\n    select: `count() as browserTotal`,\n  },\n]);\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count() as browserTotal from (SELECT browser from orm_test.table1  GROUP BY browser  )\n```\n\n### save\n\n```javascript\n// new data model\nconst data = Table1Model.build();\n\n// set value\ndata.time = new _Date_();\ndata.status = 1;\ndata.browser = \"chrome\";\ndata.browser_v = \"90.0.1.21\";\n\n// do save\ndata.save().then((res) => {\n  console.log(\"save:\", res);\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### create\n\n```javascript\n//do create\nawait Table1Model.create({\n  status: 1,\n  time: new Date(),\n  browser: \"chrome\",\n  browser_v: \"90.0.1.21\",\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### InsertMany\n\n```javascript\nconst list = [\n  { status: 2, browser: \"IE\", browser_v: \"10.0.1.21\" },\n  { status: 2, browser: \"FF\", browser_v: \"2.0.3\" },\n  { status: 3, browser: \"IE\", browser_v: \"1.1.1\" },\n];\n\nTable1Model.insertMany(list);\n// or\nTable1Model.insertMany(\n  list.map((item) => {\n    const data = Table1Model.build();\n    // set value\n    data.time = new Date();\n    data.status = item.status;\n    data.browser = item.browser;\n    data.browser_v = item.browser_v;\n    return data;\n  })\n);\n```\n\nFinal executed SQL:\n\n```sql\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"IE\",\"browser_v\":\"10.0.1.21\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"FF\",\"browser_v\":\"2.0.3\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":3,\"browser\":\"IE\",\"browser_v\":\"1.1.1\"}]\n```\n\n### delete\n\n```javascript\n\nTable1Model.delete({\n  where: `browser='Chrome'`,\n})\n```\n\nFinal executed SQL:\n\n```sql\nALTER TABLE orm_test.table1  DELETE  WHERE browser='Chrome'\n```\n\n## cluster\n\n**Create a cluster instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_cluster_test\",\n    cluster: \"default_cluster\",\n  },\n  // ...other\n});\nconst table2Schema = {\n  // table name\n  tableName: \"table2\",\n  ...other,\n};\n\n// create database 'orm_cluster_test'\n// SQL: CREATE DATABASE IF NOT EXISTS orm_cluster_test ON CLUSTER default_cluster\nawait chOrm.createDatabase();\n\n// register schema and create [if] table\n// createTable() SQL: CREATE TABLE IF NOT EXISTS orm_cluster_test.table2 ON CLUSTER default_cluster...\nconst Table2Model = await chOrm.model(table2Schema);\n```\n\n# Wechat Discussion\n\n[Click to join](https://github.com/zimv/node-clickhouse-orm/issues/3)\n\n##### or\n\n[![Join the chat at https://gitter.im/zimv/node-clickhouse-orm](https://badges.gitter.im/zimv/node-clickhouse-orm.svg)](https://gitter.im/zimv/node-clickhouse-orm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)","readmeFilename":"README.md","gitHead":"67744c78dee995c1ea1069c22375a7f78411b54a","_id":"clickhouse-orm@3.0.2-alpha1","_nodeVersion":"16.15.1","_npmVersion":"9.2.0","dist":{"integrity":"sha512-7Qnr1BsG++3uJwmXHVUHxuNOx5JKMLnKuEhXNyEOrUO4fEVB4blorJ7CHEm6MU6Mh21K3FqlKYgj/dZnMBZH0g==","shasum":"2506f3f6c9d16d67639314c5ce590b60e42b47f3","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-3.0.2-alpha1.tgz","fileCount":26,"unpackedSize":72992,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCnpWsSdtnyzckiHQ5BBm/1bH8pGpeSSyVVyNkWtyLISgIgKnVP4IZ2tVEKHcIFpy32+2uMZKfcSGXtLt6ktQBkeBw="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJj0gHPACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmprnRAAhey5TDjvSNqbhGTSPSglqq5vinByuGr74t8pSP1vk2ZP+pZ9\r\nGanHtAdG4W609ORbG7lj38cqS1O2ixmXzmODJhjOQwRaUY+aVtnqozH9/Enr\r\njv/5thVSJ3n0njyPBLB/2j1YrxZ1gyqa7Hv9UOuKD/BRn/ooCf8kFp42NjlF\r\n1ZfIdM7O/EwPJyx5f3Dsr/sAnWKc3dydjT6d/THoDNS36swiYeYTnq/4MsA/\r\nIj54Jcb/GgrDW99lsfTAUxAA3BmIxd7Be4lnR957H1MTz8JRXEk9PYwOPT+L\r\nJwuTdlX5drcQx3N1svmoHEueHwyNmcVDS7guBm7xhztLNNg8fu02tjcQBhfH\r\njGRtzwcJWQ08QXRRM6V2qDaD7cowybMOWnDP91J7UiwYul8H4y/pdksCwjKJ\r\nMAF5Y7XyCQ7VfR13j1yqHBFC3k0BiaTWkW4MHXHjB2hyb389qU9Qbad4dhOt\r\nTJx7PaYt3Z/ot/kHkoM0X42XAosNdUupq8wYjYEhUjRHF62Z1lOf4zhmMZh+\r\nb9iEmPp8mJiPa7PIa+rfKazg7g+MBV3iAK/udddaDwUoXJkGoFgs7LCkMUnE\r\n0kWFNPF5nPHtOBq6vvY5VMYiefMPY5doVpc8k1IsW6hNyz6ZSM69DJJaQMLc\r\n0qeFXbteuUAnKVIlr3CQit3dgFQMc8FZWz8=\r\n=q4q5\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_3.0.2-alpha1_1674707407783_0.16189569879900878"},"_hasShrinkwrap":false},"3.0.2":{"name":"clickhouse-orm","version":"3.0.2","description":"Clickhouse orm for Nodejs","repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"keywords":["zimv","clickhouse","orm"],"author":{"name":"zimv"},"license":"MIT","bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"homepage":"https://github.com/zimv/node-clickhouse-orm#readme","scripts":{"tsc":"tsc","build":"rm -rf ./dist & npm run tsc","ts-basic":"ts-node ./examples/basic.ts","node-basic":"node ./examples/basic","ts-more":"ts-node ./examples/more.ts","ts-cluster":"ts-node ./examples/cluster.ts","ts-datatype":"ts-node ./examples/datatype.ts","ts-sync":"ts-node ./examples/syncTable.ts","test":"jest --coverage","coveralls":"jest --coverage --coverageReporters=text-lcov | coveralls"},"dependencies":{"clickhouse":"^2.6.0","colors":"^1.4.0"},"devDependencies":{"@types/jest":"^27.4.1","coveralls":"^3.1.1","dayjs":"^1.10.7","jest":"^27.4.1","jest-mock":"^27.5.1","ts-jest":"^27.1.3","ts-node":"^10.4.0","typescript":"^4.3.5"},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"03f52fa92e3784e540fba55787fde9d3e7857354","_id":"clickhouse-orm@3.0.2","_nodeVersion":"16.15.1","_npmVersion":"9.2.0","dist":{"integrity":"sha512-3bvbYxlN48CbZtuPKYizM3vjCVpnIF7Fd6L+/WzxbV09yNInN5zKYI6ipSEx5Jtq4GmF2vtMIuuH0VAfbZYOoA==","shasum":"7e66ed1906e17a09437dc07f09352e112cfadab2","tarball":"https://registry.npmjs.org/clickhouse-orm/-/clickhouse-orm-3.0.2.tgz","fileCount":26,"unpackedSize":72985,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIESG5+oIMAhQkoMHi6EBQoyZQiJkHm+tb1LvPtcxEMoiAiBpfQRaS4128ewCr45nkP09ieOqOUgi7IkGsn6Wjzml0w=="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJj0gZJACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmqjMg//SA3Ag7JLzNYqZ2WLEssq5OzSdtqPYFEeOUcDs8gtuj9PkYbe\r\nCwY8jKrYDHoMikJxB6Fvmr85u0pKx773HTAeXudlzDA8JauFtngw0fPye4ZU\r\nhn435LSZBNDQz02t6FtzqfKOGjrAVW8fHjJc9Sn9p9U4FvNjsMSwIzG8sfJ2\r\nKXaUpKWUep1Y2b9MTILFjw95dHJoPtF33OJyJvOlRCVaidisQwXri0DCHG3Z\r\nmYzJILsW+leo9m5O6G/8tHWPJkOXoirC9eeYQwIrkpTkjCe4zhJcwkbrZ8xM\r\nomXBjm2KBlgwu1rQ7Fih1UwGfEtuKxWypE5iqCTAj2Y6vMocPEoZ8f+X9P+T\r\nX9FqYB+YZUGkvT96KN5CpJVygA+n99xoJlrRLU5IDYsQ1I1r4z/jmXSo0lQj\r\n7U0KEsURpSXwC1RJlQ5rZc+pv2NoIM+mR6VT7Y1bwwo1Hf8SX3SQF7rdw+Hc\r\nKw/wpZeRbEZLG+LFwJCO1gNKrqPvw6kT+V3+AqRlk3M1Zlw2vB/oa/dgVIeM\r\nRsa9XD6mlafzlJ7c8Ni4B3xnDXZTIf9yxMa2OcFRVY38zLwzYO2hEUay8Tyh\r\nQB+qNvSvROxHi84RphkBdJTjVDBclWlA/FbvK2dChksIvVJlAxXqYxjvd9n4\r\nw8up3LWHnm/bAoqGyg6h6TkE90BeElOGqCY=\r\n=2Cg2\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"zimv","email":"472953586@qq.com"},"directories":{},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/clickhouse-orm_3.0.2_1674708553486_0.7151638748495421"},"_hasShrinkwrap":false}},"time":{"created":"2022-02-05T15:48:16.013Z","1.0.0":"2022-02-05T15:48:16.218Z","modified":"2023-01-26T04:49:13.769Z","1.0.1":"2022-02-10T12:24:34.811Z","2.0.0-alpha.0":"2022-02-21T10:23:44.330Z","2.0.0":"2022-02-24T02:40:27.998Z","2.0.1-alpha.0":"2022-10-10T12:08:18.986Z","2.0.1-alpha.1":"2022-10-10T12:08:44.234Z","2.0.1":"2022-10-12T08:38:29.246Z","2.0.2-beta":"2022-12-28T09:24:18.124Z","2.0.2":"2022-12-28T09:48:49.746Z","3.0.0-alpha":"2023-01-05T11:53:35.564Z","3.0.0-alpha2":"2023-01-05T12:03:41.819Z","3.0.0-alpha3":"2023-01-06T06:54:34.519Z","3.0.0-alpha4":"2023-01-06T07:56:04.009Z","3.0.0-alpha5":"2023-01-09T08:24:53.111Z","3.0.0":"2023-01-11T07:21:50.219Z","3.0.1":"2023-01-11T07:51:13.956Z","3.0.2-alpha1":"2023-01-26T04:30:07.961Z","3.0.2":"2023-01-26T04:49:13.679Z"},"maintainers":[{"name":"zimv","email":"472953586@qq.com"}],"description":"Clickhouse orm for Nodejs","homepage":"https://github.com/zimv/node-clickhouse-orm#readme","keywords":["zimv","clickhouse","orm"],"repository":{"type":"git","url":"git+https://github.com/zimv/node-clickhouse-orm.git"},"author":{"name":"zimv"},"bugs":{"url":"https://github.com/zimv/node-clickhouse-orm/issues"},"license":"MIT","readme":"[![Coverage Status](https://coveralls.io/repos/github/zimv/node-clickhouse-orm/badge.svg?branch=main)](https://coveralls.io/github/zimv/node-clickhouse-orm?branch=main)\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://img.shields.io/npm/v/clickhouse-orm.svg\"></a>\n<a href=\"https://npms.io/search?q=clickhouse-orm\" alt=\"NPM latest version\"><img src=\"https://badges.npms.io/clickhouse-orm.svg\"></a>\n<a href=\"https://www.npmjs.com/package/clickhouse-orm\" alt=\"NPM total downloads\"><img src=\"https://img.shields.io/npm/dt/clickhouse-orm.svg\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github stars\"><img src=\"https://img.shields.io/github/stars/zimv/node-clickhouse-orm.svg?style=social&label=Star\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github forks\"><img src=\"https://img.shields.io/github/forks/zimv/node-clickhouse-orm.svg?style=social&label=Fork\"></a>\n<a href=\"https://github.com/zimv/node-clickhouse-orm\" alt=\"Github contributors\"><img src=\"https://img.shields.io/github/contributors/zimv/node-clickhouse-orm.svg\"></a>\n\n# clickhouse-orm  [(中文 README)](https://github.com/zimv/node-clickhouse-orm/blob/main/README-zh.md)\n\n[![Join the chat at https://gitter.im/zimv/node-clickhouse-orm](https://badges.gitter.im/zimv/node-clickhouse-orm.svg)](https://gitter.im/zimv/node-clickhouse-orm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n\nClickhouse ORM for Nodejs. Send query over HTTP interface. Using [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n# Install:\n\n```\nnpm i clickhouse-orm\n```\n\n# Usage\n\n**Create instance：**\n\n```typescript\nconst { ClickhouseOrm } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_test\",\n  },\n  debug: true,\n  client: {\n    url: \"localhost\",\n    port: \"8123\",\n    basicAuth: {\n      username: \"default\",\n      password: \"\",\n    },\n    debug: false,\n    isUseGzip: true,\n    format: \"json\", // \"json\" || \"csv\" || \"tsv\"\n  },\n});\n```\n\n**Define Model：**\n```typescript\nimport { DATA_TYPE, ModelSyncTableConfig } from 'clickhouse-orm';\nconst table1Schema: ModelSyncTableConfig<{\n  status?: number;\n  time: Date;\n  browser?: string;\n  browser_v?: string;\n}> = {\n  tableName: \"table1\",\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.String },\n    browser_v: { type: DATA_TYPE.String },\n  },\n  options: `ENGINE = MergeTree\n  PARTITION BY toYYYYMM(time)\n  ORDER BY time`,\n  autoCreate: true,\n  autoSync: true,\n};\n```\n\n**Create data / Find：**\n\n```typescript\n// create database 'orm_test'\nawait chOrm.createDatabase();\n// register schema and create [if] table\nconst Table1Model = await chOrm.model(table1Schema);\n\n// create data\nconst resCreate = await Table1Model.create({\n  status: 1,\n  time: new Date(),\n  browser: \"chrome\",\n  browser_v: \"90.0.1.21\",\n});\nconsole.log(\"create:\", resCreate);\n\n// find\nTable1Model.find({\n  select: \"*\",\n  limit: 3,\n}).then((res) => {\n  // SQL: SELECT * from orm_test.table1 LIMIT 3\n  console.log(\"find:\", res);\n});\n```\n\n**More in [Basic Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/basic.js).**\n\n# Document\n\n`Note`: '?' is a Optional\n\n### ClickhouseOrm\n\n\n\n`db` : object<{name:string, engine?:string, cluster?:string}>\n\n> name: database name\n\n> engine?: database engine\n\n> cluster?: cluster name\n\n`debug` : boolean\n\n> Default: false\n\n`client` : object\n\n> Drive configuration. More in [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse).\n\n### Model config params\n**1. ModelConfig**\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type, default? } } | `Type` defines the data type, and `default` sets the default value |\n\n\n```typescript\nimport { DATA_TYPE, ModelConfig } from 'clickhouse-orm';\nconst xxxSchema: ModelConfig<{\n  status?: number;\n  time: Date;\n  browser?: string;\n  browser_v?: string;\n}> = {\n  // table name\n  tableName: \"xxx\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.LowCardinality(DATA_TYPE.String) },\n    browser_v: { type: DATA_TYPE.String  }\n  },\n};\n```\n----\n\n\n**2. ModelSyncTableConfig** (Recommended)\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type, default? } } | `Type` defines the data type, and `default` sets the default value |\n| options | true | string | Create table setting |\n| autoCreate | true | boolean | Auto create table |\n| autoSync | false | boolean | Auto sync table structure`(Careful use)` |\n \n\nAutomatically create tables and automatically synchronize table field structures\n\n```typescript\nimport { DATA_TYPE, ModelSyncTableConfig } from 'clickhouse-orm';\nconst oldSchema: ModelSyncTableConfig<{\n    time: Date;\n    will_typeChanged?: number;\n    will_deleted?: string;\n  }> = {\n  tableName: \"xxx\",\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    will_typeChanged: { type: DATA_TYPE.Int16 },\n    will_deleted: { type: DATA_TYPE.String },\n  },\n  options: `ENGINE = MergeTree\n  PARTITION BY toYYYYMM(time)\n  ORDER BY time`,\n  autoCreate: true,\n  autoSync: true,\n};\n```\nSynchronize the table structure (just the field columns) when creating the model. When the model is created, the field structure of the remote database table will be pulled for comparison with the schema in the current code. Finally, the ORM will automatically execute (add, delete, and modify) statements.\n\n\n```typescript\nconst newSchema = {\n  ...oldSchema,\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    will_typeChanged: { type: DATA_TYPE.Int32 },\n    add_column: { type: DATA_TYPE.String },\n  }\n}\nchOrm.model(newSchema)\n```\n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  DROP COLUMN will_deleted \n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  ADD COLUMN add_column String \n\n> clickhouse-orm-log: sync table structure: ALTER TABLE orm_test.xxx  MODIFY COLUMN will_typeChanged Int32\n\nUnrecognized field name modification! The following configuration will delete **column1** and add **column2**.\n\n```typescript\noldSchema = {\n  column1: { type: DATA_TYPE.String },\n}\nnewSchema = {\n  column2: { type: DATA_TYPE.String },\n}\n```\n\n**More in [SyncTable Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/syncTable.ts).**\n\n----\n**3. ModelSqlCreateTableConfig**\n\n|  | required | type | description |\n| ------ | ------ | ------ | ------ |\n| tableName | true | string | It is the table name. |\n| schema | true | { [column]: { type, default? } } | `Type` defines the data type, and `default` sets the default value |\n| createTable | true | string | It is the SQL for creating tables.When model is executed, this SQL will be executed. It is suggested to add 'IF NOT EXISTS'. <br> Watch out !!! >>>>> If the table already exists and you want to modify it. You need to execute the modification sql through other clients（Such as Remote terminal） and update the code of the Schema!!!|\n\n\nCustomized table creation statement, and the table will be created automatically when the model is created\n\n```typescript\nimport { DATA_TYPE, ModelSqlCreateTableConfig } from 'clickhouse-orm';\nconst xxxSchema: ModelSqlCreateTableConfig<{\n    status?: number;\n    time: Date;\n    browser?: string;\n    browser_v?: string;\n  }> = {\n  // table name\n  tableName: \"xxx\",\n  // define column name\n  schema: {\n    time: { type: DATA_TYPE.DateTime, default: Date },\n    status: { type: DATA_TYPE.Int32 },\n    browser: { type: DATA_TYPE.LowCardinality(DATA_TYPE.String) },\n    browser_v: { type: DATA_TYPE.String  }\n  },\n  // create table sql\n  createTable: (dbTableName) => {\n    // dbTableName = db + '.' + tableName = (orm_test.table1)\n    return `\n      CREATE TABLE IF NOT EXISTS ${dbTableName}\n      (\n        time DateTime,\n        status Int32,\n        browser LowCardinality(String),\n        browser_v String\n      )\n      ENGINE = MergeTree\n      PARTITION BY toYYYYMM(time)\n      ORDER BY time`;\n  },\n};\n```\n\n### DATA_TYPE\n\nClickHouse data type. Most of the following data will be validated by ORM, but only the basic data type `number | string | boolean | date` will be validated, not the most standard data type. For example, in `Int8`, ORM only verifies the `number` type.\n\n\n```typescript\n  UInt8;\n  UInt16;\n  UInt32;\n  UInt64;\n  Int8;\n  Int16;\n  Int32;\n  Int64;\n  Float32;\n  Float64;\n  Boolean;\n  String;\n  UUID;\n  Date;\n  Date32;\n  DateTime;\n  DateTime64;\n  /**\n   *\n   * @param Number\n   * @example DATA_TYPE.FixedString(3)\n   */\n  FixedString;\n  /**\n   *\n   * @param DATA_TYPE\n   * @example DATA_TYPE.LowCardinality(DATA_TYPE.String)\n   */\n  LowCardinality;\n  /**\n   *\n   * @param string\n   * @example DATA_TYPE.Enum8(`'hello' = 1, 'world' = 2`)\n   * @desc number [-128, 127]\n   */\n  Enum8;\n  /**\n   *\n   * @param string\n   * @example DATA_TYPE.Enum16(`'hello' = 3000, 'world' = 3500`)\n   * @desc number [-32768, 32767]\n   */\n  Enum16;\n  /**\n   *\n   * @param columnType\n   * Clickhouse dataTypes: Array(T), JSON, Map(key, value), IPv4, Nullable(), more...\n   * @example DATA_TYPE.Other('Array(String)') , DATA_TYPE.Other('Int8')\n   * @desc No `INSERT` data validation provided\n   */\n  Other;\n```\n**More in [Datatype Example](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/datatype.ts).**\n### Log\n\nThe **setLogService** is a global configuration method and will affect all instances.\n\n`Default: console.log`\n\nCustom example: **[winston](https://github.com/winstonjs/winston)**\n\n```javascript\nconst { setLogService } = require(\"clickhouse-orm\");\nconst winston = require(\"winston\");\nconst logger = winston.createLogger();\n\nsetLogService(logger.info);\n```\n\n### Use SQL directly：\n\n```javascript\nchOrm.client\n  .query(`select * from orm_test.table1 limit 3`)\n  .toPromise()\n  .then((res) => {\n    console.log(\"Use sql:\", res);\n  });\n```\n\nThe `chOrm.client` is the [TimonKK/clickhouse](https://github.com/TimonKK/clickhouse) instance.\n\n# [More Examples](https://github.com/zimv/node-clickhouse-orm/blob/main/examples/more.ts)\n\n### Find\n\n```javascript\nimport * as dayjs from \"dayjs\";\n\nqueryExample1({\n  Model: Table1Model,\n  status: 1,\n  beginTime: dayjs().subtract(1, \"day\").format(\"YYYY-MM-DD HH:mm:ss\"),\n  endTime: dayjs().format(\"YYYY-MM-DD HH:mm:ss\"),\n}).then((res) => {\n  console.log(\"queryExample1:\", res);\n});\n\nconst queryExample1 = ({ Model, status, beginTime, endTime }) => {\n  let wheres = [],\n    where;\n  if (status) wheres.push(`status='${status}'`);\n  if (beginTime) wheres.push(`time>='${beginTime}'`);\n  if (endTime) wheres.push(`time<='${endTime}'`);\n  if (wheres.length > 0) where = wheres.join(\" and \");\n\n  return Model.find({\n    where,\n    select: `*`,\n    orderBy: \"time ASC\",\n    limit: 5,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT * from orm_test.table1 where status='1' and time>='2022-02-04 15:34:22' and time<='2022-02-05 15:34:22'  ORDER BY time ASC LIMIT 5\n```\n\n### Count\n\n```javascript\ncountExample1({\n  Model: Table1Model,\n}).then((res) => {\n  console.log(\"countExample1:\", res);\n});\n\nconst countExample1 = ({ Model }) => {\n  return Model.find({\n    select: `count(*) AS total`,\n  });\n};\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count(*) AS total from orm_test.table1\n```\n\n### GroupBy\n\n```javascript\nTable1Model.find({\n  select: `status,browser`,\n  groupBy: \"status,browser\",\n});\n```\n\nFinal executed SQL:\n\n```sql\nSELECT status,browser from orm_test.table1  GROUP BY status,browser\n```\n\n### Nested Queries\n\n```javascript\nTable1Model.find([\n  {\n    select: `browser`,\n    groupBy: \"browser\",\n  },\n  {\n    select: `count() as browserTotal`,\n  },\n]);\n```\n\nFinal executed SQL:\n\n```sql\nSELECT count() as browserTotal from (SELECT browser from orm_test.table1  GROUP BY browser  )\n```\n\n### save\n\n```javascript\n// new data model\nconst data = Table1Model.build();\n\n// set value\ndata.time = new _Date_();\ndata.status = 1;\ndata.browser = \"chrome\";\ndata.browser_v = \"90.0.1.21\";\n\n// do save\ndata.save().then((res) => {\n  console.log(\"save:\", res);\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### create\n\n```javascript\n//do create\nawait Table1Model.create({\n  status: 1,\n  time: new Date(),\n  browser: \"chrome\",\n  browser_v: \"90.0.1.21\",\n});\n```\n\nFinal executed SQL:\n\n```\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:51:16.919Z\",\"status\":1,\"browser\":\"chrome\",\"browser_v\":\"90.0.1.21\"}]\\\n```\n\n### InsertMany\n\n```javascript\nconst list = [\n  { status: 2, browser: \"IE\", browser_v: \"10.0.1.21\" },\n  { status: 2, browser: \"FF\", browser_v: \"2.0.3\" },\n  { status: 3, browser: \"IE\", browser_v: \"1.1.1\" },\n];\n\nTable1Model.insertMany(list);\n// or\nTable1Model.insertMany(\n  list.map((item) => {\n    const data = Table1Model.build();\n    // set value\n    data.time = new Date();\n    data.status = item.status;\n    data.browser = item.browser;\n    data.browser_v = item.browser_v;\n    return data;\n  })\n);\n```\n\nFinal executed SQL:\n\n```sql\nINSERT INTO orm_test.table1 (time,status,browser,browser_v) [{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"IE\",\"browser_v\":\"10.0.1.21\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":2,\"browser\":\"FF\",\"browser_v\":\"2.0.3\"},{\"time\":\"2022-02-05T07:34:22.226Z\",\"status\":3,\"browser\":\"IE\",\"browser_v\":\"1.1.1\"}]\n```\n\n### delete\n\n```javascript\n\nTable1Model.delete({\n  where: `browser='Chrome'`,\n})\n```\n\nFinal executed SQL:\n\n```sql\nALTER TABLE orm_test.table1  DELETE  WHERE browser='Chrome'\n```\n\n## cluster\n\n**Create a cluster instance：**\n\n```javascript\nconst { ClickhouseOrm, DATA_TYPE, setLogService } = require(\"clickhouse-orm\");\n\nconst chOrm = ClickhouseOrm({\n  db: {\n    name: \"orm_cluster_test\",\n    cluster: \"default_cluster\",\n  },\n  // ...other\n});\nconst table2Schema = {\n  // table name\n  tableName: \"table2\",\n  ...other,\n};\n\n// create database 'orm_cluster_test'\n// SQL: CREATE DATABASE IF NOT EXISTS orm_cluster_test ON CLUSTER default_cluster\nawait chOrm.createDatabase();\n\n// register schema and create [if] table\n// createTable() SQL: CREATE TABLE IF NOT EXISTS orm_cluster_test.table2 ON CLUSTER default_cluster...\nconst Table2Model = await chOrm.model(table2Schema);\n```\n\n# Wechat Discussion\n\n[Click to join](https://github.com/zimv/node-clickhouse-orm/issues/3)\n\n##### or\n\n[![Join the chat at https://gitter.im/zimv/node-clickhouse-orm](https://badges.gitter.im/zimv/node-clickhouse-orm.svg)](https://gitter.im/zimv/node-clickhouse-orm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)","readmeFilename":"README.md"}