pub fn copy_from<T>(table: T) -> CopyFromQuery<T, NotSet>where
T: Table,
Expand description
Creates a COPY FROM
statement
This function constructs COPY FROM
statement which copies data
from a source into the database. It’s designed to move larger
amounts of data into the database.
This function accepts a target table as argument.
There are two ways to construct a COPY FROM
statement with
diesel:
- By providing a
Vec<I>
whereI
implementsInsertable
for the given table - By providing a target selection (column list or table name) and a callback that provides the data
The first variant uses the BINARY
format internally to send
the provided data efficiently to the database. It automatically
sets the right options and does not allow changing them.
Use CopyFromQuery::from_insertable
for this.
The second variant allows you to control the behaviour
of the generated COPY FROM
statement in detail. It can
be setup via the CopyFromQuery::from_raw_data
function.
The callback accepts an opaque object as argument that allows
to write the corresponding data to the database. The exact
format depends on the settings chosen by the various
CopyFromQuery::with_*
methods. See
the postgresql documentation
for more details about the expected 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 CopyFromQuery::from_insertable
#[derive(Insertable)]
#[diesel(table_name = users)]
#[diesel(treat_none_as_default_value = false)]
struct NewUser {
name: &'static str,
}
let data = vec![
NewUser { name: "Diva Plavalaguna" },
NewUser { name: "Father Vito Cornelius" },
];
let count = diesel::copy_from(users::table)
.from_insertable(&data)
.execute(connection)?;
assert_eq!(count, 2);
§Via CopyFromQuery::from_raw_data
use diesel::pg::CopyFormat;
let count = diesel::copy_from(users::table)
.from_raw_data(users::table, |copy| {
writeln!(copy, "3,Diva Plavalaguna").unwrap();
writeln!(copy, "4,Father Vito Cornelius").unwrap();
diesel::QueryResult::Ok(())
})
.with_format(CopyFormat::Csv)
.execute(connection)?;
assert_eq!(count, 2);