Debian Codegraph @

FAQ.md

raw symbols SCIP
1 SQLx Frequently Asked Questions
2 ===============================
3
4 ### What database versions does SQLx support?
5
6 This is a difficult question to answer because it depends on which features of the databases are used and when those features were introduced. SQL databases tend to be very strongly backwards-compatible so it's likely that SQLx will work with some very old versions.
7
8 TLS support is one of the features that ages most quickly with databases, since old SSL/TLS versions are deprecated over time as they become insecure due to weaknesses being discovered; this is especially important to consider when using RusTLS, as it only supports the latest TLS version for security reasons (see the question below mentioning RusTLS for details).
9
10 As a rule, however, we only officially support the range of versions for each database that are still actively maintained, and will drop support for versions as they reach their end-of-life.
11
12 * Postgres has a page to track these versions and give their end-of-life dates: https://www.postgresql.org/support/versioning/
13 * MariaDB has a similar list here (though it doesn't show the dates at which old versions were EOL'd): https://mariadb.com/kb/en/mariadb-server-release-dates/
14 * MySQL's equivalent page is more concerned with what platforms are supported by the newest and oldest maintained versions: https://www.mysql.com/support/supportedplatforms/database.html
15 * However, its Wikipedia page helpfully tracks its versions and their announced EOL dates: https://en.wikipedia.org/wiki/MySQL#Release_history
16 * SQLite is easy as only SQLite 3 is supported and the current version depends on the version of the `libsqlite3-sys` crate being used.
17
18 For each database and where applicable, we test against the latest and oldest versions that we intend to support. You can see the current versions being tested against by looking at our CI config: https://github.com/launchbadge/sqlx/blob/main/.github/workflows/sqlx.yml#L168
19
20 -------------------------------------------------------------------
21 ### What versions of Rust does SQLx support? What is SQLx's MSRV\*?
22
23 SQLx's MSRV is the second-to-latest stable release as of the beginning of the current release cycle (`0.x.0`).
24 It will remain there until the next major release (`0.{x + 1}.0`).
25
26 For example, as of the `0.8.0` release of SQLx, the latest stable Rust version was `1.79.0`, so the MSRV for the
27 `0.8.x` release cycle of SQLx is `1.78.0`.
28
29 This guarantees that SQLx will compile with a Rust version that is _at least_ six weeks old, which should be plenty
30 of time for it to make it through any packaging system that is being actively kept up to date.
31
32 We do _not_ recommend installing Rust through operating system packages,
33 as they can often be a whole year or more out-of-date.
34
35 \*Minimum Supported Rust Version
36
37 [`rust-version`]: https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-rust-version-field
38
39 ----------------------------------------------------------------
40 ### I'm getting `HandshakeFailure` or `CorruptMessage` when trying to connect to a server over TLS using RusTLS. What gives?
41
42 To encourage good security practices and limit cruft, RusTLS does not support older versions of TLS or cryptographic algorithms
43 that are considered insecure. `HandshakeFailure` is a normal error returned when RusTLS and the server cannot agree on parameters for
44 a secure connection.
45
46 Check the supported TLS versions for the database server version you're running. If it does not support TLS 1.2 or greater, then
47 you likely will not be able to connect to it with RusTLS.
48
49 The ideal solution, of course, is to upgrade your database server to a version that supports at least TLS 1.2.
50
51 * MySQL: [has supported TLS 1.2 since 5.6.46](https://dev.mysql.com/doc/refman/5.6/en/encrypted-connection-protocols-ciphers.html#encrypted-connection-supported-protocols).
52 * PostgreSQL: depends on the system OpenSSL version.
53 * MSSQL: TLS is not supported yet.
54
55 If you're running a third-party database that talks one of these protocols, consult its documentation for supported TLS versions.
56
57 If you're stuck on an outdated version, which is unfortunate but tends to happen for one reason or another, try switching to the corresponding
58 `runtime-<tokio, async-std, actix>-native-tls` feature for SQLx. That will use the system APIs for TLS which tend to have much wider support.
59 See [the `native-tls` crate docs](https://docs.rs/native-tls/latest/native_tls/) for details.
60
61 The `CorruptMessage` error occurs in similar situations and many users have had success with switching to `-native-tls` to get around it.
62 However, if you do encounter this error, please try to capture a Wireshark or `tcpdump` trace of the TLS handshake as the RusTLS folks are interested
63 in covering cases that trigger this (as it might indicate a protocol handling bug or the server is doing something non-standard):
64 https://github.com/rustls/rustls/issues/893
65
66 ----------------------------------------------------------------
67 ### How does SQLx help prevent SQL Injection?
68 ### How do Query Parameters work?
69 ### Why does SQLx use Prepared Statements for most queries?
70 ### Can I Use Query Parameters to add conditional SQL to my query?
71 ### Why can't I use DDL (e.g. `CREATE TABLE`, `ALTER TABLE`, etc.) with the `sqlx::query*()` functions or `sqlx::query*!()` macros?
72
73 These questions can all be answered by a thorough explanation of prepared statements. Feel free to skip the parts you already know.
74
75 Back in the day, if a web application wanted to include user input in a SQL query,
76 a search parameter for example, it had no choice but to simply format that data into the query.
77 PHP applications used to be full of snippets like this:
78
79 ```php
80 /* Imagine this is user input */
81 $city = "Munich";
82
83 /* $query = "SELECT country FROM city WHERE name='Munich'" */
84 $query = sprintf("SELECT country FROM city WHERE name='%s'", $city);
85 $result = $mysqli->query($query);
86 ```
87
88 However, this leaves the application vulnerable to [SQL injection attacks](https://en.wikipedia.org/wiki/SQL_injection),
89 because it's trivial to craft an input string that will terminate the existing query and begin a new one,
90 and the database won't know the difference and will execute both. As illustrated in the famous XKCD #327:
91
92 <a href="https://xkcd.com/327/"><img src="https://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="Her daughter is named Help I'm trapped in a driver's license factory." alt="Exploits of a Mom" srcset="https:////imgs.xkcd.com/comics/exploits_of_a_mom_2x.png 2x" style="image-orientation:none">
93
94 The fictional school's student database application might have contained a query that looked like this:
95 ```php
96 $student_name = "Robert');DROP TABLE Students;--"
97
98 $query = sprintf("INSERT INTO Students (name) VALUES ('%s')", $student_name);
99 $result = $mysqli->query($query);
100 ```
101
102 When formatted into the middle of this query, the maliciously crafted input string closes the quotes and finishes the statement (`Robert');`),
103 then starts another one with the nefarious payload (`DROP TABLE Students;`), and causes the rest of the original query to be ignored by starting a SQL comment (`--`).
104 Thus, the database server sees, and executes, three separate statements like so:
105
106 ```SQL
107 INSERT INTO Students(firstname) VALUES ('Robert');
108 DROP TABLE Students;
109 --');
110 ```
111
112 And thus the school has lost this year's student records (at least they had last years' backed up?).
113
114 The original mitigation for this attack was to make sure that any untrustworthy user input was properly escaped (or "sanitized"),
115 and many frameworks provided utility functions for this, such as PHP's [`mysqli::real_escape_string()`](https://www.php.net/manual/en/mysqli.real-escape-string.php) (not to be confused with the obsolete [`mysql_real_escape_string()`](https://www.php.net/manual/en/function.mysql-real-escape-string) or [`mysql_escape_string()`](https://www.php.net/manual/en/function.mysql-escape-string.php)).
116
117 These would prefix any syntactically significant characters (in this case, quotation marks) with a backslash,
118 so it's less likely to affect the database server's interpretation of the query:
119
120 ```php
121 $student_name = $mysqli->real_escape_string("Robert');DROP TABLE Students;--");
122
123 /*
124 Everything is okay now as the dastardly single-quote has been inactivated by the backslash:
125 "INSERT INTO Students (name) VALUES ('Robert\');DROP TABLE Students;--');"
126 */
127 $query = sprintf("INSERT INTO Students (name) VALUES ('%s')", $student_name);
128 ```
129
130 The database server sees the backslash and knows that the single-quote is part of the string content, not its terminating character.
131
132 However, this was something that you still had to _remember_ to do, making it only half a solution. Additionally, properly escaping the string requires knowledge of the current character set of the connection which is why the `mysqli` object is a required parameter
133 (or the receiver in object-oriented style). And you could always just forget to wrap the string parameter in quotes (`'%s'`) in the first place, which these wouldn't help with.
134
135 Even when everything is working correctly, formatting dynamic data into a query still requires the database server to
136 re-parse and generate a new query plan with every new variant--caching helps, but is not a silver bullet.
137
138 #### Prepared Statements to the rescue!
139
140 These solve both problems (injection and re-parsing) by **completely separating** the query from any dynamic input data.
141
142 Instead of formatting data into the query, you use a (database-specific) token to signify a value that will be passed separately:
143
144 ```SQL
145 -- MySQL
146 INSERT INTO Students (name) VALUES(?);
147 -- Postgres and SQLite
148 INSERT INTO Students (name) VALUES($1);
149 ```
150
151 The database will substitute a given value when _executing_ the query, long after it's finished parsing it.
152 The database will effectively treat the parameter as a variable.
153 There is, by design, **no way** for a query parameter to modify the SQL of a query,
154 unless you're using some `exec()`-like SQL function that lets you execute a string as a query,
155 but then hopefully you know what you're doing.
156
157 In fact, parsing and executing prepared statements are explicitly separate steps in pretty much every database's protocol,
158 where the query string, without any values attached, is parsed first and given an identifier, then a separate execution step
159 simply passes that identifier along with the values to substitute.
160
161 The response from the initial parsing often contains useful metadata about the query, which SQLx's query macros use to great effect
162 (see "How do the query macros work under the hood?" below).
163
164 Unfortunately, query parameters do not appear to be standardized, as every database has a different syntax.
165 Look through the project for specific examples for your database, and consult your database manual about prepared statements
166 for more information.
167
168 The syntax SQLite supports is effectively a superset of many databases' syntaxes, including MySQL and Postgres.
169 To simplify our examples, we use the same syntax for Postgres and SQLite; though SQLite's syntax technically allows
170 alphanumeric identifiers, that's not currently exposed in SQLx, and it's expected to be a numeric 1-based index like Postgres.
171
172 Some databases, like MySQL and PostgreSQL, may have special statements that let the user explicitly create and execute prepared statements (often `PREPARE` and `EXECUTE`, respectively),
173 but most of the time an application, or library like SQLx, will interact with prepared statements using specialized messages in the database's client/server protocol.
174 Prepared statements created through this protocol may or may not be accessible using explicit SQL statements, depending on the database flavor.
175
176 Since the dynamic data is handled separately, an application only needs to prepare a statement once,
177 and then it can execute it as many times as it wants with all kinds of different data (at least of the same type and number).
178 Prepared statements are generally tracked per-connection, so an application may need to re-prepare a statement several times over its lifetime as it opens new connections.
179 If it uses a connection pool, ideally all connections will eventually have all statements already prepared (assuming a closed set of statements),
180 so the overhead of parsing and generating a query plan is amortized.
181
182 Query parameters are also usually transmitted in a compact binary format, which saves bandwidth over having to send them as human-readable strings.
183
184 Because of the obvious security and performance benefits of prepared statements, the design of SQLx tries to make them as easy to use and transparent as possible.
185 The `sqlx::query*()` family of functions, as well as the `sqlx::query*!()` macros, will always prefer prepared statements. This was an explicit goal from day one.
186
187 SQLx will **never** substitute query parameters for values on the client-side, it will always let the database server handle that. We have concepts for making certain usage patterns easier,
188 like expanding a dynamic list of parameters (e.g. `?, ?, ?, ?, ...`) since MySQL and SQLite don't really support arrays, but will never simply format data into a query implicitly.
189
190 Our pervasive use of prepared statements can cause some problems with third-party database implementations, e.g. projects like CockroachDB or PGBouncer that support the Postgres protocol but have their own semantics.
191 In this case, you might try setting [`.persistent(false)`](https://docs.rs/sqlx/latest/sqlx/query/struct.Query.html#method.persistent) before executing a query, which will cause the connection not to retain
192 the prepared statement after executing it.
193
194 Not all SQL statements are allowed in prepared statements, either.
195 As a general rule, DML (Data Manipulation Language, i.e. `SELECT`, `INSERT`, `UPDATE`, `DELETE`) is allowed while DDL (Data Definition Language, e.g. `CREATE TABLE`, `ALTER TABLE`, etc.) is not.
196 Consult your database manual for details.
197
198 To execute DDL requires using a different API than `query*()` or `query*!()` in SQLx.
199 Ideally, we'd like to encourage you to use SQLx's built-in support for migrations (though that could be better documented, we'll get to it).
200 However, in the event that isn't feasible, or you have different needs, you can execute pretty much any statement,
201 including multiple statements separated by semicolons (`;`), by directly invoking methods of the [`Executor` trait](https://docs.rs/sqlx/latest/sqlx/trait.Executor.html#method.execute)
202 on any type that implements it, and passing your query string, e.g.:
203
204 ```rust
205 use sqlx::postgres::PgConnection;
206 use sqlx::Executor;
207
208 let mut conn: PgConnection = connect().await?;
209
210 conn
211 .execute(
212 "CREATE TABLE IF NOT EXISTS StudentContactInfo (student_id INTEGER, person_name TEXT, relation TEXT, phone TEXT);\
213 INSERT INTO StudentContactInfo (student_id, person_name, relation, phone) \
214 SELECT student_id, guardian_name, guardian_relation, guardian_phone FROM Students;\
215 ALTER TABLE Students DROP guardian_name, guardian_relation, guardian_phone;"
216 )
217 .await?;
218 ```
219
220 This is also pending a redesign to make it easier to discover and utilize.
221
222 ----------------------------------------------------------------
223 ### How can I do a `SELECT ... WHERE foo IN (...)` query?
224
225
226 In the future SQLx will support binding arrays as a comma-separated list for every database,
227 but unfortunately there's no general solution for that currently in SQLx itself.
228 You would need to manually generate the query, at which point it
229 cannot be used with the macros.
230
231 However, **in Postgres** you can work around this limitation by binding the arrays directly and using `= ANY()`:
232
233 ```rust
234 let db: PgPool = /* ... */;
235 let foo_ids: Vec<i64> = vec![/* ... */];
236
237 let foos = sqlx::query!(
238 "SELECT * FROM foo WHERE id = ANY($1)",
239 // a bug of the parameter typechecking code requires all array parameters to be slices
240 &foo_ids[..]
241 )
242 .fetch_all(&db)
243 .await?;
244 ```
245
246 Even when SQLx gains generic placeholder expansion for arrays, this will still be the optimal way to do it for Postgres,
247 as comma-expansion means each possible length of the array generates a different query
248 (and represents a combinatorial explosion if more than one array is used).
249
250 Note that you can use any operator that returns a boolean, but beware that `!= ANY($1)` is **not equivalent** to `NOT IN (...)` as it effectively works like this:
251
252 `lhs != ANY(rhs) -> false OR lhs != rhs[0] OR lhs != rhs[1] OR ... lhs != rhs[length(rhs) - 1]`
253
254 The equivalent of `NOT IN (...)` would be `!= ALL($1)`:
255
256 `lhs != ALL(rhs) -> true AND lhs != rhs[0] AND lhs != rhs[1] AND ... lhs != rhs[length(rhs) - 1]`
257
258 Note that `ANY` using any operator and passed an empty array will return `false`, thus the leading `false OR ...`.
259 Meanwhile, `ALL` with any operator and passed an empty array will return `true`, thus the leading `true AND ...`.
260
261 See also: [Postgres Manual, Section 9.24: Row and Array Comparisons](https://www.postgresql.org/docs/current/functions-comparisons.html)
262
263 -----
264 ### How can I bind an array to a `VALUES()` clause? How can I do bulk inserts?
265
266 Like the above, SQLx currently does not support this in the general case right now but will in the future.
267
268 However, **Postgres** also has a feature to save the day here! You can pass an array to `UNNEST()` and
269 it will treat it as a temporary table:
270
271 ```rust
272 let foo_texts: Vec<String> = vec![/* ... */];
273
274 sqlx::query!(
275 // because `UNNEST()` is a generic function, Postgres needs the cast on the parameter here
276 // in order to know what type to expect there when preparing the query
277 "INSERT INTO foo(text_column) SELECT * FROM UNNEST($1::text[])",
278 &foo_texts[..]
279 )
280 .execute(&db)
281 .await?;
282 ```
283
284 `UNNEST()` can also take more than one array, in which case it'll treat each array as a column in the temporary table:
285
286 ```rust
287 // this solution currently requires each column to be its own vector
288 // in the future we're aiming to allow binding iterators directly as arrays
289 // so you can take a vector of structs and bind iterators mapping to each field
290 let foo_texts: Vec<String> = vec![/* ... */];
291 let foo_bools: Vec<bool> = vec![/* ... */];
292 let foo_ints: Vec<i64> = vec![/* ... */];
293 let foo_opt_texts: Vec<Option<String>> = vec![/* ... */];
294 let foo_opt_naive_dts: Vec<Option<NaiveDateTime>> = vec![/* ... */]
295
296
297 sqlx::query!(
298 "
299 INSERT INTO foo(text_column, bool_column, int_column, opt_text_column, opt_naive_dt_column)
300 SELECT * FROM UNNEST($1::text[], $2::bool[], $3::int8[], $4::text[], $5::timestamp[])
301 ",
302 &foo_texts[..],
303 &foo_bools[..],
304 &foo_ints[..],
305 // Due to a limitation in how SQLx typechecks query parameters, `Vec<Option<T>>` is unable to be typechecked.
306 // This demonstrates the explicit type override syntax, which tells SQLx not to typecheck these parameters.
307 // See the documentation for `query!()` for more details.
308 &foo_opt_texts as &[Option<String>],
309 &foo_opt_naive_dts as &[Option<NaiveDateTime>]
310 )
311 .execute(&db)
312 .await?;
313 ```
314
315 Again, even with comma-expanded lists in the future this will likely still be the most performant way to run bulk inserts
316 with Postgres--at least until we get around to implementing an interface for `COPY FROM STDIN`, though
317 this solution with `UNNEST()` will still be more flexible as you can use it in queries that are more complex
318 than just inserting into a table.
319
320 Note that if some vectors are shorter than others, `UNNEST` will fill the corresponding columns with `NULL`s
321 to match the longest vector.
322
323 For example, if `foo_texts` is length 5, `foo_bools` is length 4, `foo_ints` is length 3, the resulting table will
324 look like this:
325
326 | Row # | `text_column` | `bool_column` | `int_column` |
327 | ----- | -------------- | -------------- | ------------- |
328 | 1 | `foo_texts[0]` | `foo_bools[0]` | `foo_ints[0]` |
329 | 2 | `foo_texts[1]` | `foo_bools[1]` | `foo_ints[1]` |
330 | 3 | `foo_texts[2]` | `foo_bools[2]` | `foo_ints[2]` |
331 | 4 | `foo_texts[3]` | `foo_bools[3]` | `NULL` |
332 | 5 | `foo_texts[4]` | `NULL` | `NULL` |
333
334 See Also:
335 * [Postgres Manual, Section 7.2.1.4: Table Functions](https://www.postgresql.org/docs/current/queries-table-expressions.html#QUERIES-TABLEFUNCTIONS)
336 * [Postgres Manual, Section 9.19: Array Functions and Operators](https://www.postgresql.org/docs/current/functions-array.html)
337
338 ----
339 ### How do I compile with the macros without needing a database, e.g. in CI?
340
341 The macros support an offline mode which saves data for existing queries to a `.sqlx` directory,
342 so the macros can just read those instead of talking to a database.
343
344 See the following:
345
346 * [the docs for `query!()`](https://docs.rs/sqlx/0.5.5/sqlx/macro.query.html#offline-mode-requires-the-offline-feature)
347 * [the README for `sqlx-cli`](sqlx-cli/README.md#enable-building-in-offline-mode-with-query)
348
349 To keep `.sqlx` up-to-date you need to run `cargo sqlx prepare` before every commit that
350 adds or changes a query; you can do this with a Git pre-commit hook:
351
352 ```shell
353 $ echo "cargo sqlx prepare > /dev/null 2>&1; git add .sqlx > /dev/null" > .git/hooks/pre-commit
354 ```
355
356 Note that this may make committing take some time as it'll cause your project to be recompiled, and
357 as an ergonomic choice it does _not_ block committing if `cargo sqlx prepare` fails.
358
359 We're working on a way for the macros to save their data to the filesystem automatically which should be part of SQLx 0.7,
360 so your pre-commit hook would then just need to stage the changed files. This can be enabled by creating a directory
361 and setting the `SQLX_OFFLINE_DIR` environment variable to it before compiling.
362 However, this behaviour is not considered stable and it is still recommended to use `cargo sqlx prepare`.
363
364 ----
365
366 ### How do the query macros work under the hood?
367
368 The macros work by talking to the database at compile time. When a(n) SQL client asks to create a prepared statement
369 from a query string, the response from the server typically includes information about the following:
370
371 * the number of bind parameters, and their expected types if the database is capable of inferring that
372 * the number, names and types of result columns, as well as the original table and columns names before aliasing
373
374 In MySQL/MariaDB, we also get boolean flag signaling if a column is `NOT NULL`, however
375 in Postgres and SQLite, we need to do a bit more work to determine whether a column can be `NULL` or not.
376
377 After preparing, the Postgres driver will first look up the result columns in their source table and check if they have
378 a `NOT NULL` constraint. Then, it will execute `EXPLAIN (VERBOSE, FORMAT JSON) <your query>` to determine which columns
379 come from half-open joins (LEFT and RIGHT joins), which makes a normally `NOT NULL` column nullable. Since the
380 `EXPLAIN VERBOSE` format is not stable or completely documented, this inference isn't perfect. However, it does err on
381 the side of producing false-positives (marking a column nullable when it's `NOT NULL`) to avoid errors at runtime.
382
383 If you do encounter false-positives please feel free to open an issue; make sure to include your query, any relevant
384 schema as well as the output of `EXPLAIN (VERBOSE, FORMAT JSON) <your query>` which will make this easier to debug.
385
386 The SQLite driver will pull the bytecode of the prepared statement and step through it to find any instructions
387 that produce a null value for any column in the output.
388
389 ---
390 ### Why can't SQLx just look at my database schema/migrations and parse the SQL itself?
391
392 Take a moment and think of the effort that would be required to do that.
393
394 To implement this for a single database driver, SQLx would need to:
395
396 * know how to parse SQL, and not just standard SQL but the specific dialect of that particular database
397 * know how to analyze and typecheck SQL queries in the context of the original schema
398 * if inferring schema from migrations it would need to simulate all the schema-changing effects of those migrations
399
400 This is effectively reimplementing a good chunk of the database server's frontend,
401
402 _and_ maintaining and ensuring correctness of that reimplementation,
403
404 including bugs and idiosyncrasies,
405
406 for the foreseeable future,
407
408 for _every_ database we intend to support.
409
410 Even Sisyphus would pity us.
411
412 ----
413
414 ### Why does my project using sqlx query macros not build on docs.rs?
415
416 Docs.rs doesn't have access to your database, so it needs to be provided prepared queries in a `.sqlx` directory and be instructed to set the `SQLX_OFFLINE` environment variable to true while compiling your project. Luckily for us, docs.rs creates a `DOCS_RS` environment variable that we can access in a custom build script to achieve this functionality.
417
418 To do so, first, make sure that you have run `cargo sqlx prepare` to generate a `.sqlx` directory in your project.
419
420 Next, create a file called `build.rs` in the root of your project directory (at the same level as `Cargo.toml`). Add the following code to it:
421 ```rs
422 fn main() {
423 // When building in docs.rs, we want to set SQLX_OFFLINE mode to true
424 if std::env::var_os("DOCS_RS").is_some() {
425 println!("cargo:rustc-env=SQLX_OFFLINE=true");
426 }
427 }
428 ```