apla / node-clickhouse

Yandex ClickHouse driver for nodejs
MIT License
217 stars 50 forks source link

How to insert type 'Date'? #46

Open Sir-Will opened 4 years ago

Sir-Will commented 4 years ago

hey,

I'm trying to insert the clickhouse type Date from js Date(). I tried new Date().toISOString().substr(0,10) which worked fine but reading it causes it to return a String.

What's the proper way of doing this?

nezed commented 4 years ago

For INSERTs done with JSONEachRow and writing JS objects to stream (like here) you can pass Date instance as a column value.

For now with SELECTs you will always get Date and DateTime values as strings, and forced to parse them by yourself.

suenot commented 4 years ago

You can use moment library:

const ClickHouse = require('@apla/clickhouse')
const moment = require('moment')
const options = <OPTIONS>
const ch = new ClickHouse(options)

const writableStream = ch.query('INSERT INTO testdb.testtable', { format: 'JSONEachRow' }, (err) => {
    console.log(err)
    console.log('Clickhouse insert!')
})
writableStream.write({
    'name': 'Foo',
    'timestamp': new Date(),
    'date': moment.utc(new Date()).format('YYYY-MM-DD'),
    'datetime': moment.utc(new Date()).format('YYYY-MM-DD HH:mm:ss'),
})
writableStream.write({
    'name': 'Bar',
    'timestamp': new Date(),
    'date': moment.utc(new Date()).format('YYYY-MM-DD'),
    'datetime': moment.utc(new Date()).format('YYYY-MM-DD HH:mm:ss'),
})
writableStream.end()