Debian Codegraph @

README.md

raw symbols SCIP
1 <h1 align="center">SQLx</h1>
2 <div align="center">
3 <strong>
4 🧰 The Rust SQL Toolkit
5 </strong>
6 </div>
7
8 <br />
9
10 <div align="center">
11 <!-- Github Actions -->
12 <a href="https://github.com/launchbadge/sqlx/actions/workflows/sqlx.yml?query=branch%3Amain">
13 <img src="https://img.shields.io/github/actions/workflow/status/launchbadge/sqlx/sqlx.yml?branch=main&style=flat-square" alt="actions status" /></a>
14 <!-- Version -->
15 <a href="https://crates.io/crates/sqlx">
16 <img src="https://img.shields.io/crates/v/sqlx.svg?style=flat-square"
17 alt="Crates.io version" /></a>
18 <!-- Discord -->
19 <a href="https://discord.gg/uuruzJ7">
20 <img src="https://img.shields.io/discord/665528275556106240?style=flat-square" alt="chat" /></a>
21 <!-- Docs -->
22 <a href="https://docs.rs/sqlx">
23 <img src="https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square" alt="docs.rs docs" /></a>
24 <!-- Downloads -->
25 <a href="https://crates.io/crates/sqlx">
26 <img src="https://img.shields.io/crates/d/sqlx.svg?style=flat-square" alt="Download" />
27 </a>
28 </div>
29
30 <div align="center">
31 <h4>
32 <a href="#install">
33 Install
34 </a>
35 <span> | </span>
36 <a href="#usage">
37 Usage
38 </a>
39 <span> | </span>
40 <a href="https://docs.rs/sqlx">
41 Docs
42 </a>
43 <span> | </span>
44 <a href="https://github.com/launchbadge/sqlx/wiki/Ecosystem">
45 Ecosystem
46 </a>
47 <span> | </span>
48 <a href="https://discord.gg/uuruzJ7">
49 Discord
50 </a>
51 </h4>
52 </div>
53
54 <br />
55
56 <div align="center">
57 <small>Built with ❤️ by <a href="https://launchbadge.com">The LaunchBadge team</a></small>
58 </div>
59
60 <br />
61
62 <div align="center">
63 <h5>Have a question? Be sure to <a href="FAQ.md">check the FAQ first!</a></h5>
64 </div>
65
66 <br />
67
68 SQLx is an async, pure Rust<sub>†</sub> SQL crate featuring compile-time checked queries without a DSL.
69
70 - **Truly Asynchronous**. Built from the ground-up using async/await for maximum concurrency.
71
72 - **Compile-time checked queries** (if you want). See [SQLx is not an ORM](#sqlx-is-not-an-orm).
73
74 - **Database Agnostic**. Support for [PostgreSQL], [MySQL], [MariaDB], [SQLite].
75 - [MSSQL] was supported prior to version 0.7, but has been removed pending a full rewrite of the driver as part of our [SQLx Pro initiative].
76
77 - **Pure Rust**. The Postgres and MySQL/MariaDB drivers are written in pure Rust using **zero** unsafe<sub>††</sub> code.
78
79 - **Runtime Agnostic**. Works on different runtimes ([`async-std`] / [`tokio`] / [`actix`]) and TLS backends ([`native-tls`], [`rustls`]).
80
81 <small><small>
82
83 † The SQLite driver uses the libsqlite3 C library as SQLite is an embedded database (the only way
84 we could be pure Rust for SQLite is by porting _all_ of SQLite to Rust).
85
86 †† SQLx uses `#![forbid(unsafe_code)]` unless the `sqlite` feature is enabled.
87 The SQLite driver directly invokes the SQLite3 API via `libsqlite3-sys`, which requires `unsafe`.
88
89 </small></small>
90
91 [postgresql]: http://postgresql.org/
92 [sqlite]: https://sqlite.org/
93 [mysql]: https://www.mysql.com/
94 [mariadb]: https://www.mariadb.org/
95 [mssql]: https://www.microsoft.com/en-us/sql-server
96 [SQLx Pro initiative]: https://github.com/launchbadge/sqlx/discussions/1616
97
98 ---
99
100 - Cross-platform. Being native Rust, SQLx will compile anywhere Rust is supported.
101
102 - Built-in connection pooling with `sqlx::Pool`.
103
104 - Row streaming. Data is read asynchronously from the database and decoded on demand.
105
106 - Automatic statement preparation and caching. When using the high-level query API (`sqlx::query`), statements are
107 prepared and cached per connection.
108
109 - Simple (unprepared) query execution including fetching results into the same `Row` types used by
110 the high-level API. Supports batch execution and returns results from all statements.
111
112 - Transport Layer Security (TLS) where supported ([MySQL], [MariaDB] and [PostgreSQL]).
113
114 - Asynchronous notifications using `LISTEN` and `NOTIFY` for [PostgreSQL].
115
116 - Nested transactions with support for save points.
117
118 - `Any` database driver for changing the database driver at runtime. An `AnyPool` connects to the driver indicated by the URL scheme.
119
120 ## Install
121
122 SQLx is compatible with the [`async-std`], [`tokio`], and [`actix`] runtimes; and, the [`native-tls`] and [`rustls`] TLS backends. When adding the dependency, you must choose a runtime feature that is `runtime` + `tls`.
123
124 [`async-std`]: https://github.com/async-rs/async-std
125 [`tokio`]: https://github.com/tokio-rs/tokio
126 [`actix`]: https://github.com/actix/actix-net
127 [`native-tls`]: https://crates.io/crates/native-tls
128 [`rustls`]: https://crates.io/crates/rustls
129
130 ```toml
131 # Cargo.toml
132 [dependencies]
133 # PICK ONE OF THE FOLLOWING:
134
135 # tokio (no TLS)
136 sqlx = { version = "0.8", features = [ "runtime-tokio" ] }
137 # tokio + native-tls
138 sqlx = { version = "0.8", features = [ "runtime-tokio", "tls-native-tls" ] }
139 # tokio + rustls with ring and WebPKI CA certificates
140 sqlx = { version = "0.8", features = [ "runtime-tokio", "tls-rustls-ring-webpki" ] }
141 # tokio + rustls with ring and platform's native CA certificates
142 sqlx = { version = "0.8", features = [ "runtime-tokio", "tls-rustls-ring-native-roots" ] }
143 # tokio + rustls with aws-lc-rs
144 sqlx = { version = "0.8", features = [ "runtime-tokio", "tls-rustls-aws-lc-rs" ] }
145
146 # async-std (no TLS)
147 sqlx = { version = "0.8", features = [ "runtime-async-std" ] }
148 # async-std + native-tls
149 sqlx = { version = "0.8", features = [ "runtime-async-std", "tls-native-tls" ] }
150 # async-std + rustls with ring and WebPKI CA certificates
151 sqlx = { version = "0.8", features = [ "runtime-async-std", "tls-rustls-ring-webpki" ] }
152 # async-std + rustls with ring and platform's native CA certificates
153 sqlx = { version = "0.8", features = [ "runtime-async-std", "tls-rustls-ring-native-roots" ] }
154 # async-std + rustls with aws-lc-rs
155 sqlx = { version = "0.8", features = [ "runtime-async-std", "tls-rustls-aws-lc-rs" ] }
156 ```
157
158 #### Cargo Feature Flags
159
160 For backward-compatibility reasons, the runtime and TLS features can either be chosen together as a single feature,
161 or separately.
162
163 For forward compatibility, you should use the separate runtime and TLS features as the combination features may
164 be removed in the future.
165
166 - `runtime-async-std`: Use the `async-std` runtime without enabling a TLS backend.
167
168 - `runtime-async-std-native-tls`: Use the `async-std` runtime and `native-tls` TLS backend (SOFT-DEPRECATED).
169
170 - `runtime-async-std-rustls`: Use the `async-std` runtime and `rustls` TLS backend (SOFT-DEPRECATED).
171
172 - `runtime-tokio`: Use the `tokio` runtime without enabling a TLS backend.
173
174 - `runtime-tokio-native-tls`: Use the `tokio` runtime and `native-tls` TLS backend (SOFT-DEPRECATED).
175
176 - `runtime-tokio-rustls`: Use the `tokio` runtime and `rustls` TLS backend (SOFT-DEPRECATED).
177
178 - Actix-web is fully compatible with Tokio and so a separate runtime feature is no longer needed.
179
180 - `tls-native-tls`: Use the `native-tls` TLS backend (OpenSSL on *nix, SChannel on Windows, Secure Transport on macOS).
181
182 - `tls-rustls`: Use the `rustls` TLS backend (cross-platform backend, only supports TLS 1.2 and 1.3).
183
184 - `postgres`: Add support for the Postgres database server.
185
186 - `mysql`: Add support for the MySQL/MariaDB database server.
187
188 - `mssql`: Add support for the MSSQL database server.
189
190 - `sqlite`: Add support for the self-contained [SQLite](https://sqlite.org/) database engine with SQLite bundled and statically-linked.
191
192 - `sqlite-unbundled`: The same as above (`sqlite`), but link SQLite from the system instead of the bundled version.
193 * Allows updating SQLite independently of SQLx or using forked versions.
194 * You must have SQLite installed on the system or provide a path to the library at build time.
195 See [the `rusqlite` README](https://github.com/rusqlite/rusqlite?tab=readme-ov-file#notes-on-building-rusqlite-and-libsqlite3-sys) for details.
196 * May result in link errors if the SQLite version is too old. Version `3.20.0` or newer is recommended.
197 * Can increase build time due to the use of bindgen.
198
199 - `any`: Add support for the `Any` database driver, which can proxy to a database driver at runtime.
200
201 - `derive`: Add support for the derive family macros, those are `FromRow`, `Type`, `Encode`, `Decode`.
202
203 - `macros`: Add support for the `query*!` macros, which allows compile-time checked queries.
204
205 - `migrate`: Add support for the migration management and `migrate!` macro, which allow compile-time embedded migrations.
206
207 - `uuid`: Add support for UUID (in Postgres).
208
209 - `chrono`: Add support for date and time types from `chrono`.
210
211 - `time`: Add support for date and time types from `time` crate (alternative to `chrono`, which is preferred by `query!` macro, if both enabled)
212
213 - `bstr`: Add support for `bstr::BString`.
214
215 - `bigdecimal`: Add support for `NUMERIC` using the `bigdecimal` crate.
216
217 - `rust_decimal`: Add support for `NUMERIC` using the `rust_decimal` crate.
218
219 - `ipnetwork`: Add support for `INET` and `CIDR` (in postgres) using the `ipnetwork` crate.
220
221 - `json`: Add support for `JSON` and `JSONB` (in postgres) using the `serde_json` crate.
222
223 - Offline mode is now always enabled. See [sqlx-cli/README.md][readme-offline].
224
225 [readme-offline]: sqlx-cli/README.md#enable-building-in-offline-mode-with-query
226
227 ## SQLx is not an ORM!
228
229 SQLx supports **compile-time checked queries**. It does not, however, do this by providing a Rust
230 API or DSL (domain-specific language) for building queries. Instead, it provides macros that take
231 regular SQL as input and ensure that it is valid for your database. The way this works is that
232 SQLx connects to your development DB at compile time to have the database itself verify (and return
233 some info on) your SQL queries. This has some potentially surprising implications:
234
235 - Since SQLx never has to parse the SQL string itself, any syntax that the development DB accepts
236 can be used (including things added by database extensions)
237 - Due to the different amount of information databases let you retrieve about queries, the extent of
238 SQL verification you get from the query macros depends on the database
239
240 **If you are looking for an (asynchronous) ORM,** you can check out our new [Ecosystem wiki page](https://github.com/launchbadge/sqlx/wiki/Ecosystem#orms)!
241
242 [`ormx`]: https://crates.io/crates/ormx
243 [`SeaORM`]: https://github.com/SeaQL/sea-orm
244 ## Usage
245
246 See the `examples/` folder for more in-depth usage.
247
248 ### Quickstart
249
250 ```rust
251 use sqlx::postgres::PgPoolOptions;
252 // use sqlx::mysql::MySqlPoolOptions;
253 // etc.
254
255 #[async_std::main] // Requires the `attributes` feature of `async-std`
256 // or #[tokio::main]
257 // or #[actix_web::main]
258 async fn main() -> Result<(), sqlx::Error> {
259 // Create a connection pool
260 // for MySQL/MariaDB, use MySqlPoolOptions::new()
261 // for SQLite, use SqlitePoolOptions::new()
262 // etc.
263 let pool = PgPoolOptions::new()
264 .max_connections(5)
265 .connect("postgres://postgres:password@localhost/test").await?;
266
267 // Make a simple query to return the given parameter (use a question mark `?` instead of `$1` for MySQL/MariaDB)
268 let row: (i64,) = sqlx::query_as("SELECT $1")
269 .bind(150_i64)
270 .fetch_one(&pool).await?;
271
272 assert_eq!(row.0, 150);
273
274 Ok(())
275 }
276 ```
277
278
279 ### Connecting
280
281 A single connection can be established using any of the database connection types and calling `connect()`.
282
283 ```rust
284 use sqlx::Connection;
285
286 let conn = SqliteConnection::connect("sqlite::memory:").await?;
287 ```
288
289 Generally, you will want to instead create a connection pool (`sqlx::Pool`) for the application to
290 regulate how many server-side connections it's using.
291
292 ```rust
293 let pool = MySqlPool::connect("mysql://user:pass@host/database").await?;
294 ```
295
296 ### Querying
297
298 In SQL, queries can be separated into prepared (parameterized) or unprepared (simple). Prepared queries have their
299 query plan _cached_, use a binary mode of communication (lower bandwidth and faster decoding), and utilize parameters
300 to avoid SQL injection. Unprepared queries are simple and intended only for use where a prepared statement
301 will not work, such as various database commands (e.g., `PRAGMA` or `SET` or `BEGIN`).
302
303 SQLx supports all operations with both types of queries. In SQLx, a `&str` is treated as an unprepared query,
304 and a `Query` or `QueryAs` struct is treated as a prepared query.
305
306 ```rust
307 // low-level, Executor trait
308 conn.execute("BEGIN").await?; // unprepared, simple query
309 conn.execute(sqlx::query("DELETE FROM table")).await?; // prepared, cached query
310 ```
311
312 We should prefer to use the high-level `query` interface whenever possible. To make this easier, there are finalizers
313 on the type to avoid the need to wrap with an executor.
314
315 ```rust
316 sqlx::query("DELETE FROM table").execute(&mut conn).await?;
317 sqlx::query("DELETE FROM table").execute(&pool).await?;
318 ```
319
320 The `execute` query finalizer returns the number of affected rows, if any, and drops all received results.
321 In addition, there are `fetch`, `fetch_one`, `fetch_optional`, and `fetch_all` to receive results.
322
323 The `Query` type returned from `sqlx::query` will return `Row<'conn>` from the database. Column values can be accessed
324 by ordinal or by name with `row.get()`. As the `Row` retains an immutable borrow on the connection, only one
325 `Row` may exist at a time.
326
327 The `fetch` query finalizer returns a stream-like type that iterates through the rows in the result sets.
328
329 ```rust
330 // provides `try_next`
331 use futures::TryStreamExt;
332 // provides `try_get`
333 use sqlx::Row;
334
335 let mut rows = sqlx::query("SELECT * FROM users WHERE email = ?")
336 .bind(email)
337 .fetch(&mut conn);
338
339 while let Some(row) = rows.try_next().await? {
340 // map the row into a user-defined domain type
341 let email: &str = row.try_get("email")?;
342 }
343 ```
344
345 To assist with mapping the row into a domain type, one of two idioms may be used:
346
347 ```rust
348 let mut stream = sqlx::query("SELECT * FROM users")
349 .map(|row: PgRow| {
350 // map the row into a user-defined domain type
351 })
352 .fetch(&mut conn);
353 ```
354
355 ```rust
356 #[derive(sqlx::FromRow)]
357 struct User { name: String, id: i64 }
358
359 let mut stream = sqlx::query_as::<_, User>("SELECT * FROM users WHERE email = ? OR name = ?")
360 .bind(user_email)
361 .bind(user_name)
362 .fetch(&mut conn);
363 ```
364
365 Instead of a stream of results, we can use `fetch_one` or `fetch_optional` to request one required or optional result
366 from the database.
367
368 ### Compile-time verification
369
370 We can use the macro, `sqlx::query!` to achieve compile-time syntactic and semantic verification of the SQL, with
371 an output to an anonymous record type where each SQL column is a Rust field (using raw identifiers where needed).
372
373 ```rust
374 let countries = sqlx::query!(
375 "
376 SELECT country, COUNT(*) as count
377 FROM users
378 GROUP BY country
379 WHERE organization = ?
380 ",
381 organization
382 )
383 .fetch_all(&pool) // -> Vec<{ country: String, count: i64 }>
384 .await?;
385
386 // countries[0].country
387 // countries[0].count
388 ```
389
390 Differences from `query()`:
391
392 - The input (or bind) parameters must be given all at once (and they are compile-time validated to be
393 the right number and the right type).
394
395 - The output type is an anonymous record. In the above example the type would be similar to:
396
397 ```rust
398 { country: String, count: i64 }
399 ```
400
401 - The `DATABASE_URL` environment variable must be set at build time to a database which it can prepare
402 queries against; the database does not have to contain any data but must be the same
403 kind (MySQL, Postgres, etc.) and have the same schema as the database you will be connecting to at runtime.
404
405 For convenience, you can use [a `.env` file][dotenv]<sup>1</sup> to set DATABASE_URL so that you don't have to pass it every time:
406
407 ```
408 DATABASE_URL=mysql://localhost/my_database
409 ```
410
411 [dotenv]: https://github.com/dotenv-rs/dotenv#examples
412
413 The biggest downside to `query!()` is that the output type cannot be named (due to Rust not
414 officially supporting anonymous records). To address that, there is a `query_as!()` macro that is
415 mostly identical except that you can name the output type.
416
417 ```rust
418 // no traits are needed
419 struct Country { country: String, count: i64 }
420
421 let countries = sqlx::query_as!(Country,
422 "
423 SELECT country, COUNT(*) as count
424 FROM users
425 GROUP BY country
426 WHERE organization = ?
427 ",
428 organization
429 )
430 .fetch_all(&pool) // -> Vec<Country>
431 .await?;
432
433 // countries[0].country
434 // countries[0].count
435 ```
436
437 To avoid the need of having a development database around to compile the project even when no
438 modifications (to the database-accessing parts of the code) are done, you can enable "offline mode"
439 to cache the results of the SQL query analysis using the `sqlx` command-line tool. See
440 [sqlx-cli/README.md](./sqlx-cli/README.md#enable-building-in-offline-mode-with-query).
441
442 Compile-time verified queries do quite a bit of work at compile time. Incremental actions like
443 `cargo check` and `cargo build` can be significantly faster when using an optimized build by
444 putting the following in your `Cargo.toml` (More information in the
445 [Profiles section](https://doc.rust-lang.org/cargo/reference/profiles.html) of The Cargo Book)
446
447 ```toml
448 [profile.dev.package.sqlx-macros]
449 opt-level = 3
450 ```
451
452 <sup>1</sup> The `dotenv` crate itself appears abandoned as of [December 2021](https://github.com/dotenv-rs/dotenv/issues/74)
453 so we now use the `dotenvy` crate instead. The file format is the same.
454
455 ## Safety
456
457 This crate uses `#![forbid(unsafe_code)]` to ensure everything is implemented in 100% Safe Rust.
458
459 If the `sqlite` feature is enabled, this is downgraded to `#![deny(unsafe_code)]` with `#![allow(unsafe_code)]` on the
460 `sqlx::sqlite` module. There are several places where we interact with the C SQLite API. We try to document each call for the invariants we're assuming. We absolutely welcome auditing of, and feedback on, our unsafe code usage.
461
462 ## License
463
464 Licensed under either of
465
466 - Apache License, Version 2.0
467 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
468 - MIT license
469 ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
470
471 at your option.
472
473 ## Contribution
474
475 Unless you explicitly state otherwise, any Contribution intentionally submitted
476 for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
477 dual licensed as above, without any additional terms or conditions.