Mathe Eliel
Mathe Eliel

Reputation: 738

How do I convert a PostgreSQL timestamp to String?

I am getting this error when I try to retreive data from a database:

thread 'main' panicked at 'error retrieving column 2: error deserializing column 2: cannot convert between the Rust type `alloc::string::String` and the Postgres type `timestamp`'

Db structure:

CREATE TABLE IF NOT EXISTS table_(
            id SERIAL PRIMARY KEY,
            data VARCHAR NOT NULL,
            date_saved TIMESTAMP
        )
struct MyType{
    local_id: i32,
    data: String,
    date_saved: String
}

let records = client.query("SELECT id,data,date_saved FROM table_",&[])?;
let mut the_records : Vec<MyType> = vec![];
for record in records {
    let saved_data = MyType {
        local_id: record.get(0),
        data: record.get(1),
        date_saved: record.get(2),
    };
    println!("{:?}",saved_data.data);
    the_records.push(saved_data);
}

Upvotes: 4

Views: 2875

Answers (2)

Robins Tharakan
Robins Tharakan

Reputation: 2483

The above answer is good, but if you want a quicker solution (for e.g. want to just print to screen / log etc.), just cast the Timestamp to a TEXT within Postgres and then rust wouldn't complain.

So for e.g. this would throw ERROR:

SELECT now(); -- Will throw error

But this wouldn't

SELECT now()::TEXT; -- Will work fine

Upvotes: 1

Mathe Eliel
Mathe Eliel

Reputation: 738

I found out that there is no possible conversion between Postgres Timestamp and String according to https://docs.rs/postgres/0.17.5/postgres/types/trait.FromSql.html but we need to use std::time::SystemTime.

So MyType will be:

struct MyType{
    local_id: i32,
    data: String,
    date_saved: std::time::SystemTime
}

And I can manipulate time from there.

Upvotes: 2

Related Questions