简体   繁体   中英

PostgreSQL returning NULL as a row in case query returns empty

I have a generic code which is trying to access field values after query returns.

SELECT 
    ROUND(AVG(EXTRACT(EPOCH FROM (time::timestamp)))) as extended_time
FROM log_info 
WHERE 
    id = 1 AND 
    code = 200;

However, this is returning NULL value as single row which is causing my application to crash.

for row in &con.query(query, args.as_slice()).unwrap() {
    let extended_time: i32 = row.get("extended_time");
    ...
}

crashes with following error :-

error retrieving column "extended_time": Conversion(WasNull)

Running manually returns

 extended_time
-------------

(1 row)

Without AVG query returns expected result

SELECT 
    EXTRACT(EPOCH FROM (time::timestamp)) as extended_time
FROM log_info 
WHERE 
    id = 1 AND 
    code = 200;

 extended_time
-------------
(0 rows)

An i32 can't be empty. You should use an Option as your query can return NULL :

let extended_time: Option<i32> = row.get("extended_time");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM