sqlx/macros/mod.rs
1/// Statically checked SQL query with `println!()` style syntax.
2///
3/// This expands to an instance of [`query::Map`][crate::query::Map] that outputs an ad-hoc anonymous
4/// struct type, if the query has at least one output column that is not `Void`, or `()` (unit) otherwise:
5///
6/// ```rust,ignore
7/// # use sqlx::Connect;
8/// # #[cfg(all(feature = "mysql", feature = "_rt-async-std"))]
9/// # #[async_std::main]
10/// # async fn main() -> sqlx::Result<()>{
11/// # let db_url = dotenvy::var("DATABASE_URL").expect("DATABASE_URL must be set");
12/// #
13/// # if !(db_url.starts_with("mysql") || db_url.starts_with("mariadb")) { return Ok(()) }
14/// # let mut conn = sqlx::MySqlConnection::connect(db_url).await?;
15/// // let mut conn = <impl sqlx::Executor>;
16/// let account = sqlx::query!("select (1) as id, 'Herp Derpinson' as name")
17/// .fetch_one(&mut conn)
18/// .await?;
19///
20/// // anonymous struct has `#[derive(Debug)]` for convenience
21/// println!("{account:?}");
22/// println!("{}: {}", account.id, account.name);
23///
24/// # Ok(())
25/// # }
26/// #
27/// # #[cfg(any(not(feature = "mysql"), not(feature = "_rt-async-std")))]
28/// # fn main() {}
29/// ```
30///
31/// The output columns will be mapped to their corresponding Rust types.
32/// See the documentation for your database for details:
33///
34/// * Postgres: [crate::postgres::types]
35/// * MySQL: [crate::mysql::types]
36/// * Note: due to wire protocol limitations, the query macros do not know when
37/// a column should be decoded as `bool`. It will be inferred to be `i8` instead.
38/// See the link above for details.
39/// * SQLite: [crate::sqlite::types]
40///
41/// **The method you want to call on the result depends on how many rows you're expecting.**
42///
43/// | Number of Rows | Method to Call* | Returns | Notes |
44/// |----------------| ----------------------------|-----------------------------------------------------|-------|
45/// | None†| `.execute(...).await` | `sqlx::Result<DB::QueryResult>` | For `INSERT`/`UPDATE`/`DELETE` without `RETURNING`. |
46/// | Zero or One | `.fetch_optional(...).await`| `sqlx::Result<Option<{adhoc struct}>>` | Extra rows are ignored. |
47/// | Exactly One | `.fetch_one(...).await` | `sqlx::Result<{adhoc struct}>` | Errors if no rows were returned. Extra rows are ignored. Aggregate queries, use this. |
48/// | At Least One | `.fetch(...)` | `impl Stream<Item = sqlx::Result<{adhoc struct}>>` | Call `.try_next().await` to get each row result. |
49/// | Multiple | `.fetch_all(...)` | `sqlx::Result<Vec<{adhoc struct}>>` | |
50///
51/// \* All methods accept one of `&mut {connection type}`, `&mut Transaction` or `&Pool`.
52/// †Only callable if the query returns no columns; otherwise it's assumed the query *may* return at least one row.
53/// ## Requirements
54/// * The `DATABASE_URL` environment variable must be set at build-time to point to a database
55/// server with the schema that the query string will be checked against.
56/// All variants of `query!()` use [dotenv]<sup>1</sup> so this can be in a `.env` file instead.
57///
58/// * Or, `.sqlx` must exist at the workspace root. See [Offline Mode](#offline-mode-requires-the-offline-feature)
59/// below.
60///
61/// * The query must be a string literal, or concatenation of string literals using `+` (useful
62/// for queries generated by macro), or else it cannot be introspected (and thus cannot be dynamic
63/// or the result of another macro).
64///
65/// * The `QueryAs` instance will be bound to the same database type as `query!()` was compiled
66/// against (e.g. you cannot build against a Postgres database and then run the query against
67/// a MySQL database).
68///
69/// * The schema of the database URL (e.g. `postgres://` or `mysql://`) will be used to
70/// determine the database type.
71///
72/// <sup>1</sup> The `dotenv` crate itself appears abandoned as of [December 2021](https://github.com/dotenv-rs/dotenv/issues/74)
73/// so we now use the [dotenvy] crate instead. The file format is the same.
74///
75/// [dotenv]: https://crates.io/crates/dotenv
76/// [dotenvy]: https://crates.io/crates/dotenvy
77///
78/// ## Configuration with `sqlx.toml`
79/// Multiple crate-wide configuration options are now available, including:
80///
81/// * change the name of the `DATABASE_URL` variable for using multiple databases in the same workspace
82/// * In the initial implementation, a separate crate must be created for each database.
83/// Using multiple databases in the same crate may become possible in the future.
84/// * global type overrides (useful for custom types!)
85/// * per-column type overrides
86/// * force use of a specific crate (e.g. `chrono` when both it and `time` are enabled)
87///
88/// See the [configuration guide] and [reference `sqlx.toml`] for details.
89///
90/// See also `examples/postgres/multi-database` and `examples/postgres/preferred-crates`
91/// for example usage.
92///
93/// [configuration guide]: crate::_config::macros::Config
94/// [reference `sqlx.toml`]: crate::_config::_reference
95///
96/// ## Query Arguments
97/// Like `println!()` and the other formatting macros, you can add bind parameters to your SQL
98/// and this macro will typecheck passed arguments and error on missing ones:
99///
100/// ```rust,ignore
101/// # use sqlx::Connect;
102/// # #[cfg(all(feature = "mysql", feature = "_rt-async-std"))]
103/// # #[async_std::main]
104/// # async fn main() -> sqlx::Result<()>{
105/// # let db_url = dotenvy::var("DATABASE_URL").expect("DATABASE_URL must be set");
106/// #
107/// # if !(db_url.starts_with("mysql") || db_url.starts_with("mariadb")) { return Ok(()) }
108/// # let mut conn = sqlx::mysql::MySqlConnection::connect(db_url).await?;
109/// // let mut conn = <impl sqlx::Executor>;
110/// let account = sqlx::query!(
111/// // just pretend "accounts" is a real table
112/// "select * from (select (1) as id, 'Herp Derpinson' as name) accounts where id = ?",
113/// 1i32
114/// )
115/// .fetch_one(&mut conn)
116/// .await?;
117///
118/// println!("{account:?}");
119/// println!("{}: {}", account.id, account.name);
120/// # Ok(())
121/// # }
122/// #
123/// # #[cfg(any(not(feature = "mysql"), not(feature = "_rt-async-std")))]
124/// # fn main() {}
125/// ```
126///
127/// Bind parameters in the SQL string are specific to the database backend:
128///
129/// * Postgres: `$N` where `N` is the 1-based positional argument index
130/// * MySQL/SQLite: `?` which matches arguments in order that it appears in the query
131///
132/// ## Nullability: Bind Parameters
133/// **The nullability of bind parameters is _not_ verified at compile time.** Unlike output
134/// columns (see the [next section](#nullability-output-columns)), the `query!()` family of
135/// macros does not check whether an `Option<T>` bound to a parameter is compatible with the
136/// nullability of the target column. This is a fundamental limitation, not an oversight:
137/// determining which parameter maps to which column would require the macros to parse and
138/// analyze the SQL themselves, which SQLx explicitly does not do
139/// (see [the FAQ][faq-parse-sql] for the reasoning).
140///
141/// For any bind parameter, both `T` and `Option<T>` are accepted (as well as either behind
142/// references). `Option::None` is bound as SQL `NULL`. If the target column has a `NOT NULL`
143/// constraint, binding `None` will compile successfully but fail **at runtime** with a
144/// database error, for example:
145///
146/// ```rust,ignore
147/// // Schema: `CREATE TABLE foo (data TEXT NOT NULL);`
148/// // Compiles fine, fails at runtime:
149/// sqlx::query!("INSERT INTO foo (data) VALUES ($1)", None::<String>)
150/// .execute(&pool)
151/// .await?;
152/// ```
153///
154/// If you need this kind of safety, encode the constraint in your Rust types (e.g. use `String`
155/// instead of `Option<String>` for the field that feeds the bind parameter) or cover the
156/// invariant with an integration test against a real database.
157///
158/// ### Bind parameters in `WHERE` clauses
159/// If binding in a `WHERE` clause, note that equality comparisons with `NULL` may not work
160/// as expected; instead you must use `IS NOT NULL` or `IS NULL` to check if a column is not
161/// null or is null, respectively.
162///
163/// In Postgres and MySQL you may also use `IS [NOT] DISTINCT FROM` to compare with a possibly
164/// `NULL` value. In MySQL `IS NOT DISTINCT FROM` can be shortened to `<=>`.
165/// In SQLite you can use `IS` or `IS NOT`. Note that operator precedence may be different.
166///
167/// [faq-parse-sql]: https://github.com/transact-rs/sqlx/blob/main/FAQ.md#why-cant-sqlx-just-look-at-my-database-schemamigrations-and-parse-the-sql-itself
168///
169/// ## Nullability: Output Columns
170/// In most cases, the database engine can tell us whether or not a column may be `NULL`, and
171/// the `query!()` macro adjusts the field types of the returned struct accordingly.
172///
173/// For Postgres, this only works for columns which come directly from actual tables,
174/// as the implementation will need to query the table metadata to find if a given column
175/// has a `NOT NULL` constraint. Columns that do not have a `NOT NULL` constraint or are the result
176/// of an expression are assumed to be nullable and so `Option<T>` is used instead of `T`.
177///
178/// For MySQL, the implementation looks at [the `NOT_NULL` flag](https://dev.mysql.com/doc/dev/mysql-server/8.0.12/group__group__cs__column__definition__flags.html#ga50377f5ca5b3e92f3931a81fe7b44043)
179/// of [the `ColumnDefinition` structure in `COM_QUERY_OK`](https://dev.mysql.com/doc/internals/en/com-query-response.html#column-definition):
180/// if it is set, `T` is used; if it is not set, `Option<T>` is used.
181///
182/// MySQL appears to be capable of determining the nullability of a result column even if it
183/// is the result of an expression, depending on if the expression may in any case result in
184/// `NULL` which then depends on the semantics of what functions are used. Consult the MySQL
185/// manual for the functions you are using to find the cases in which they return `NULL`.
186///
187/// For SQLite we perform a similar check to Postgres, looking for `NOT NULL` constraints
188/// on columns that come from tables. However, for SQLite we also can step through the output
189/// of `EXPLAIN` to identify columns that may or may not be `NULL`.
190///
191/// To override the nullability of an output column, [see below](#type-overrides-output-columns).
192///
193/// ## Type Overrides: Bind Parameters (Postgres only)
194/// For typechecking of bind parameters, casts using `as` are treated as overrides for the inferred
195/// types of bind parameters and no typechecking is emitted:
196///
197/// ```rust,ignore
198/// #[derive(sqlx::Type)]
199/// #[sqlx(transparent)]
200/// struct MyInt4(i32);
201///
202/// let my_int = MyInt4(1);
203///
204/// sqlx::query!("select $1::int4 as id", my_int as MyInt4)
205/// ```
206///
207/// Using `expr as _` simply signals to the macro to not type-check that bind expression,
208/// and then that syntax is stripped from the expression so as to not trigger type errors.
209///
210/// ## Type Overrides: Output Columns
211/// Type overrides are also available for output columns, utilizing the SQL standard's support
212/// for arbitrary text in column names:
213///
214/// ##### Force Not-Null
215/// Selecting a column `foo as "foo!"` (Postgres / SQLite) or `` foo as `foo!` `` (MySQL) overrides
216/// inferred nullability and forces the column to be treated as `NOT NULL`; this is useful e.g. for
217/// selecting expressions in Postgres where we cannot infer nullability:
218///
219/// ```rust,ignore
220/// # async fn main() {
221/// # let mut conn = panic!();
222/// // Postgres: using a raw query string lets us use unescaped double-quotes
223/// // Note that this query wouldn't work in SQLite as we still don't know the exact type of `id`
224/// let record = sqlx::query!(r#"select 1 as "id!""#) // MySQL: use "select 1 as `id!`" instead
225/// .fetch_one(&mut conn)
226/// .await?;
227///
228/// // For Postgres this would have been inferred to be Option<i32> instead
229/// assert_eq!(record.id, 1i32);
230/// # }
231///
232/// ```
233///
234/// ##### Force Nullable
235/// Selecting a column `foo as "foo?"` (Postgres / SQLite) or `` foo as `foo?` `` (MySQL) overrides
236/// inferred nullability and forces the column to be treated as nullable; this is provided mainly
237/// for symmetry with `!`.
238///
239/// ```rust,ignore
240/// # async fn main() {
241/// # let mut conn = panic!();
242/// // Postgres/SQLite:
243/// let record = sqlx::query!(r#"select 1 as "id?""#) // MySQL: use "select 1 as `id?`" instead
244/// .fetch_one(&mut conn)
245/// .await?;
246///
247/// // For Postgres this would have been inferred to be Option<i32> anyway
248/// // but this is just a basic example
249/// assert_eq!(record.id, Some(1i32));
250/// # }
251/// ```
252///
253/// MySQL should be accurate with regards to nullability as it directly tells us when a column is
254/// expected to never be `NULL`. Any mistakes should be considered a bug in MySQL.
255///
256/// However, inference in SQLite and Postgres is more fragile as it depends primarily on observing
257/// `NOT NULL` constraints on columns. If a `NOT NULL` column is brought in by a `LEFT JOIN` then
258/// that column may be `NULL` if its row does not satisfy the join condition. Similarly, a
259/// `FULL JOIN` or `RIGHT JOIN` may generate rows from the primary table that are all `NULL`.
260///
261/// Unfortunately, the result of mistakes in inference is a `UnexpectedNull` error at runtime.
262///
263/// In Postgres, we patch up this inference by analyzing `EXPLAIN VERBOSE` output (which is not
264/// well documented, is highly dependent on the query plan that Postgres generates, and may differ
265/// between releases) to find columns that are the result of left/right/full outer joins. This
266/// analysis errs on the side of producing false positives (marking columns nullable that are not
267/// in practice) but there are likely edge cases that it does not cover yet.
268///
269/// Using `?` as an override we can fix this for columns we know to be nullable in practice:
270///
271/// ```rust,ignore
272/// # async fn main() {
273/// # let mut conn = panic!();
274/// // Ironically this is the exact column we primarily look at to determine nullability in Postgres
275/// let record = sqlx::query!(
276/// r#"select attnotnull as "attnotnull?" from (values (1)) ids left join pg_attribute on false"#
277/// )
278/// .fetch_one(&mut conn)
279/// .await?;
280///
281/// // Although we do our best, under Postgres this might have been inferred to be `bool`
282/// // In that case, we would have gotten an error
283/// assert_eq!(record.attnotnull, None);
284/// # }
285/// ```
286///
287/// If you find that you need to use this override, please open an issue with a query we can use
288/// to reproduce the problem. For Postgres users, especially helpful would be the output of
289/// `EXPLAIN (VERBOSE, FORMAT JSON) <your query>` with bind parameters substituted in the query
290/// (as the exact value of bind parameters can change the query plan)
291/// and the definitions of any relevant tables (or sufficiently anonymized equivalents).
292///
293/// ##### Force a Different/Custom Type
294/// Selecting a column `foo as "foo: T"` (Postgres / SQLite) or `` foo as `foo: T` `` (MySQL)
295/// overrides the inferred type which is useful when selecting user-defined [custom types][crate::Type#compile-time-verification]
296/// (dynamic type checking is still done so if the types are incompatible this will be an error
297/// at runtime instead of compile-time). Note that this syntax alone doesn't override inferred nullability,
298/// but it is compatible with the forced not-null and forced nullable annotations:
299///
300/// ```rust,ignore
301/// # async fn main() {
302/// # let mut conn = panic!();
303/// #[derive(sqlx::Type)]
304/// #[sqlx(transparent)]
305/// struct MyInt4(i32);
306///
307/// let my_int = MyInt4(1);
308///
309/// // Postgres/SQLite
310/// sqlx::query!(r#"select 1 as "id!: MyInt4""#) // MySQL: use "select 1 as `id: MyInt4`" instead
311/// .fetch_one(&mut conn)
312/// .await?;
313///
314/// // For Postgres this would have been inferred to be `Option<i32>`, MySQL/SQLite `i32`
315/// // Note that while using `id: MyInt4` (without the `!`) would work the same for MySQL/SQLite,
316/// // Postgres would expect `Some(MyInt4(1))` and the code wouldn't compile
317/// assert_eq!(record.id, MyInt4(1));
318/// # }
319/// ```
320///
321/// ##### Overrides cheatsheet
322///
323/// | Syntax | Nullability | Type |
324/// | --------- | --------------- | ---------- |
325/// | `foo!` | Forced not-null | Inferred |
326/// | `foo?` | Forced nullable | Inferred |
327/// | `foo: T` | Inferred | Overridden |
328/// | `foo!: T` | Forced not-null | Overridden |
329/// | `foo?: T` | Forced nullable | Overridden |
330///
331/// ## Offline Mode
332/// The macros can be configured to not require a live database connection for compilation,
333/// but it requires a couple extra steps:
334///
335/// * Run `cargo install sqlx-cli`.
336/// * In your project with `DATABASE_URL` set (or in a `.env` file) and the database server running,
337/// run `cargo sqlx prepare`.
338/// * Check the generated `.sqlx` directory into version control.
339/// * Don't have `DATABASE_URL` set during compilation.
340///
341/// Your project can now be built without a database connection (you must omit `DATABASE_URL` or
342/// else it will still try to connect). To update the generated file simply run `cargo sqlx prepare`
343/// again.
344///
345/// To ensure that your `.sqlx` directory is kept up-to-date, both with the queries in your
346/// project and your database schema itself, run
347/// `cargo install sqlx-cli && cargo sqlx prepare --check` in your Continuous Integration script.
348///
349/// See [the README for `sqlx-cli`](https://crates.io/crates/sqlx-cli) for more information.
350///
351/// ## See Also
352/// * [`query_as!`][`crate::query_as!`] if you want to use a struct you can name,
353/// * [`query_file!`][`crate::query_file!`] if you want to define the SQL query out-of-line,
354/// * [`query_file_as!`][`crate::query_file_as!`] if you want both of the above.
355#[macro_export]
356#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
357macro_rules! query (
358 // in Rust 1.45 we can now invoke proc macros in expression position
359 ($query:expr) => ({
360 $crate::sqlx_macros::expand_query!(source = $query)
361 });
362 // RFC: this semantically should be `$($args:expr),*` (with `$(,)?` to allow trailing comma)
363 // but that doesn't work in 1.45 because `expr` fragments get wrapped in a way that changes
364 // their hygiene, which is fixed in 1.46 so this is technically just a temp. workaround.
365 // My question is: do we care?
366 // I was hoping using the `expr` fragment might aid code completion but it doesn't in my
367 // experience, at least not with IntelliJ-Rust at the time of writing (version 0.3.126.3220-201)
368 // so really the only benefit is making the macros _slightly_ self-documenting, but it's
369 // not like it makes them magically understandable at-a-glance.
370 ($query:expr, $($args:tt)*) => ({
371 $crate::sqlx_macros::expand_query!(source = $query, args = [$($args)*])
372 })
373);
374
375/// A variant of [`query!`][`crate::query!`] which does not check the input or output types. This still does parse
376/// the query to ensure it's syntactically and semantically valid for the current database.
377#[macro_export]
378#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
379macro_rules! query_unchecked (
380 ($query:expr) => ({
381 $crate::sqlx_macros::expand_query!(source = $query, checked = false)
382 });
383 ($query:expr, $($args:tt)*) => ({
384 $crate::sqlx_macros::expand_query!(source = $query, args = [$($args)*], checked = false)
385 })
386);
387
388/// A variant of [`query!`][`crate::query!`] where the SQL query is stored in a separate file.
389///
390/// Useful for large queries and potentially cleaner than multiline strings.
391///
392/// The syntax and requirements (see [`query!`][`crate::query!`]) are the same except the SQL
393/// string is replaced by a file path.
394///
395/// The file must be relative to the project root (the directory containing `Cargo.toml`),
396/// unlike `include_str!()` which uses compiler internals to get the path of the file where it
397/// was invoked.
398///
399/// -----
400///
401/// `examples/queries/account-by-id.sql`:
402/// ```text
403/// select * from (select (1) as id, 'Herp Derpinson' as name) accounts
404/// where id = ?
405/// ```
406///
407/// `src/my_query.rs`:
408/// ```rust,ignore
409/// # use sqlx::Connect;
410/// # #[cfg(all(feature = "mysql", feature = "_rt-async-std"))]
411/// # #[async_std::main]
412/// # async fn main() -> sqlx::Result<()>{
413/// # let db_url = dotenvy::var("DATABASE_URL").expect("DATABASE_URL must be set");
414/// #
415/// # if !(db_url.starts_with("mysql") || db_url.starts_with("mariadb")) { return Ok(()) }
416/// # let mut conn = sqlx::MySqlConnection::connect(db_url).await?;
417/// let account = sqlx::query_file!("tests/test-query-account-by-id.sql", 1i32)
418/// .fetch_one(&mut conn)
419/// .await?;
420///
421/// println!("{account:?}");
422/// println!("{}: {}", account.id, account.name);
423///
424/// # Ok(())
425/// # }
426/// #
427/// # #[cfg(any(not(feature = "mysql"), not(feature = "_rt-async-std")))]
428/// # fn main() {}
429/// ```
430#[macro_export]
431#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
432macro_rules! query_file (
433 ($path:literal) => ({
434 $crate::sqlx_macros::expand_query!(source_file = $path)
435 });
436 ($path:literal, $($args:tt)*) => ({
437 $crate::sqlx_macros::expand_query!(source_file = $path, args = [$($args)*])
438 })
439);
440
441/// A variant of [`query_file!`][`crate::query_file!`] which does not check the input or output
442/// types. This still does parse the query to ensure it's syntactically and semantically valid
443/// for the current database.
444#[macro_export]
445#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
446macro_rules! query_file_unchecked (
447 ($path:literal) => ({
448 $crate::sqlx_macros::expand_query!(source_file = $path, checked = false)
449 });
450 ($path:literal, $($args:tt)*) => ({
451 $crate::sqlx_macros::expand_query!(source_file = $path, args = [$($args)*], checked = false)
452 })
453);
454
455/// A variant of [`query!`][`crate::query!`] which takes a path to an explicitly defined struct
456/// as the output type.
457///
458/// This lets you return the struct from a function or add your own trait implementations.
459///
460/// **This macro does not use [`FromRow`][crate::FromRow]**; in fact, no trait implementations are
461/// required at all, though this may change in future versions.
462///
463/// The macro maps rows using a struct literal where the names of columns in the query are expected
464/// to be the same as the fields of the struct (but the order does not need to be the same).
465/// The types of the columns are based on the query and not the corresponding fields of the struct,
466/// so this is type-safe as well.
467///
468/// This enforces a few things:
469/// * The query must output at least one column.
470/// * The column names of the query must match the field names of the struct.
471/// * The field types must be the Rust equivalent of their SQL counterparts; see the corresponding
472/// module for your database for mappings:
473/// * Postgres: [crate::postgres::types]
474/// * MySQL: [crate::mysql::types]
475/// * Note: due to wire protocol limitations, the query macros do not know when
476/// a column should be decoded as `bool`. It will be inferred to be `i8` instead.
477/// See the link above for details.
478/// * SQLite: [crate::sqlite::types]
479/// * If a column may be `NULL`, the corresponding field's type must be wrapped in `Option<_>`.
480/// * Neither the query nor the struct may have unused fields.
481///
482/// The only modification to the `query!()` syntax is that the struct name is given before the SQL
483/// string:
484/// ```rust,ignore
485/// # use sqlx::Connect;
486/// # #[cfg(all(feature = "mysql", feature = "_rt-async-std"))]
487/// # #[async_std::main]
488/// # async fn main() -> sqlx::Result<()>{
489/// # let db_url = dotenvy::var("DATABASE_URL").expect("DATABASE_URL must be set");
490/// #
491/// # if !(db_url.starts_with("mysql") || db_url.starts_with("mariadb")) { return Ok(()) }
492/// # let mut conn = sqlx::MySqlConnection::connect(db_url).await?;
493/// #[derive(Debug)]
494/// struct Account {
495/// id: i32,
496/// name: String
497/// }
498///
499/// // let mut conn = <impl sqlx::Executor>;
500/// let account = sqlx::query_as!(
501/// Account,
502/// "select * from (select (1) as id, 'Herp Derpinson' as name) accounts where id = ?",
503/// 1i32
504/// )
505/// .fetch_one(&mut conn)
506/// .await?;
507///
508/// println!("{account:?}");
509/// println!("{}: {}", account.id, account.name);
510///
511/// # Ok(())
512/// # }
513/// #
514/// # #[cfg(any(not(feature = "mysql"), not(feature = "_rt-async-std")))]
515/// # fn main() {}
516/// ```
517///
518/// **The method you want to call depends on how many rows you're expecting.**
519///
520/// | Number of Rows | Method to Call* | Returns (`T` being the given struct) | Notes |
521/// |----------------| ----------------------------|----------------------------------------|-------|
522/// | Zero or One | `.fetch_optional(...).await`| `sqlx::Result<Option<T>>` | Extra rows are ignored. |
523/// | Exactly One | `.fetch_one(...).await` | `sqlx::Result<T>` | Errors if no rows were returned. Extra rows are ignored. Aggregate queries, use this. |
524/// | At Least One | `.fetch(...)` | `impl Stream<Item = sqlx::Result<T>>` | Call `.try_next().await` to get each row result. |
525/// | Multiple | `.fetch_all(...)` | `sqlx::Result<Vec<T>>` | |
526///
527/// \* All methods accept one of `&mut {connection type}`, `&mut Transaction` or `&Pool`.
528/// (`.execute()` is omitted as this macro requires at least one column to be returned.)
529///
530/// ### Column Type Override: Infer from Struct Field
531/// In addition to the column type overrides supported by [`query!`][`crate::query!`],
532/// [`query_as!()`][`crate::query_as!`] supports an
533/// additional override option:
534///
535/// If you select a column `foo as "foo: _"` (Postgres/SQLite) or `` foo as `foo: _` `` (MySQL)
536/// it causes that column to be inferred based on the type of the corresponding field in the given
537/// record struct. Runtime type-checking is still done so an error will be emitted if the types
538/// are not compatible.
539///
540/// This allows you to override the inferred type of a column to instead use a custom-defined type:
541///
542/// ```rust,ignore
543/// #[derive(sqlx::Type)]
544/// #[sqlx(transparent)]
545/// struct MyInt4(i32);
546///
547/// struct Record {
548/// id: MyInt4,
549/// }
550///
551/// let my_int = MyInt4(1);
552///
553/// // Postgres/SQLite
554/// sqlx::query_as!(Record, r#"select 1 as "id: _""#) // MySQL: use "select 1 as `id: _`" instead
555/// .fetch_one(&mut conn)
556/// .await?;
557///
558/// assert_eq!(record.id, MyInt4(1));
559/// ```
560///
561/// ### Troubleshooting: "error: mismatched types"
562/// If you get a "mismatched types" error from an invocation of this macro and the error
563/// isn't pointing specifically at a parameter.
564///
565/// For example, code like this (using a Postgres database):
566///
567/// ```rust,ignore
568/// struct Account {
569/// id: i32,
570/// name: Option<String>,
571/// }
572///
573/// let account = sqlx::query_as!(
574/// Account,
575/// r#"SELECT id, name from (VALUES (1, 'Herp Derpinson')) accounts(id, name)"#,
576/// )
577/// .fetch_one(&mut conn)
578/// .await?;
579/// ```
580///
581/// Might produce an error like this:
582/// ```text,ignore
583/// error[E0308]: mismatched types
584/// --> tests/postgres/macros.rs:126:19
585/// |
586/// 126 | let account = sqlx::query_as!(
587/// | ___________________^
588/// 127 | | Account,
589/// 128 | | r#"SELECT id, name from (VALUES (1, 'Herp Derpinson')) accounts(id, name)"#,
590/// 129 | | )
591/// | |_____^ expected `i32`, found enum `std::option::Option`
592/// |
593/// = note: expected type `i32`
594/// found enum `std::option::Option<i32>`
595/// ```
596///
597/// This means that you need to check that any field of the "expected" type (here, `i32`) matches
598/// the Rust type mapping for its corresponding SQL column (see the `types` module of your database,
599/// listed above, for mappings). The "found" type is the SQL->Rust mapping that the macro chose.
600///
601/// In the above example, the returned column is inferred to be nullable because it's being
602/// returned from a `VALUES` statement in Postgres, so the macro inferred the field to be nullable
603/// and so used `Option<i32>` instead of `i32`. **In this specific case** we could use
604/// `select id as "id!"` to override the inferred nullability because we know in practice
605/// that column will never be `NULL` and it will fix the error.
606///
607/// Nullability inference and type overrides are discussed in detail in the docs for
608/// [`query!`][`crate::query!`].
609///
610/// It unfortunately doesn't appear to be possible right now to make the error specifically mention
611/// the field; this probably requires the `const-panic` feature (still unstable as of Rust 1.45).
612#[macro_export]
613#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
614macro_rules! query_as (
615 ($out_struct:path, $query:expr) => ( {
616 $crate::sqlx_macros::expand_query!(record = $out_struct, source = $query)
617 });
618 ($out_struct:path, $query:expr, $($args:tt)*) => ( {
619 $crate::sqlx_macros::expand_query!(record = $out_struct, source = $query, args = [$($args)*])
620 })
621);
622
623/// Combines the syntaxes of [`query_as!`][`crate::query_as!`] and [`query_file!`][`crate::query_file!`].
624///
625/// Enforces requirements of both macros; see them for details.
626///
627/// ```rust,ignore
628/// # use sqlx::Connect;
629/// # #[cfg(all(feature = "mysql", feature = "_rt-async-std"))]
630/// # #[async_std::main]
631/// # async fn main() -> sqlx::Result<()>{
632/// # let db_url = dotenvy::var("DATABASE_URL").expect("DATABASE_URL must be set");
633/// #
634/// # if !(db_url.starts_with("mysql") || db_url.starts_with("mariadb")) { return Ok(()) }
635/// # let mut conn = sqlx::MySqlConnection::connect(db_url).await?;
636/// #[derive(Debug)]
637/// struct Account {
638/// id: i32,
639/// name: String
640/// }
641///
642/// // let mut conn = <impl sqlx::Executor>;
643/// let account = sqlx::query_file_as!(Account, "tests/test-query-account-by-id.sql", 1i32)
644/// .fetch_one(&mut conn)
645/// .await?;
646///
647/// println!("{account:?}");
648/// println!("{}: {}", account.id, account.name);
649///
650/// # Ok(())
651/// # }
652/// #
653/// # #[cfg(any(not(feature = "mysql"), not(feature = "_rt-async-std")))]
654/// # fn main() {}
655/// ```
656#[macro_export]
657#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
658macro_rules! query_file_as (
659 ($out_struct:path, $path:literal) => ( {
660 $crate::sqlx_macros::expand_query!(record = $out_struct, source_file = $path)
661 });
662 ($out_struct:path, $path:literal, $($args:tt)*) => ( {
663 $crate::sqlx_macros::expand_query!(record = $out_struct, source_file = $path, args = [$($args)*])
664 })
665);
666
667/// A variant of [`query_as!`][`crate::query_as!`] which does not check the input or output types. This still does parse
668/// the query to ensure it's syntactically and semantically valid for the current database.
669#[macro_export]
670#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
671macro_rules! query_as_unchecked (
672 ($out_struct:path, $query:expr) => ( {
673 $crate::sqlx_macros::expand_query!(record = $out_struct, source = $query, checked = false)
674 });
675
676 ($out_struct:path, $query:expr, $($args:tt)*) => ( {
677 $crate::sqlx_macros::expand_query!(record = $out_struct, source = $query, args = [$($args)*], checked = false)
678 })
679);
680
681/// A variant of [`query_file_as!`][`crate::query_file_as!`] which does not check the input or output types. This
682/// still does parse the query to ensure it's syntactically and semantically valid
683/// for the current database.
684#[macro_export]
685#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
686macro_rules! query_file_as_unchecked (
687 ($out_struct:path, $path:literal) => ( {
688 $crate::sqlx_macros::expand_query!(record = $out_struct, source_file = $path, checked = false)
689 });
690
691 ($out_struct:path, $path:literal, $($args:tt)*) => ( {
692 $crate::sqlx_macros::expand_query!(record = $out_struct, source_file = $path, args = [$($args)*], checked = false)
693 })
694);
695
696/// A variant of [`query!`][`crate::query!`] which expects a single column from the query and evaluates to an
697/// instance of [QueryScalar][crate::query::QueryScalar].
698///
699/// The name of the column is not required to be a valid Rust identifier, however you can still
700/// use the column type override syntax in which case the column name _does_ have to be a valid
701/// Rust identifier for the override to parse properly. If the override parse fails the error
702/// is silently ignored (we just don't have a reliable way to tell the difference). **If you're
703/// getting a different type than expected, please check to see if your override syntax is correct
704/// before opening an issue.**
705///
706/// Wildcard overrides like in [`query_as!`][`crate::query_as!`] are also allowed, in which case the output type
707/// is left up to inference.
708///
709/// See [`query!`][`crate::query!`] for more information.
710#[macro_export]
711#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
712macro_rules! query_scalar (
713 ($query:expr) => (
714 $crate::sqlx_macros::expand_query!(scalar = _, source = $query)
715 );
716 ($query:expr, $($args:tt)*) => (
717 $crate::sqlx_macros::expand_query!(scalar = _, source = $query, args = [$($args)*])
718 )
719);
720
721/// A variant of [`query_scalar!`][`crate::query_scalar!`] which takes a file path like
722/// [`query_file!`][`crate::query_file!`].
723#[macro_export]
724#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
725macro_rules! query_file_scalar (
726 ($path:literal) => (
727 $crate::sqlx_macros::expand_query!(scalar = _, source_file = $path)
728 );
729 ($path:literal, $($args:tt)*) => (
730 $crate::sqlx_macros::expand_query!(scalar = _, source_file = $path, args = [$($args)*])
731 )
732);
733
734/// A variant of [`query_scalar!`][`crate::query_scalar!`] which does not typecheck bind parameters
735/// and leaves the output type to inference.
736/// The query itself is still checked that it is syntactically and semantically
737/// valid for the database, that it only produces one column and that the number of bind parameters
738/// is correct.
739///
740/// For this macro variant the name of the column is irrelevant.
741#[macro_export]
742#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
743macro_rules! query_scalar_unchecked (
744 ($query:expr) => (
745 $crate::sqlx_macros::expand_query!(scalar = _, source = $query, checked = false)
746 );
747 ($query:expr, $($args:tt)*) => (
748 $crate::sqlx_macros::expand_query!(scalar = _, source = $query, args = [$($args)*], checked = false)
749 )
750);
751
752/// A variant of [`query_file_scalar!`][`crate::query_file_scalar!`] which does not typecheck bind
753/// parameters and leaves the output type to inference.
754/// The query itself is still checked that it is syntactically and
755/// semantically valid for the database, that it only produces one column and that the number of
756/// bind parameters is correct.
757///
758/// For this macro variant the name of the column is irrelevant.
759#[macro_export]
760#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
761macro_rules! query_file_scalar_unchecked (
762 ($path:literal) => (
763 $crate::sqlx_macros::expand_query!(scalar = _, source_file = $path, checked = false)
764 );
765 ($path:literal, $($args:tt)*) => (
766 $crate::sqlx_macros::expand_query!(scalar = _, source_file = $path, args = [$($args)*], checked = false)
767 )
768);
769
770#[allow(clippy::needless_doctest_main)]
771/// Embeds migrations into the binary by expanding to a static instance of [Migrator][crate::migrate::Migrator].
772///
773/// ```rust,ignore
774/// // Consider instead setting
775/// sqlx::migrate!("db/migrations")
776/// .run(&pool)
777/// .await?;
778/// ```
779///
780/// ```rust,ignore
781/// use sqlx::migrate::Migrator;
782///
783/// static MIGRATOR: Migrator = sqlx::migrate!(); // defaults to "./migrations"
784/// ```
785///
786/// The directory must be relative to the project root (the directory containing `Cargo.toml`),
787/// unlike `include_str!()` which uses compiler internals to get the path of the file where it
788/// was invoked.
789///
790/// See [MigrationSource][crate::migrate::MigrationSource] for details on structure of the ./migrations directory.
791///
792/// ## Note: Platform-specific Line Endings
793/// Different platforms use different bytes for line endings by default:
794/// * Linux and MacOS use Line Feeds (LF:`\n`)
795/// * Windows uses Carriage Returns _and_ Line Feeds (CRLF:'\r\n')
796///
797/// This may result in un-reproducible hashes across platforms unless taken into account.
798///
799/// One solution is to use a [`.gitattributes` file](https://git-scm.com/docs/gitattributes)
800/// and force `.sql` files to be checked out with Line Feeds:
801///
802/// ```gitattributes
803/// *.sql text eol=lf
804/// ```
805///
806/// Another option is to configure migrations to ignore whitespace.
807/// See the next section for details.
808///
809/// ## Configuration with `sqlx.toml`
810/// Multiple crate-wide configuration options are now available, including:
811///
812/// * creating schemas on database setup
813/// * renaming the `_sqlx_migrations` table or placing it into a new schema
814/// * relocating the migrations directory
815/// * ignoring characters for hashing (such as whitespace and newlines)
816///
817/// See the [configuration guide] and [reference `sqlx.toml`] for details.
818///
819/// `sqlx-cli` can also read these options and use them when setting up or migrating databases.
820///
821/// [configuration guide]: crate::_config::migrate::Config
822/// [reference `sqlx.toml`]: crate::_config::_reference
823///
824/// ## Triggering Recompilation on Migration Changes
825/// In some cases when making changes to embedded migrations, such as adding a new migration without
826/// changing any Rust source files, you might find that `cargo build` doesn't actually do anything,
827/// or when you do `cargo run` your application isn't applying new migrations on startup.
828///
829/// This is because our ability to tell the compiler to watch external files for changes
830/// from a proc-macro is very limited. The compiler by default only re-runs proc macros when
831/// one or more source files have changed, because normally it shouldn't have to otherwise. SQLx is
832/// just weird in that external factors can change the output of proc macros, much to the chagrin of
833/// the compiler team and IDE plugin authors.
834///
835/// As of 0.5.6, we emit `include_str!()` with an absolute path for each migration, but that
836/// only works to get the compiler to watch _existing_ migration files for changes.
837///
838/// Our only options for telling it to watch the whole `migrations/` directory are either via the
839/// user creating a Cargo build script in their project, or using an unstable API on nightly
840/// governed by a `cfg`-flag.
841///
842/// ##### Stable Rust: Cargo Build Script
843/// The only solution on stable Rust right now is to create a Cargo build script in your project
844/// and have it print `cargo:rerun-if-changed=migrations`:
845///
846/// `build.rs`
847/// ```no_run
848/// fn main() {
849/// println!("cargo:rerun-if-changed=migrations");
850/// }
851/// ```
852///
853/// You can run `sqlx migrate build-script` to generate this file automatically.
854///
855/// See: [The Cargo Book: 3.8 Build Scripts; Outputs of the Build Script](https://doc.rust-lang.org/stable/cargo/reference/build-scripts.html#outputs-of-the-build-script)
856///
857/// #### Nightly Rust: `cfg` Flag
858/// The `migrate!()` macro also listens to `--cfg sqlx_macros_unstable`, which will enable
859/// the `track_path` feature to directly tell the compiler to watch the `migrations/` directory:
860///
861/// ```sh,ignore
862/// $ env RUSTFLAGS='--cfg sqlx_macros_unstable' cargo build
863/// ```
864///
865/// Note that this unfortunately will trigger a fully recompile of your dependency tree, at least
866/// for the first time you use it. It also, of course, requires using a nightly compiler.
867///
868/// You can also set it in `build.rustflags` in `.cargo/config.toml`:
869/// ```toml,ignore
870/// [build]
871/// rustflags = ["--cfg=sqlx_macros_unstable"]
872/// ```
873///
874/// And then continue building and running your project normally.
875///
876/// If you're building on nightly anyways, it would be extremely helpful to help us test
877/// this feature and find any bugs in it.
878///
879/// Subscribe to [the `track_path` tracking issue](https://github.com/rust-lang/rust/issues/73921)
880/// for discussion and the future stabilization of this feature.
881///
882/// For brevity and because it involves the same commitment to unstable features in `proc_macro`,
883/// if you're using `--cfg procmacro2_semver_exempt` it will also enable this feature
884/// (see [`proc-macro2` docs / Unstable Features](https://docs.rs/proc-macro2/1.0.27/proc_macro2/#unstable-features)).
885#[cfg(feature = "migrate")]
886#[macro_export]
887macro_rules! migrate {
888 ($dir:literal) => {{
889 $crate::sqlx_macros::migrate!($dir)
890 }};
891
892 () => {{
893 $crate::sqlx_macros::migrate!()
894 }};
895}