pub fn copy_to<T>(target: T) -> CopyToQuery<T, NotSet>where
T: CopyTarget,
Expand description
Creates a COPY TO
statement
This function constructs a COPY TO
statement which copies data
from the database to a client side target. It’s designed to move
larger amounts of data out of the database.
This function accepts a target selection (table name or list of columns) as argument.
There are two ways to use a COPY TO
statement with diesel:
- By using
CopyToQuery::load
directly to load the deserialized result directly into a specified type - By using the
with_*
methods to configure the format sent by the database and then by callingCopyToQuery::load_raw
to receive the raw data sent by the database.
The first variant uses the BINARY
format internally to receive
the selected data efficiently. It automatically sets the right options
and does not allow to change them via with_*
methods.
The second variant allows you to control the behaviour of the
generated COPY TO
statement in detail. You can use the various
with_*
methods for that before issuing the statement via CopyToQuery::load_raw
.
That method will return an type that implements std::io::BufRead
, which
allows you to directly read the response from the database in the configured
format.
See the postgresql documentation
for more details about the supported formats.
If you don’t have any specific needs you should prefer using the more convenient first variant.
This functionality is postgresql specific.
§Examples
§Via CopyToQuery::load()
#[derive(Queryable, Selectable, PartialEq, Debug)]
#[diesel(table_name = users)]
#[diesel(check_for_backend(diesel::pg::Pg))]
struct User {
name: String,
}
let out = diesel::copy_to(users::table)
.load::<User, _>(connection)?
.collect::<Result<Vec<_>, _>>()?;
assert_eq!(out, vec![User{ name: "Sean".into() }, User{ name: "Tess".into() }]);
§Via CopyToQuery::load_raw()
use diesel::pg::CopyFormat;
use std::io::Read;
let mut copy = diesel::copy_to(users::table)
.with_format(CopyFormat::Csv)
.load_raw(connection)?;
let mut out = String::new();
copy.read_to_string(&mut out).unwrap();
assert_eq!(out, "1,Sean\n2,Tess\n");