Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add parameter and column formatting to query_raw()#747

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletionspostgres-types/src/lib.rs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -190,6 +190,7 @@ where
if !T::accepts(ty) {
return Err(Box::new(WrongType::new::<T>(ty.clone())));
}

v.to_sql(ty, out)
}

Expand DownExpand Up@@ -741,11 +742,11 @@ pub enum IsNull {
/// an index offset of 1. **Note:** the impl for arrays only exist when the
/// Cargo feature `array-impls` is enabled.
pub trait ToSql: fmt::Debug {
/// Converts the value of `self` into thebinary format of the specified
/// Converts the value of `self` into the`Format` of the specified
/// Postgres `Type`, appending it to `out`.
///
/// The caller of this method is responsible for ensuring that this type
/// is compatible with the Postgres `Type`.
/// is compatible with the Postgres `Type` and `Format`.
///
/// The return value indicates if this value should be represented as
/// `NULL`. If this is the case, implementations **must not** write
Expand All@@ -771,6 +772,33 @@ pub trait ToSql: fmt::Debug {
) -> Result<IsNull, Box<dyn Error + Sync + Send>>;
}

/// Supported Postgres message format types
///
/// Using Text format in a message assumes a Postgres `SERVER_ENCODING` of `UTF8`
#[derive(Copy, Clone, Debug)]
pub enum Format {
/// Text format (UTF-8)
Text,
/// Compact, typed binary format
Binary,
}

/// Convert from `Format` to the Postgres integer representation of those formats
impl From<&Format> for i16 {
fn from(format: &Format) -> Self {
match format {
Format::Text => 0,
Format::Binary => 1,
}
}
}

impl From<Format> for i16 {
fn from(format: Format) -> Self {
Self::from(&format)
}
}

impl<'a, T> ToSql for &'a T
where
T: ToSql,
Expand Down
33 changes: 26 additions & 7 deletionspostgres/src/client.rs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,7 +6,7 @@ use crate::{
use std::task::Poll;
use std::time::Duration;
use tokio_postgres::tls::{MakeTlsConnect, TlsConnect};
use tokio_postgres::types::{BorrowToSql, ToSql, Type};
use tokio_postgres::types::{BorrowToSql,Format,ToSql, Type};
use tokio_postgres::{Error, Row, SimpleQueryMessage, Socket};

/// A synchronous PostgreSQL client.
Expand DownExpand Up@@ -221,14 +221,20 @@ impl Client {
///
/// ```no_run
/// use postgres::{Client, NoTls};
/// use postgres::types::Format;
/// use fallible_iterator::FallibleIterator;
/// use std::iter;
///
/// # fn main() -> Result<(), postgres::Error> {
/// let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
///
/// let baz = true;
/// let mut it = client.query_raw("SELECT foo FROM bar WHERE baz = $1", iter::once(baz))?;
/// let mut it = client.query_raw(
/// "SELECT foo FROM bar WHERE baz = $1",
/// iter::once(baz),
/// Some(Format::Binary),
/// Some(Format::Binary),
/// )?;
///
/// while let Some(row) = it.next()? {
/// let foo: i32 = row.get("foo");
Expand All@@ -243,7 +249,7 @@ impl Client {
///
/// ```no_run
/// # use postgres::{Client, NoTls};
/// use postgres::types::ToSql;
/// use postgres::types::{ToSql, Format};
/// use fallible_iterator::FallibleIterator;
/// # fn main() -> Result<(), postgres::Error> {
/// # let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
Expand All@@ -255,6 +261,8 @@ impl Client {
/// let mut it = client.query_raw(
/// "SELECT foo FROM bar WHERE biz = $1 AND baz = $2",
/// params,
/// Some(Format::Text),
/// Some(Format::Binary),
/// )?;
///
/// while let Some(row) = it.next()? {
Expand All@@ -264,16 +272,27 @@ impl Client {
/// # Ok(())
/// # }
/// ```
pub fn query_raw<T, P, I>(&mut self, query: &T, params: I) -> Result<RowIter<'_>, Error>
pub fn query_raw<T, P, I, J, K>(
&mut self,
query: &T,
params: I,
param_formats: J,
column_formats: K,
) -> Result<RowIter<'_>, Error>
where
T: ?Sized + ToStatement,
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
J: IntoIterator<Item = Format>,
K: IntoIterator<Item = Format>,
{
let stream = self
.connection
.block_on(self.client.query_raw(query, params))?;
let stream = self.connection.block_on(self.client.query_raw(
query,
params,
param_formats,
column_formats,
))?;
Ok(RowIter::new(self.connection.as_ref(), stream))
}

Expand Down
38 changes: 31 additions & 7 deletionspostgres/src/generic_client.rs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
use crate::types::{BorrowToSql, ToSql, Type};
use crate::types::{BorrowToSql,Format,ToSql, Type};
use crate::{
Client, CopyInWriter, CopyOutReader, Error, Row, RowIter, SimpleQueryMessage, Statement,
ToStatement, Transaction,
Expand DownExpand Up@@ -37,12 +37,20 @@ pub trait GenericClient: private::Sealed {
T: ?Sized + ToStatement;

/// Like `Client::query_raw`.
fn query_raw<T, P, I>(&mut self, query: &T, params: I) -> Result<RowIter<'_>, Error>
fn query_raw<T, P, I, J, K>(
&mut self,
query: &T,
params: I,
param_formats: J,
column_formats: K,
) -> Result<RowIter<'_>, Error>
where
T: ?Sized + ToStatement,
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator;
I::IntoIter: ExactSizeIterator,
J: IntoIterator<Item = Format>,
K: IntoIterator<Item = Format>;

/// Like `Client::prepare`.
fn prepare(&mut self, query: &str) -> Result<Statement, Error>;
Expand DownExpand Up@@ -105,14 +113,22 @@ impl GenericClient for Client {
self.query_opt(query, params)
}

fn query_raw<T, P, I>(&mut self, query: &T, params: I) -> Result<RowIter<'_>, Error>
fn query_raw<T, P, I, J, K>(
&mut self,
query: &T,
params: I,
param_formats: J,
column_formats: K,
) -> Result<RowIter<'_>, Error>
where
T: ?Sized + ToStatement,
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
J: IntoIterator<Item = Format>,
K: IntoIterator<Item = Format>,
{
self.query_raw(query, params)
self.query_raw(query, params, param_formats, column_formats)
}

fn prepare(&mut self, query: &str) -> Result<Statement, Error> {
Expand DownExpand Up@@ -185,14 +201,22 @@ impl GenericClient for Transaction<'_> {
self.query_opt(query, params)
}

fn query_raw<T, P, I>(&mut self, query: &T, params: I) -> Result<RowIter<'_>, Error>
fn query_raw<T, P, I, J, K>(
&mut self,
query: &T,
params: I,
param_formats: J,
column_formats: K,
) -> Result<RowIter<'_>, Error>
where
T: ?Sized + ToStatement,
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
J: IntoIterator<Item = Format>,
K: IntoIterator<Item = Format>,
{
self.query_raw(query, params)
self.query_raw(query, params, param_formats, column_formats)
}

fn prepare(&mut self, query: &str) -> Result<Statement, Error> {
Expand Down
19 changes: 16 additions & 3 deletionspostgres/src/transaction.rs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
use crate::connection::ConnectionRef;
use crate::{CancelToken, CopyInWriter, CopyOutReader, Portal, RowIter, Statement, ToStatement};
use tokio_postgres::types::{BorrowToSql, ToSql, Type};
use tokio_postgres::types::{BorrowToSql,Format,ToSql, Type};
use tokio_postgres::{Error, Row, SimpleQueryMessage};

/// A representation of a PostgreSQL database transaction.
Expand DownExpand Up@@ -102,16 +102,29 @@ impl<'a> Transaction<'a> {
}

/// Like `Client::query_raw`.
pub fn query_raw<T, P, I>(&mut self, query: &T, params: I) -> Result<RowIter<'_>, Error>
pub fn query_raw<T, P, I, J, K>(
&mut self,
query: &T,
params: I,
param_formats: J,
column_formats: K,
) -> Result<RowIter<'_>, Error>
where
T: ?Sized + ToStatement,
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
J: IntoIterator<Item = Format>,
K: IntoIterator<Item = Format>,
{
let stream = self
.connection
.block_on(self.transaction.as_ref().unwrap().query_raw(query, params))?;
.block_on(self.transaction.as_ref().unwrap().query_raw(
query,
params,
param_formats,
column_formats,
))?;
Ok(RowIter::new(self.connection.as_ref(), stream))
}

Expand Down
17 changes: 14 additions & 3 deletionstokio-postgres/src/bind.rs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
use crate::client::InnerClient;
use crate::codec::FrontendMessage;
use crate::connection::RequestMessages;
use crate::types::BorrowToSql;
use crate::types::{BorrowToSql, Format};
use crate::{query, Error, Portal, Statement};
use postgres_protocol::message::backend::Message;
use postgres_protocol::message::frontend;
Expand All@@ -10,19 +10,30 @@ use std::sync::Arc;

static NEXT_ID: AtomicUsize = AtomicUsize::new(0);

pub async fn bind<P, I>(
pub async fn bind<P, I, J, K>(
client: &Arc<InnerClient>,
statement: Statement,
params: I,
param_formats: J,
column_formats: K,
) -> Result<Portal, Error>
where
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
J: IntoIterator<Item = Format>,
K: IntoIterator<Item = Format>,
{
let name = format!("p{}", NEXT_ID.fetch_add(1, Ordering::SeqCst));
let buf = client.with_buf(|buf| {
query::encode_bind(&statement, params, &name, buf)?;
query::encode_bind(
&statement,
params,
param_formats,
column_formats,
&name,
buf,
)?;
frontend::sync(buf);
Ok(buf.split().freeze())
})?;
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp