Skip to main content

sql_builder/query/
insert.rs

1mod build;
2mod conflict;
3mod values;
4
5use crate::{
6    DynIden, Expr, IntoColumnRef, IntoIden, IntoTableRef, OnConflict, QueryStatement,
7    ReturningClause, SelectStatement, SubQueryStatement, TableRef, WithClause, WithQuery,
8    error::{Error, Result},
9};
10
11/// Represents a value source that can be used in an insert query.
12///
13/// [`InsertValueSource`] is a node in the expression tree and can represent a raw value set
14/// ('VALUES') or a select query.
15#[derive(Debug, Clone, PartialEq)]
16pub(crate) enum InsertValueSource {
17    Values(Vec<Vec<Expr>>),
18    Select(Box<SelectStatement>),
19}
20
21/// Insert any new rows into an existing table
22///
23/// # Examples
24///
25/// ```
26/// use sql_builder::*;
27///
28/// let query = Query::insert()
29///     .into_table("glyph")
30///     .columns(["aspect", "image"])
31///     .values_panic([5.15.into(), "12A".into()])
32///     .values_panic([4.21.into(), "123".into()])
33///     .take();
34///
35/// assert_eq!(
36///     query.to_string(MysqlQueryBuilder).unwrap(),
37///     r#"INSERT INTO `glyph` (`aspect`, `image`) VALUES (5.15, '12A'), (4.21, '123')"#
38/// );
39/// assert_eq!(
40///     query.to_string(PostgresQueryBuilder).unwrap(),
41///     r#"INSERT INTO "glyph" ("aspect", "image") VALUES (5.15, '12A'), (4.21, '123')"#
42/// );
43/// assert_eq!(
44///     query.to_string(SqliteQueryBuilder).unwrap(),
45///     r#"INSERT INTO "glyph" ("aspect", "image") VALUES (5.15, '12A'), (4.21, '123')"#
46/// );
47/// ```
48#[derive(Debug, Default, Clone, PartialEq)]
49pub struct InsertStatement {
50    pub(crate) replace: bool,
51    pub(crate) table: Option<Box<TableRef>>,
52    pub(crate) columns: Vec<DynIden>,
53    pub(crate) source: Option<InsertValueSource>,
54    pub(crate) on_conflict: Option<OnConflict>,
55    pub(crate) returning: Option<ReturningClause>,
56    pub(crate) default_values: Option<usize>,
57    pub(crate) with: Option<WithClause>,
58}
59
60impl InsertStatement {
61    /// Default rows that will actually render; explicit columns or a source override them.
62    pub(crate) fn active_default_rows(&self) -> Option<usize> {
63        self.default_values
64            .filter(|count| *count != 0 && self.columns.is_empty() && self.source.is_none())
65    }
66}