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