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