mz_postgres_util/
query.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use tokio_postgres::{Client, SimpleQueryMessage, SimpleQueryRow};
11
12use crate::PostgresError;
13
14/// Runs the given query using the client and expects at most a single row to be returned.
15pub async fn simple_query_opt(
16    client: &Client,
17    query: &str,
18) -> Result<Option<SimpleQueryRow>, PostgresError> {
19    let result = client.simple_query(query).await?;
20    let mut rows = result.into_iter().filter_map(|msg| match msg {
21        SimpleQueryMessage::Row(row) => Some(row),
22        _ => None,
23    });
24    match (rows.next(), rows.next()) {
25        (Some(row), None) => Ok(Some(row)),
26        (None, None) => Ok(None),
27        _ => Err(PostgresError::UnexpectedRow),
28    }
29}