Debian Codegraph @

src/pg/query_builder/copy/copy_from.rs

raw
1 use std::borrow::Cow;
2 use std::marker::PhantomData;
3
4 use byteorder::NetworkEndian;
5 use byteorder::WriteBytesExt;
6
7 use super::CommonOptions;
8 use super::CopyFormat;
9 use super::CopyTarget;
10 use crate::expression::bound::Bound;
11 use crate::insertable::ColumnInsertValue;
12 use crate::pg::backend::FailedToLookupTypeError;
13 use crate::pg::metadata_lookup::PgMetadataCacheKey;
14 use crate::pg::Pg;
15 use crate::pg::PgMetadataLookup;
16 use crate::query_builder::BatchInsert;
17 use crate::query_builder::QueryFragment;
18 use crate::query_builder::QueryId;
19 use crate::query_builder::ValuesClause;
20 use crate::serialize::IsNull;
21 use crate::serialize::ToSql;
22 use crate::Connection;
23 use crate::Insertable;
24 use crate::QueryResult;
25 use crate::{Column, Table};
26
27 /// Describes the different possible settings for the `HEADER` option
28 /// for `COPY FROM` statements
29 #[derive(Debug, Copy, Clone)]
30 pub enum CopyHeader {
31 /// Is the header set?
32 Set(bool),
33 /// Match the header with the targeted table names
34 /// and fail in the case of a mismatch
35 Match,
36 }
37
38 #[derive(Debug, Default)]
39 pub struct CopyFromOptions {
40 common: CommonOptions,
41 default: Option<String>,
42 header: Option<CopyHeader>,
43 }
44
45 impl QueryFragment<Pg> for CopyFromOptions {
46 fn walk_ast<'b>(
47 &'b self,
48 mut pass: crate::query_builder::AstPass<'_, 'b, Pg>,
49 ) -> crate::QueryResult<()> {
50 if self.any_set() {
51 let mut comma = "";
52 pass.push_sql(" WITH (");
53 self.common.walk_ast(pass.reborrow(), &mut comma);
54 if let Some(ref default) = self.default {
55 pass.push_sql(comma);
56 comma = ", ";
57 pass.push_sql("DEFAULT '");
58 // we cannot use binds here
59 // so we need to make sure quotes in
60 // the input are handled correctly
61 let default = default.replace('\'', "''");
62 pass.push_sql(&default);
63 pass.push_sql("'");
64 }
65 if let Some(ref header) = self.header {
66 pass.push_sql(comma);
67 // commented out because rustc complains otherwise
68 //comma = ", ";
69 pass.push_sql("HEADER ");
70 match header {
71 CopyHeader::Set(true) => pass.push_sql("1"),
72 CopyHeader::Set(false) => pass.push_sql("0"),
73 CopyHeader::Match => pass.push_sql("MATCH"),
74 }
75 }
76
77 pass.push_sql(")");
78 }
79 Ok(())
80 }
81 }
82
83 impl CopyFromOptions {
84 fn any_set(&self) -> bool {
85 self.common.any_set() || self.default.is_some() || self.header.is_some()
86 }
87 }
88
89 #[derive(Debug)]
90 pub struct CopyFrom<S, F> {
91 options: CopyFromOptions,
92 copy_callback: F,
93 p: PhantomData<S>,
94 }
95
96 pub(crate) struct InternalCopyFromQuery<S, T> {
97 pub(crate) target: S,
98 p: PhantomData<T>,
99 }
100
101 #[cfg(feature = "postgres")]
102 impl<S, T> InternalCopyFromQuery<S, T> {
103 pub(crate) fn new(target: S) -> Self {
104 Self {
105 target,
106 p: PhantomData,
107 }
108 }
109 }
110
111 impl<S, T> QueryId for InternalCopyFromQuery<S, T>
112 where
113 S: CopyFromExpression<T>,
114 {
115 const HAS_STATIC_QUERY_ID: bool = false;
116 type QueryId = ();
117 }
118
119 impl<S, T> QueryFragment<Pg> for InternalCopyFromQuery<S, T>
120 where
121 S: CopyFromExpression<T>,
122 {
123 fn walk_ast<'b>(
124 &'b self,
125 mut pass: crate::query_builder::AstPass<'_, 'b, Pg>,
126 ) -> crate::QueryResult<()> {
127 pass.unsafe_to_cache_prepared();
128 pass.push_sql("COPY ");
129 self.target.walk_target(pass.reborrow())?;
130 pass.push_sql(" FROM STDIN");
131 self.target.options().walk_ast(pass.reborrow())?;
132 Ok(())
133 }
134 }
135
136 pub trait CopyFromExpression<T> {
137 type Error: From<crate::result::Error> + std::error::Error;
138
139 fn callback(&mut self, copy: &mut impl std::io::Write) -> Result<(), Self::Error>;
140
141 fn walk_target<'b>(
142 &'b self,
143 pass: crate::query_builder::AstPass<'_, 'b, Pg>,
144 ) -> crate::QueryResult<()>;
145
146 fn options(&self) -> &CopyFromOptions;
147 }
148
149 impl<S, F, E> CopyFromExpression<S::Table> for CopyFrom<S, F>
150 where
151 E: From<crate::result::Error> + std::error::Error,
152 S: CopyTarget,
153 F: Fn(&mut dyn std::io::Write) -> Result<(), E>,
154 {
155 type Error = E;
156
157 fn callback(&mut self, copy: &mut impl std::io::Write) -> Result<(), Self::Error> {
158 (self.copy_callback)(copy)
159 }
160
161 fn options(&self) -> &CopyFromOptions {
162 &self.options
163 }
164
165 fn walk_target<'b>(
166 &'b self,
167 pass: crate::query_builder::AstPass<'_, 'b, Pg>,
168 ) -> crate::QueryResult<()> {
169 S::walk_target(pass)
170 }
171 }
172
173 struct Dummy;
174
175 impl PgMetadataLookup for Dummy {
176 fn lookup_type(&mut self, type_name: &str, schema: Option<&str>) -> crate::pg::PgTypeMetadata {
177 let cache_key = PgMetadataCacheKey::new(
178 schema.map(Into::into).map(Cow::Owned),
179 Cow::Owned(type_name.into()),
180 );
181 crate::pg::PgTypeMetadata(Err(FailedToLookupTypeError::new_internal(cache_key)))
182 }
183 }
184
185 trait CopyFromInsertableHelper {
186 type Target: CopyTarget;
187 const COLUMN_COUNT: i16;
188
189 fn write_to_buffer(&self, idx: i16, out: &mut Vec<u8>) -> QueryResult<IsNull>;
190 }
191
192 macro_rules! impl_copy_from_insertable_helper_for_values_clause {
193 ($(
194 $Tuple:tt {
195 $(($idx:tt) -> $T:ident, $ST:ident, $TT:ident,)+
196 }
197 )+) => {
198 $(
199 impl<__T, $($ST,)* $($T,)* $($TT,)*> CopyFromInsertableHelper for ValuesClause<
200 ($(ColumnInsertValue<$ST, Bound<$T, $TT>>,)*),
201 __T>
202 where
203 __T: Table,
204 $($ST: Column<Table = __T>,)*
205 ($($ST,)*): CopyTarget,
206 $($TT: ToSql<$T, Pg>,)*
207 {
208 type Target = ($($ST,)*);
209
210 // statically known to always fit
211 // as we don't support more than 128 columns
212 #[allow(clippy::cast_possible_truncation)]
213 const COLUMN_COUNT: i16 = $Tuple as i16;
214
215 fn write_to_buffer(&self, idx: i16, out: &mut Vec<u8>) -> QueryResult<IsNull> {
216 use crate::query_builder::ByteWrapper;
217 use crate::serialize::Output;
218
219 let values = &self.values;
220 match idx {
221 $($idx =>{
222 let item = &values.$idx.expr.item;
223 let is_null = ToSql::<$T, Pg>::to_sql(
224 item,
225 &mut Output::new( ByteWrapper(out), &mut Dummy as _)
226 ).map_err(crate::result::Error::SerializationError)?;
227 return Ok(is_null);
228 })*
229 _ => unreachable!(),
230 }
231 }
232 }
233
234 impl<'a, __T, $($ST,)* $($T,)* $($TT,)*> CopyFromInsertableHelper for ValuesClause<
235 ($(ColumnInsertValue<$ST, &'a Bound<$T, $TT>>,)*),
236 __T>
237 where
238 __T: Table,
239 $($ST: Column<Table = __T>,)*
240 ($($ST,)*): CopyTarget,
241 $($TT: ToSql<$T, Pg>,)*
242 {
243 type Target = ($($ST,)*);
244
245 // statically known to always fit
246 // as we don't support more than 128 columns
247 #[allow(clippy::cast_possible_truncation)]
248 const COLUMN_COUNT: i16 = $Tuple as i16;
249
250 fn write_to_buffer(&self, idx: i16, out: &mut Vec<u8>) -> QueryResult<IsNull> {
251 use crate::query_builder::ByteWrapper;
252 use crate::serialize::Output;
253
254 let values = &self.values;
255 match idx {
256 $($idx =>{
257 let item = &values.$idx.expr.item;
258 let is_null = ToSql::<$T, Pg>::to_sql(
259 item,
260 &mut Output::new( ByteWrapper(out), &mut Dummy as _)
261 ).map_err(crate::result::Error::SerializationError)?;
262 return Ok(is_null);
263 })*
264 _ => unreachable!(),
265 }
266 }
267 }
268 )*
269 }
270 }
271
272 diesel_derives::__diesel_for_each_tuple!(impl_copy_from_insertable_helper_for_values_clause);
273
274 #[derive(Debug)]
275 pub struct InsertableWrapper<I>(Option<I>);
276
277 impl<I, T, V, QId, const STATIC_QUERY_ID: bool> CopyFromExpression<T> for InsertableWrapper<I>
278 where
279 I: Insertable<T, Values = BatchInsert<Vec<V>, T, QId, STATIC_QUERY_ID>>,
280 V: CopyFromInsertableHelper,
281 {
282 type Error = crate::result::Error;
283
284 fn callback(&mut self, copy: &mut impl std::io::Write) -> Result<(), Self::Error> {
285 let io_result_mapper = |e| crate::result::Error::DeserializationError(Box::new(e));
286 // see https://www.postgresql.org/docs/current/sql-copy.html for
287 // a description of the binary format
288 //
289 // We don't write oids
290
291 // write the header
292 copy.write_all(&super::COPY_MAGIC_HEADER)
293 .map_err(io_result_mapper)?;
294 copy.write_i32::<NetworkEndian>(0)
295 .map_err(io_result_mapper)?;
296 copy.write_i32::<NetworkEndian>(0)
297 .map_err(io_result_mapper)?;
298 // write the data
299 // we reuse the same buffer here again and again
300 // as we expect the data to be "similar"
301 // this skips reallocating
302 let mut buffer = Vec::<u8>::new();
303 let values = self
304 .0
305 .take()
306 .expect("We only call this callback once")
307 .values();
308 for i in values.values {
309 // column count
310 buffer
311 .write_i16::<NetworkEndian>(V::COLUMN_COUNT)
312 .map_err(io_result_mapper)?;
313 for idx in 0..V::COLUMN_COUNT {
314 // first write the null indicator as dummy value
315 buffer
316 .write_i32::<NetworkEndian>(-1)
317 .map_err(io_result_mapper)?;
318 let len_before = buffer.len();
319 let is_null = i.write_to_buffer(idx, &mut buffer)?;
320 if is_null == IsNull::No {
321 // fill in the length afterwards
322 let len_after = buffer.len();
323 let diff = (len_after - len_before)
324 .try_into()
325 .map_err(|e| crate::result::Error::SerializationError(Box::new(e)))?;
326 let bytes = i32::to_be_bytes(diff);
327 for (b, t) in bytes.into_iter().zip(&mut buffer[len_before - 4..]) {
328 *t = b;
329 }
330 }
331 }
332 copy.write_all(&buffer).map_err(io_result_mapper)?;
333 buffer.clear();
334 }
335 // write the trailer
336 copy.write_i16::<NetworkEndian>(-1)
337 .map_err(io_result_mapper)?;
338 Ok(())
339 }
340
341 fn options(&self) -> &CopyFromOptions {
342 &CopyFromOptions {
343 common: CommonOptions {
344 format: Some(CopyFormat::Binary),
345 freeze: None,
346 delimiter: None,
347 null: None,
348 quote: None,
349 escape: None,
350 },
351 default: None,
352 header: None,
353 }
354 }
355
356 fn walk_target<'b>(
357 &'b self,
358 pass: crate::query_builder::AstPass<'_, 'b, Pg>,
359 ) -> crate::QueryResult<()> {
360 <V as CopyFromInsertableHelper>::Target::walk_target(pass)
361 }
362 }
363
364 /// The structure returned by [`copy_from`]
365 ///
366 /// The [`from_raw_data`] and the [`from_insertable`] methods allow
367 /// to configure the data copied into the database
368 ///
369 /// The `with_*` methods allow to configure the settings used for the
370 /// copy statement.
371 ///
372 /// [`from_raw_data`]: CopyFromQuery::from_raw_data
373 /// [`from_insertable`]: CopyFromQuery::from_insertable
374 #[derive(Debug)]
375 #[must_use = "`COPY FROM` statements are only executed when calling `.execute()`."]
376 #[cfg(feature = "postgres_backend")]
377 pub struct CopyFromQuery<T, Action> {
378 table: T,
379 action: Action,
380 }
381
382 impl<T> CopyFromQuery<T, NotSet>
383 where
384 T: Table,
385 {
386 /// Copy data into the database by directly providing the data in the corresponding format
387 ///
388 /// `target` specifies the column selection that is the target of the `COPY FROM` statement
389 /// `action` expects a callback which accepts a [`std::io::Write`] argument. The necessary format
390 /// accepted by this writer sink depends on the options provided via the `with_*` methods
391 #[allow(clippy::wrong_self_convention)] // the sql struct is named that way
392 pub fn from_raw_data<F, C, E>(self, _target: C, action: F) -> CopyFromQuery<T, CopyFrom<C, F>>
393 where
394 C: CopyTarget<Table = T>,
395 F: Fn(&mut dyn std::io::Write) -> Result<(), E>,
396 {
397 CopyFromQuery {
398 table: self.table,
399 action: CopyFrom {
400 p: PhantomData,
401 options: Default::default(),
402 copy_callback: action,
403 },
404 }
405 }
406
407 /// Copy a set of insertable values into the database.
408 ///
409 /// The `insertable` argument is expected to be a `Vec<I>`, `&[I]` or similar, where `I`
410 /// needs to implement `Insertable<T>`. If you use the [`#[derive(Insertable)]`](derive@crate::prelude::Insertable)
411 /// derive macro make sure to also set the `#[diesel(treat_none_as_default_value = false)]` option
412 /// to disable the default value handling otherwise implemented by `#[derive(Insertable)]`.
413 ///
414 /// This uses the binary format. It internally configures the correct
415 /// set of settings and does not allow to set other options
416 #[allow(clippy::wrong_self_convention)] // the sql struct is named that way
417 pub fn from_insertable<I>(self, insertable: I) -> CopyFromQuery<T, InsertableWrapper<I>>
418 where
419 InsertableWrapper<I>: CopyFromExpression<T>,
420 {
421 CopyFromQuery {
422 table: self.table,
423 action: InsertableWrapper(Some(insertable)),
424 }
425 }
426 }
427
428 impl<T, C, F> CopyFromQuery<T, CopyFrom<C, F>> {
429 /// The format used for the copy statement
430 ///
431 /// See the [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-copy.html)
432 /// for more details.
433 pub fn with_format(mut self, format: CopyFormat) -> Self {
434 self.action.options.common.format = Some(format);
435 self
436 }
437
438 /// Whether or not the `freeze` option is set
439 ///
440 /// See the [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-copy.html)
441 /// for more details.
442 pub fn with_freeze(mut self, freeze: bool) -> Self {
443 self.action.options.common.freeze = Some(freeze);
444 self
445 }
446
447 /// Which delimiter should be used for textual input formats
448 ///
449 /// See the [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-copy.html)
450 /// for more details.
451 ///
452 /// Diesel will automatically escape the provided delimiter for the default
453 /// PostgreSQL setting `standard_conforming_strings=on`. If you use a non-standard
454 /// conforming setting you need to take care of escaping the value on your own
455 pub fn with_delimiter(mut self, delimiter: char) -> Self {
456 self.action.options.common.delimiter = Some(delimiter);
457 self
458 }
459
460 /// Which string should be used in place of a `NULL` value
461 /// for textual input formats
462 ///
463 /// See the [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-copy.html)
464 /// for more details.
465 ///
466 /// Diesel will automatically escape the provided delimiter for the default
467 /// PostgreSQL setting `standard_conforming_strings=on`. If you use a non-standard
468 /// conforming setting you need to take care of escaping the value on your own
469 pub fn with_null(mut self, null: impl Into<String>) -> Self {
470 self.action.options.common.null = Some(null.into());
471 self
472 }
473
474 /// Which quote character should be used for textual input formats
475 ///
476 /// See the [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-copy.html)
477 /// for more details.
478 ///
479 /// Diesel will automatically escape the provided delimiter for the default
480 /// PostgreSQL setting `standard_conforming_strings=on`. If you use a non-standard
481 /// conforming setting you need to take care of escaping the value on your own
482 pub fn with_quote(mut self, quote: char) -> Self {
483 self.action.options.common.quote = Some(quote);
484 self
485 }
486
487 /// Which escape character should be used for textual input formats
488 ///
489 /// See the [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-copy.html)
490 /// for more details.
491 ///
492 /// Diesel will automatically escape the provided delimiter for the default
493 /// PostgreSQL setting `standard_conforming_strings=on`. If you use a non-standard
494 /// conforming setting you need to take care of escaping the value on your own
495 pub fn with_escape(mut self, escape: char) -> Self {
496 self.action.options.common.escape = Some(escape);
497 self
498 }
499
500 /// Which string should be used to indicate that
501 /// the `default` value should be used in place of that string
502 /// for textual formats
503 ///
504 /// See the [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-copy.html)
505 /// for more details.
506 ///
507 /// (This parameter was added with PostgreSQL 16)
508 ///
509 /// Diesel will automatically escape the provided delimiter for the default
510 /// PostgreSQL setting `standard_conforming_strings=on`. If you use a non-standard
511 /// conforming setting you need to take care of escaping the value on your own
512 pub fn with_default(mut self, default: impl Into<String>) -> Self {
513 self.action.options.default = Some(default.into());
514 self
515 }
516
517 /// Is a header provided as part of the textual input or not
518 ///
519 /// See the [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-copy.html)
520 /// for more details.
521 pub fn with_header(mut self, header: CopyHeader) -> Self {
522 self.action.options.header = Some(header);
523 self
524 }
525 }
526
527 /// A custom execute function tailored for `COPY FROM` statements
528 ///
529 /// This trait can be used to execute `COPY FROM` queries constructed
530 /// via [`copy_from]`
531 pub trait ExecuteCopyFromDsl<C>
532 where
533 C: Connection<Backend = Pg>,
534 {
535 /// The error type returned by the execute function
536 type Error: std::error::Error;
537
538 /// See the trait documentation for details
539 fn execute(self, conn: &mut C) -> Result<usize, Self::Error>;
540 }
541
542 #[cfg(feature = "postgres")]
543 impl<T, A> ExecuteCopyFromDsl<crate::PgConnection> for CopyFromQuery<T, A>
544 where
545 A: CopyFromExpression<T>,
546 {
547 type Error = A::Error;
548
549 fn execute(self, conn: &mut crate::PgConnection) -> Result<usize, A::Error> {
550 conn.copy_from::<A, T>(self.action)
551 }
552 }
553
554 #[cfg(feature = "r2d2")]
555 impl<T, A, C> ExecuteCopyFromDsl<crate::r2d2::PooledConnection<crate::r2d2::ConnectionManager<C>>>
556 for CopyFromQuery<T, A>
557 where
558 A: CopyFromExpression<T>,
559 C: crate::r2d2::R2D2Connection<Backend = Pg> + 'static,
560 Self: ExecuteCopyFromDsl<C>,
561 {
562 type Error = <Self as ExecuteCopyFromDsl<C>>::Error;
563
564 fn execute(
565 self,
566 conn: &mut crate::r2d2::PooledConnection<crate::r2d2::ConnectionManager<C>>,
567 ) -> Result<usize, Self::Error> {
568 self.execute(&mut **conn)
569 }
570 }
571
572 #[derive(Debug, Clone, Copy)]
573 pub struct NotSet;
574
575 /// Creates a `COPY FROM` statement
576 ///
577 /// This function constructs `COPY FROM` statement which copies data
578 /// *from* a source into the database. It's designed to move larger
579 /// amounts of data into the database.
580 ///
581 /// This function accepts a target table as argument.
582 ///
583 /// There are two ways to construct a `COPY FROM` statement with
584 /// diesel:
585 ///
586 /// * By providing a `Vec<I>` where `I` implements `Insertable` for the
587 /// given table
588 /// * By providing a target selection (column list or table name)
589 /// and a callback that provides the data
590 ///
591 /// The first variant uses the `BINARY` format internally to send
592 /// the provided data efficiently to the database. It automatically
593 /// sets the right options and does not allow changing them.
594 /// Use [`CopyFromQuery::from_insertable`] for this.
595 ///
596 /// The second variant allows you to control the behaviour
597 /// of the generated `COPY FROM` statement in detail. It can
598 /// be setup via the [`CopyFromQuery::from_raw_data`] function.
599 /// The callback accepts an opaque object as argument that allows
600 /// to write the corresponding data to the database. The exact
601 /// format depends on the settings chosen by the various
602 /// `CopyFromQuery::with_*` methods. See
603 /// [the postgresql documentation](https://www.postgresql.org/docs/current/sql-copy.html)
604 /// for more details about the expected formats.
605 ///
606 /// If you don't have any specific needs you should prefer
607 /// using the more convenient first variant.
608 ///
609 /// This functionality is postgresql specific.
610 ///
611 /// # Examples
612 ///
613 /// ## Via [`CopyFromQuery::from_insertable`]
614 ///
615 /// ```rust
616 /// # include!("../../../doctest_setup.rs");
617 /// # use crate::schema::users;
618 ///
619 /// #[derive(Insertable)]
620 /// #[diesel(table_name = users)]
621 /// #[diesel(treat_none_as_default_value = false)]
622 /// struct NewUser {
623 /// name: &'static str,
624 /// }
625 ///
626 /// # fn run_test() -> QueryResult<()> {
627 /// # let connection = &mut establish_connection();
628 ///
629 /// let data = vec![
630 /// NewUser {
631 /// name: "Diva Plavalaguna",
632 /// },
633 /// NewUser {
634 /// name: "Father Vito Cornelius",
635 /// },
636 /// ];
637 ///
638 /// let count = diesel::copy_from(users::table)
639 /// .from_insertable(&data)
640 /// .execute(connection)?;
641 ///
642 /// assert_eq!(count, 2);
643 /// # Ok(())
644 /// # }
645 /// # fn main() {
646 /// # run_test().unwrap();
647 /// # }
648 /// ```
649 ///
650 /// ## Via [`CopyFromQuery::from_raw_data`]
651 ///
652 /// ```rust
653 /// # include!("../../../doctest_setup.rs");
654 /// # fn run_test() -> QueryResult<()> {
655 /// # use crate::schema::users;
656 /// use diesel::pg::CopyFormat;
657 /// # let connection = &mut establish_connection();
658 /// let count = diesel::copy_from(users::table)
659 /// .from_raw_data(users::table, |copy| {
660 /// writeln!(copy, "3,Diva Plavalaguna").unwrap();
661 /// writeln!(copy, "4,Father Vito Cornelius").unwrap();
662 /// diesel::QueryResult::Ok(())
663 /// })
664 /// .with_format(CopyFormat::Csv)
665 /// .execute(connection)?;
666 ///
667 /// assert_eq!(count, 2);
668 /// # Ok(())
669 /// # }
670 /// # fn main() {
671 /// # run_test().unwrap();
672 /// # }
673 /// ```
674 #[cfg(feature = "postgres_backend")]
675 pub fn copy_from<T>(table: T) -> CopyFromQuery<T, NotSet>
676 where
677 T: Table,
678 {
679 CopyFromQuery {
680 table,
681 action: NotSet,
682 }
683 }