suharev7 / clickhouse-rs

Asynchronous ClickHouse client library for Rust programming language.
MIT License
324 stars 121 forks source link

How to use clickhouse rs to add datetime32 data? #182

Open trollhe opened 2 years ago

trollhe commented 2 years ago

table :

drop table if exists tmp.tmp_demo;
CREATE TABLE if not exists tmp.tmp_demo
(
    `p_time` DateTime
)
ENGINE = MergeTree
PARTITION BY p_time
ORDER BY p_time
TTL p_time + toIntervalHour(1)
SETTINGS index_granularity = 8192;

codes:

use std::{env, error::Error};
use clickhouse_rs::{row, types::Block, Pool};
use futures_util::StreamExt;
use clickhouse_rs::types::DateTimeType;

#[cfg(all(feature = "tokio_io"))]
#[tokio::main]
async fn main()-> Result<(), Box<dyn Error>>{
    // table name
    let table_name:&str = "tmp.tmp_demo";

    // clickhouse url
    let ch_url: &str = "tcp://default:abc123@localhost:9000/tmp?compression=lz4&ping_timeout=42ms";

    // get client
    let pool = Pool::new(ch_url);
    let mut client = pool.get_handle().await?;

    // assembly data
    let block = Block::new()
     .column("p_time",  vec![1667210027_u32,1667210027_u32]);

    // insert data
    client.insert(table_name, block).await?;
    Ok(())

}

error logs:

Error: FromSql(InvalidType { src: "UInt32", dst: "DateTime" })
prk3 commented 1 year ago

You can't insert integer timestampts into a column of type DateTime. Convert timestamps into chrono::DateTime objects first, like this:

use chrono_tz::Tz::UTC;

let block = Block::new().column(
    "p_time",
    vec![
        UTC.timestamp_opt(1667210027_i64, 0).unwrap(),
        UTC.timestamp_opt(1667210027_i64, 0).unwrap(),
    ],
);