sql_builder/query/insert/values.rs
1use super::*;
2
3impl InsertStatement {
4 /// Construct a new [`InsertStatement`]
5 pub fn new() -> Self {
6 Self::default()
7 }
8
9 /// Take the ownership of data in the current [`SelectStatement`]
10 pub fn take(&mut self) -> Self {
11 Self {
12 replace: self.replace,
13 table: self.table.take(),
14 columns: std::mem::take(&mut self.columns),
15 source: self.source.take(),
16 on_conflict: self.on_conflict.take(),
17 returning: self.returning.take(),
18 default_values: self.default_values.take(),
19 with: self.with.take(),
20 }
21 }
22
23 /// Use REPLACE instead of INSERT. PostgreSQL has none and refuses to render it.
24 ///
25 /// # Examples
26 ///
27 /// ```
28 /// use sql_builder::*;
29 ///
30 /// let query = Query::insert()
31 /// .replace()
32 /// .into_table("glyph")
33 /// .columns(["aspect", "image"])
34 /// .values_panic([5.15.into(), "12A".into()])
35 /// .take();
36 ///
37 /// assert_eq!(
38 /// query.to_string(MysqlQueryBuilder).unwrap(),
39 /// r#"REPLACE INTO `glyph` (`aspect`, `image`) VALUES (5.15, '12A')"#
40 /// );
41 /// assert_eq!(
42 /// query.to_string(SqliteQueryBuilder).unwrap(),
43 /// r#"REPLACE INTO "glyph" ("aspect", "image") VALUES (5.15, '12A')"#
44 /// );
45 /// ```
46 pub fn replace(&mut self) -> &mut Self {
47 self.replace = true;
48 self
49 }
50
51 /// Specify which table to insert into.
52 ///
53 /// # Examples
54 ///
55 /// See [`InsertStatement::values`]
56 pub fn into_table<T>(&mut self, tbl_ref: T) -> &mut Self
57 where
58 T: IntoTableRef,
59 {
60 self.table = Some(Box::new(tbl_ref.into_table_ref()));
61 self
62 }
63
64 /// Specify what columns to insert.
65 ///
66 /// # Examples
67 ///
68 /// See [`InsertStatement::values`]
69 pub fn columns<C, I>(&mut self, columns: I) -> &mut Self
70 where
71 C: IntoIden,
72 I: IntoIterator<Item = C>,
73 {
74 self.columns = columns.into_iter().map(|c| c.into_iden()).collect();
75 self
76 }
77
78 /// Specify a select query whose values to be inserted.
79 ///
80 /// # Examples
81 ///
82 /// ```
83 /// use sql_builder::*;
84 ///
85 /// let query = Query::insert()
86 /// .into_table("glyph")
87 /// .columns(["aspect", "image"])
88 /// .select_from(Query::select()
89 /// .column("aspect")
90 /// .column("image")
91 /// .from("glyph")
92 /// .and_where(Expr::col("image").like("0%"))
93 /// .take()
94 /// )
95 /// .unwrap()
96 /// .take();
97 ///
98 /// assert_eq!(
99 /// query.to_string(MysqlQueryBuilder).unwrap(),
100 /// r#"INSERT INTO `glyph` (`aspect`, `image`) SELECT `aspect`, `image` FROM `glyph` WHERE `image` LIKE '0%'"#
101 /// );
102 /// assert_eq!(
103 /// query.to_string(PostgresQueryBuilder).unwrap(),
104 /// r#"INSERT INTO "glyph" ("aspect", "image") SELECT "aspect", "image" FROM "glyph" WHERE "image" LIKE '0%'"#
105 /// );
106 /// assert_eq!(
107 /// query.to_string(SqliteQueryBuilder).unwrap(),
108 /// r#"INSERT INTO "glyph" ("aspect", "image") SELECT "aspect", "image" FROM "glyph" WHERE "image" LIKE '0%'"#
109 /// );
110 /// ```
111 ///
112 /// ```
113 /// use sql_builder::*;
114 /// let query = Query::insert()
115 /// .into_table("glyph")
116 /// .columns(["image"])
117 /// .select_from(
118 /// Query::select()
119 /// .expr(Expr::val("hello"))
120 /// .cond_where(Cond::all().not().add(Expr::exists(
121 /// Query::select().expr(Expr::val("world")).take(),
122 /// )))
123 /// .take(),
124 /// )
125 /// .unwrap()
126 /// .take();
127 ///
128 /// assert_eq!(
129 /// query.to_string(SqliteQueryBuilder).unwrap(),
130 /// r#"INSERT INTO "glyph" ("image") SELECT 'hello' WHERE NOT EXISTS(SELECT 'world')"#
131 /// );
132 /// ```
133 ///
134 /// ```
135 /// use sql_builder::*;
136 /// let query = Query::insert()
137 /// .into_table("glyph")
138 /// .columns(["image"])
139 /// .select_from(
140 /// Query::select()
141 /// .expr(Expr::col("name"))
142 /// .from("font")
143 /// .take(),
144 /// )
145 /// .unwrap()
146 /// .take();
147 ///
148 /// assert_eq!(
149 /// query.to_string(SqliteQueryBuilder).unwrap(),
150 /// r#"INSERT INTO "glyph" ("image") SELECT "name" FROM "font""#
151 /// );
152 /// ```
153 pub fn select_from<S>(&mut self, select: S) -> Result<&mut Self>
154 where
155 S: Into<SelectStatement>,
156 {
157 let statement = select.into();
158
159 if self.columns.len() != statement.selects.len() {
160 return Err(Error::ColValNumMismatch {
161 col_len: self.columns.len(),
162 val_len: statement.selects.len(),
163 });
164 }
165
166 self.source = Some(InsertValueSource::Select(Box::new(statement)));
167 Ok(self)
168 }
169
170 /// Specify a row of values to be inserted.
171 ///
172 /// Return error when number of values not matching number of columns.
173 ///
174 /// # Examples
175 ///
176 /// ```
177 /// use sql_builder::*;
178 ///
179 /// let query = Query::insert()
180 /// .into_table("glyph")
181 /// .columns(["aspect", "image"])
182 /// .values([
183 /// 2.into(),
184 /// Func::cast_as("2020-02-02 00:00:00", "DATE").into(),
185 /// ])
186 /// .unwrap()
187 /// .take();
188 ///
189 /// assert_eq!(
190 /// query.to_string(MysqlQueryBuilder).unwrap(),
191 /// r#"INSERT INTO `glyph` (`aspect`, `image`) VALUES (2, CAST('2020-02-02 00:00:00' AS DATE))"#
192 /// );
193 /// assert_eq!(
194 /// query.to_string(PostgresQueryBuilder).unwrap(),
195 /// r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2, CAST('2020-02-02 00:00:00' AS DATE))"#
196 /// );
197 /// assert_eq!(
198 /// query.to_string(SqliteQueryBuilder).unwrap(),
199 /// r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2, CAST('2020-02-02 00:00:00' AS DATE))"#
200 /// );
201 ///
202 /// assert!(
203 /// Query::insert()
204 /// .into_table("glyph")
205 /// .columns(["aspect", "image"])
206 /// .values([1.into()])
207 /// .is_err()
208 /// );
209 /// ```
210 pub fn values<I>(&mut self, values: I) -> Result<&mut Self>
211 where
212 I: IntoIterator<Item = Expr>,
213 {
214 let values = values.into_iter().collect::<Vec<Expr>>();
215 if self.columns.len() != values.len() {
216 return Err(Error::ColValNumMismatch {
217 col_len: self.columns.len(),
218 val_len: values.len(),
219 });
220 }
221 if !values.is_empty() {
222 let values_source = if let Some(InsertValueSource::Values(values)) = &mut self.source {
223 values
224 } else {
225 self.source = Some(InsertValueSource::Values(Default::default()));
226 if let Some(InsertValueSource::Values(values)) = &mut self.source {
227 values
228 } else {
229 unreachable!();
230 }
231 };
232 values_source.push(values);
233 }
234 Ok(self)
235 }
236
237 /// Specify a row of values to be inserted, variation of [`InsertStatement::values`].
238 ///
239 /// # Panics
240 ///
241 /// Panics when number of values not matching number of columns.
242 /// The engine's `insert_many` does not panic: it builds the column list from the active models.
243 ///
244 /// # Examples
245 ///
246 /// ```
247 /// use sql_builder::*;
248 ///
249 /// let query = Query::insert()
250 /// .into_table("glyph")
251 /// .columns(["aspect", "image"])
252 /// .values_panic([2.1345.into(), "24B".into()])
253 /// .values_panic([5.15.into(), "12A".into()])
254 /// .take();
255 ///
256 /// assert_eq!(
257 /// query.to_string(MysqlQueryBuilder).unwrap(),
258 /// r#"INSERT INTO `glyph` (`aspect`, `image`) VALUES (2.1345, '24B'), (5.15, '12A')"#
259 /// );
260 /// assert_eq!(
261 /// query.to_string(PostgresQueryBuilder).unwrap(),
262 /// r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2.1345, '24B'), (5.15, '12A')"#
263 /// );
264 /// assert_eq!(
265 /// query.to_string(SqliteQueryBuilder).unwrap(),
266 /// r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2.1345, '24B'), (5.15, '12A')"#
267 /// );
268 /// ```
269 ///
270 /// ```should_panic
271 /// # use sql_builder::*;
272 /// let query = Query::insert()
273 /// .into_table("glyph")
274 /// .columns(["aspect"])
275 /// .values_panic([2.1345.into(), "24B".into()])
276 /// .take();
277 /// ```
278 pub fn values_panic<I>(&mut self, values: I) -> &mut Self
279 where
280 I: IntoIterator<Item = Expr>,
281 {
282 self.values(values).unwrap()
283 }
284
285 /// Add rows to be inserted from an iterator, variation of [`InsertStatement::values_panic`].
286 ///
287 /// # Examples
288 ///
289 /// ```
290 /// use sql_builder::*;
291 ///
292 /// let rows = vec![[2.1345.into(), "24B".into()], [5.15.into(), "12A".into()]];
293 ///
294 /// let query = Query::insert()
295 /// .into_table("glyph")
296 /// .columns(["aspect", "image"])
297 /// .values_from_panic(rows)
298 /// .take();
299 ///
300 /// assert_eq!(
301 /// query.to_string(MysqlQueryBuilder).unwrap(),
302 /// r#"INSERT INTO `glyph` (`aspect`, `image`) VALUES (2.1345, '24B'), (5.15, '12A')"#
303 /// );
304 /// assert_eq!(
305 /// query.to_string(PostgresQueryBuilder).unwrap(),
306 /// r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2.1345, '24B'), (5.15, '12A')"#
307 /// );
308 /// assert_eq!(
309 /// query.to_string(SqliteQueryBuilder).unwrap(),
310 /// r#"INSERT INTO "glyph" ("aspect", "image") VALUES (2.1345, '24B'), (5.15, '12A')"#
311 /// );
312 /// ```
313 pub fn values_from_panic<I, J>(&mut self, values_iter: J) -> &mut Self
314 where
315 I: IntoIterator<Item = Expr>,
316 J: IntoIterator<Item = I>,
317 {
318 values_iter.into_iter().for_each(|values| {
319 self.values_panic(values);
320 });
321 self
322 }
323}