laravel-rust 0.1.3

Laravel for Rust: a full-stack Rust web framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
# Database

- [Introduction](#introduction)
- [Configuration](#configuration)
    - [Drivers](#drivers)
    - [SQLite](#sqlite)
    - [Defining more connections](#defining-more-connections)
    - [Time precision](#time-precision)
    - [Driver options](#typed-options-and-session-policy)
- [Running queries](#raw-queries)
    - [Running a select query](#running-a-select-query)
    - [Running insert, update, and delete statements](#running-insert-update-and-delete-statements)
    - [Binding values](#captured-bindings)
    - [Mapping rows to structs](#mapping-rows-to-structs)
    - [Returning inserted IDs and rows](#typed-and-bulk-returning-writes)
    - [JSON columns](#json-collections-and-identifiers)
    - [Enums, UUIDs, and IP addresses](#enums-and-ip-addresses)
    - [Dates and timestamps](#dates-and-timestamps)
    - [Decimals](#decimals)
    - [Streaming results](#scalars-streaming-and-multiple-results)
    - [Handling errors](#metadata-errors-and-escaping)
- [Transactions](#transactions)
    - [Handling deadlocks](#retrying-concurrency-failures)
    - [After-commit work](#after-commit-work-from-business-logic)
    - [Managing a transaction yourself](#managing-a-transaction-yourself)
- [Using multiple connections](#driver-neutral-connections)
    - [Scoped default connections](#scoped-default-connections)
    - [Adding connections at runtime](#laziness-and-dynamic-connections)
- [Read and write connections](#read-and-write-connections)
    - [Preventing stale reads across requests](#preventing-stale-database-reads)
- [Listening for queries](#query-diagnostics)
- [Native SQLx access](#native-sqlx-access)
- [Testing](#testing)

<a name="introduction"></a>
## Introduction

Almost every modern web application interacts with a database. Built on [SQLx](https://github.com/launchbadge/sqlx), Laravel provides first-party support for PostgreSQL, MySQL, MariaDB, and SQLite, whether you are working with raw SQL via `db::query!`, the fluent [query builder](queries.md), or [models](models.md).

Most of your application's queries will go through models and the query builder. This guide walks through configuring your database connections, working with transactions and read replicas, and writing raw SQL when a query is clearest in SQL itself. To create and modify tables, see [migrations](migrations.md).

<a name="configuration"></a>
## Configuration

Database settings live in `src/config/database.rs`. New applications define a single `postgres` connection by default. Configure the default connection name with `DB_CONNECTION` and its connection string with `DATABASE_URL`:

```ini
DB_CONNECTION=postgres
DATABASE_URL=postgres://postgres@127.0.0.1/laravel
```

Laravel selects the driver from the URL scheme: `postgres://`, `mysql://`, `mariadb://`, or `sqlite:`. Although MySQL and MariaDB share a wire protocol, their SQL syntax differs in places, so use `mariadb://` for MariaDB servers so the query builder generates MariaDB-compatible SQL.

<a name="drivers"></a>
### Drivers

Each database driver is enabled via a Cargo feature on `laravel-rust` so your application only compiles the drivers it uses. New applications enable `database-postgres` in `Cargo.toml`. To switch drivers or add another database engine, update the feature list in `Cargo.toml`:

```toml
[dependencies]
laravel-rust = { version = "0.1", features = ["database-postgres", "database-sqlite"] }
```

| Feature | Databases |
| --- | --- |
| `database-postgres` | PostgreSQL |
| `database-mysql` | MySQL and MariaDB |
| `database-sqlite` | SQLite |

Without a driver feature, the `laravel::db` module doesn't exist, and the database session, cache, and queue drivers can't run.

<a name="sqlite"></a>
### SQLite

SQLite keeps the entire database in a single file with no separate server to run, making it convenient for local development and small applications. To use it instead of PostgreSQL, replace `database-postgres` with `database-sqlite` in `Cargo.toml`, then configure your `.env` file:

```ini
DB_CONNECTION=sqlite
DATABASE_URL=sqlite://storage/app/database.sqlite?mode=rwc
```

The path is relative to your application's root directory. `mode=rwc` creates the file on first use, provided the parent directory already exists.

<a name="defining-more-connections"></a>
### Defining more connections

When your application talks to more than one database, such as a separate reporting database, register additional named connections in `src/config/database.rs`. Start from `Database::from_env(env)` so your default connection continues to read `DB_CONNECTION`, `DATABASE_URL`, `DB_MAX_CONNECTIONS`, `DB_TIME_PRECISION`, and the [read and write](#read-and-write-connections) variables from the environment:

```rust
use laravel::config::database::{ConnectionConfig, Database};
use laravel::config::{self, Env};

#[config::section]
fn database(env: &Env) -> Database {
    let mut database = Database::from_env(env);

    database.add_connection(
        "reporting",
        ConnectionConfig::new(env.get("REPORTING_DATABASE_URL").unwrap_or_default())
            .max_connections(20),
    );

    database
}
```

By default, each connection maintains a pool of up to 10 open connections. Under heavy concurrency, you can raise the default connection's pool size with `DB_MAX_CONNECTIONS`, keeping the combined total across all application instances below your database server's connection limit:

```ini
DB_MAX_CONNECTIONS=20
```

For additional connections, chain `max_connections` on `ConnectionConfig`, as shown on `reporting` above. Queries wait up to 30 seconds to acquire a connection from the pool before returning an error. To adjust pool timeouts, call `acquire_timeout`, `idle_timeout`, or `max_lifetime` on `ConnectionConfig`, such as `.acquire_timeout(5.seconds())`.

Laravel opens connection pools lazily on the first query, so an unreachable database does not prevent your application from booting unless your own boot hooks query it.

To run a query on a named connection, see [Using multiple connections](#driver-neutral-connections).

<a name="time-precision"></a>
### Time precision

By default, each database connection stores timestamps, date-times, and times with microsecond precision (6 fractional digits of seconds), matching the maximum precision supported by PostgreSQL and MySQL. Before sending a time value to the database, Laravel truncates it to the connection's precision rather than letting the database round it, and the [schema builder's](schema.md#column-types) time columns use the same precision by default. That way, a row written at `laravel::now()` is never rounded forward into the future, so a query for records up to `laravel::now()` always finds it.

To store whole seconds instead, or any other precision from `0` to `6`, set `DB_TIME_PRECISION` in your `.env` file:

```ini
DB_TIME_PRECISION=0
```

For additional connections, chain `time_precision` on `ConnectionConfig` in `src/config/database.rs`:

```rust
database.add_connection(
    "legacy",
    ConnectionConfig::new("mysql://app@10.0.0.5/legacy").time_precision(0),
);
```

When customizing a column with `.precision(n)` in a migration, give it at least the connection's precision. A column with less precision than its connection causes the database to round incoming values instead of truncating them, while a column with higher precision still only receives values truncated to the connection's precision.

> [!NOTE]
> If you change `DB_TIME_PRECISION` in an application that has already run migrations, write a new migration to update your existing time columns with `.precision(n).change()`.

<a name="typed-options-and-session-policy"></a>
### Driver options

For TLS, Unix sockets, or other settings that don't fit in a URL, build the connection in `src/config/database.rs` from SQLx's options for your driver. `initialize` runs SQL each time the pool opens a new connection:

```rust
use laravel::config::database::{ConnectionConfig, Database};
use laravel::config::{self, Env};
use laravel::db::sqlx::postgres::{PgConnectOptions, PgSslMode};

#[config::section]
fn database(env: &Env) -> Database {
    let mut database = Database::from_env(env);

    let postgres = ConnectionConfig::postgres(
        PgConnectOptions::new()
            .host("db.internal")
            .username("app")
            .database("app")
            .ssl_mode(PgSslMode::Require),
    )
    .initialize("SET search_path TO app, public");

    database.add_connection("postgres", postgres);

    database
}
```

`ConnectionConfig::mysql`, `ConnectionConfig::mariadb`, and `ConnectionConfig::sqlite` accept the same builder options. When replacing the default connection with driver options, chain `max_connections` or `time_precision` directly on the `ConnectionConfig` if you need a custom pool size or time precision.

<a name="raw-queries"></a>
## Running queries

Once your connection is configured, you may run queries with the `db::query!` macro. Write your SQL as usual, and wrap any Rust variable in braces. The macro binds each one as a query parameter, so a variable can never inject SQL. This handler finds a user by the ID in the URL, and responds with a `404` when there's no such user:

```rust
use laravel::db;
use laravel::prelude::*;

pub async fn show(Params(id): Params<i64>) -> laravel::Result<String> {
    let user = db::query!("SELECT id, name FROM users WHERE id = {id}")
        .select_one()
        .await?
        .or_abort(404)?;

    let name: String = user.try_get("name")?;

    Ok(name)
}
```

The macro runs the query on your default connection. It doesn't check the SQL against your schema when you compile, so a misspelled column is an error when the query runs, not a compile error.

<a name="running-a-select-query"></a>
### Running a select query

`select` returns every matching row, and `select_one` returns the first, if there is one. Read a row's columns with `try_get`, by name or by zero-based position:

```rust
use laravel::db;

let active = true;

let users = db::query!("SELECT id, name FROM users WHERE active = {active}")
    .select()
    .await?;

for user in users {
    let name: String = user.try_get("name")?;
}
```

Most of the time you'll want rows as structs instead, as [Mapping rows to structs](#mapping-rows-to-structs) shows. When a query returns a single value, such as a count, `scalar` returns it directly. It returns `None` when there's no row:

```rust
let count = db::query!("SELECT COUNT(*) FROM users").scalar::<i64>().await?.unwrap_or(0);
```

When calling a stored procedure that returns multiple result sets, use `select_result_sets` to collect each set in order and read its `rows`:

```rust
let account_id = 42;

let sets = db::query!("CALL account_summary({account_id})")
    .select_result_sets()
    .await?;

for row in &sets[0].rows {
    let balance: i64 = row.try_get("balance")?;
}

for row in &sets[1].rows {
    let invoice_id: i64 = row.try_get("id")?;
}
```

<a name="running-insert-update-and-delete-statements"></a>
### Running insert, update, and delete statements

Use the `insert`, `update`, and `delete` methods to execute write statements against the database. Both `update` and `delete` return the number of rows affected by the query:

```rust
use laravel::db;

let (name, email) = ("Taylor", "taylor@example.com");

db::query!("INSERT INTO users (name, email) VALUES ({name}, {email})")
    .insert()
    .await?;

let updated = db::query!("UPDATE users SET votes = 100 WHERE name = {name}")
    .update()
    .await?;

let deleted = db::query!("DELETE FROM users WHERE votes < 10").delete().await?;
```

To get the new row's ID back, see [Returning inserted IDs and rows](#typed-and-bulk-returning-writes). For statements that return nothing, such as `DROP TABLE`, use `statement`:

```rust
db::query!("DROP TABLE users").statement().await?;
```

To run multiple statements separated by semicolons, use `unprepared`. Because it sends the SQL directly as written without preparing it, it cannot bind values and returns an error if the query contains any captured variables:

```rust
db::query!(
    "CREATE TABLE audit_logs (id INTEGER PRIMARY KEY, message TEXT);
     CREATE INDEX audit_logs_message_index ON audit_logs (message);"
)
.unprepared()
.await?;
```

<a name="captured-bindings"></a>
### Binding values

A capture may name a variable or a field, such as `{email}`, `{user.id}`, or `{form.address.city}`. The macro borrows each one, so you can keep using your variables afterward. It accepts only names and fields, so compute anything else, such as a method call, into a variable first.

To match against a list, spread a `Vec`, array, or slice with `{...name}`. It binds one parameter per item:

```rust
use laravel::db;

let roles = vec!["admin", "editor"];

let users = db::query!("SELECT * FROM users WHERE role IN ({...roles})")
    .select()
    .await?;
```

An empty list returns an error without running the query, so check for one first when the list comes from input. Place captures outside SQL quotes and comments, and write a literal brace as `{{` or `}}`.

<a name="bulk-row-expansion"></a>
#### Inserting many rows

To insert a collection in one statement, expand it with `{...users(name, email)}`. The expansion writes one parenthesized row per item, binding the fields you list:

```rust
use laravel::db;

struct NewUser {
    name: String,
    email: String,
}

let users = vec![
    NewUser { name: "Taylor".into(), email: "taylor@example.com".into() },
    NewUser { name: "Jess".into(), email: "jess@example.com".into() },
];

let inserted = db::query!("INSERT INTO users (name, email) VALUES {...users(name, email)}")
    .insert()
    .await?;

let count = inserted.rows_affected();
```

Put the expansion directly after `VALUES`, without parentheses around it. Each field is a parameter, and PostgreSQL and MySQL allow 65,535 parameters in one query, while SQLite allows 32,766. Insert a larger collection in chunks.

<a name="mapping-rows-to-structs"></a>
### Mapping rows to structs

To map rows into your own structs, derive `db::FromRow` and call `select_as` or `select_one_as`. Fields map to columns by name, and `#[db(rename = "...")]` maps a field to a column with another name:

```rust
use laravel::db;

#[derive(Debug, db::FromRow)]
struct Subscriber {
    id: i64,
    #[db(rename = "email_address")]
    email: String,
    nickname: Option<String>,
}

let id = 42;

let subscriber: Option<Subscriber> =
    db::query!("SELECT id, email_address, nickname FROM subscribers WHERE id = {id}")
        .select_one_as()
        .await?;

let subscribers = db::query!("SELECT id, email_address, nickname FROM subscribers")
    .select_as::<Subscriber>()
    .await?;
```

Mapping ignores extra columns. A missing column, or a NULL in a field that isn't an `Option`, returns an error. To read one column from every row, map each row to the column's type:

```rust
let ids = db::query!("SELECT id FROM users WHERE active").select_as::<i64>().await?;
```

`#[db(json)]` decodes a JSON column into any field that implements `Deserialize`. On an `Option` field, both SQL NULL and JSON `null` read as `None`:

```rust
#[derive(db::FromRow)]
struct User {
    id: i64,
    #[db(json)]
    roles: Vec<String>,
    #[db(json)]
    preferences: Option<serde_json::Value>,
}
```

To map a column into a single-field wrapper struct, derive `Newtype`, which the [prelude](prelude.md) imports. The struct then binds and decodes as the value it wraps, so it works as a `FromRow` field and as a [model](models.md) column:

```rust
use laravel::db;
use laravel::prelude::*;

#[derive(Debug, Newtype)]
struct Email(String);

#[derive(Debug, db::FromRow)]
struct Subscriber {
    id: i64,
    email: Email,
}
```

For custom conversions, such as parsing an IANA timezone name from a text column into a `TimeZone`, implement `db::Decode`. `index` is the column's zero-based position in the row, which you can pass to `row.try_get` to read the underlying database value:

```rust
use laravel::db::{AnyRow, Decode};
use laravel::time::tz::TimeZone;

struct UserTimeZone(TimeZone);

impl Decode for UserTimeZone {
    fn decode(row: &AnyRow, index: usize) -> laravel::Result<Self> {
        let name: String = row.try_get(index)?;

        Ok(Self(TimeZone::get(&name)?))
    }
}
```

<a name="typed-and-bulk-returning-writes"></a>
### Returning inserted IDs and rows

To retrieve the ID of a newly inserted row, call `insert_returning_id`. Include a `RETURNING id` clause on PostgreSQL and SQLite; on MySQL and MariaDB, omit the clause and Laravel automatically reads the auto-increment ID:

```rust
use laravel::db;

let name = "Taylor";

let id: Option<i64> = db::query!("INSERT INTO users (name) VALUES ({name}) RETURNING id")
    .insert_returning_id()
    .await?;
```

To get whole rows back from a write, write a `RETURNING` clause and use one of the returning methods. The `_as` methods map the rows with `db::FromRow`:

```rust
#[derive(db::FromRow)]
struct User {
    id: i64,
    name: String,
}

let (id, name) = (42, "Taylor Otwell");

let user = db::query!("UPDATE users SET name = {name} WHERE id = {id} RETURNING id, name")
    .update_returning_as::<User>()
    .await?;
```

| Statement | First row, as `Option<T>` | Every row, as `Vec<T>` |
| --- | --- | --- |
| `INSERT` | `insert_returning_as` | `insert_returning_all_as` |
| `UPDATE` | `update_returning_as` | `update_returning_all_as` |
| `DELETE` | `delete_returning_as` | `delete_returning_all_as` |

Each method also has a raw variant without the `_as` suffix, such as `insert_returning` or `update_returning_all`, which returns `AnyRow` values you can read with `try_get`:

```rust
if let Some(row) = db::query!(
    "UPDATE users SET name = {name} WHERE id = {id} RETURNING id, name"
)
.update_returning()
.await?
{
    let updated_name: String = row.try_get("name")?;
}
```

PostgreSQL and SQLite support `RETURNING` on `INSERT`, `UPDATE`, and `DELETE`, MariaDB supports it on `INSERT` and `DELETE`, and MySQL does not support `RETURNING`.

<a name="json-collections-and-identifiers"></a>
### JSON columns

To store a custom Rust type as JSON, derive `db::Json` alongside Serde's traits. Bind it in queries as a standard parameter and read it back with `try_get` or as a `FromRow` field:

```rust
use laravel::db;
use laravel::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, db::Json)]
struct Preferences {
    theme: String,
    notifications: bool,
}

let id = 42;
let preferences = Preferences { theme: "dark".into(), notifications: true };

db::query!("UPDATE users SET preferences = {preferences} WHERE id = {id}")
    .update()
    .await?;

let row = db::query!("SELECT preferences FROM users WHERE id = {id}")
    .select_one()
    .await?
    .or_abort(404)?;

let preferences: Preferences = row.try_get("preferences")?;
```

A `Vec` or other collection captured as `{roles}` binds as a single JSON value, while `{...roles}` spreads it into one parameter per item. PostgreSQL and MySQL store JSON in native JSON columns, and SQLite stores it as text.

<a name="enums-and-ip-addresses"></a>
### Enums, UUIDs, and IP addresses

To store an enum without fields as text, derive `Enum`, which the [prelude](prelude.md) imports. It uses the same names as Serde, so `#[serde(rename_all)]` and `#[serde(rename)]` decide what's stored:

```rust
use laravel::db;
use laravel::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Enum)]
#[serde(rename_all = "snake_case")]
enum Status {
    PendingReview,
    Active,
}

let id = 42;
let status = Status::PendingReview;

db::query!("UPDATE posts SET status = {status} WHERE id = {id}")
    .update()
    .await?;
```

This stores `pending_review`. Reading a string that matches no variant returns an error. For enums whose variants hold data, derive `db::Json` instead and store them in a JSON column such as `table.json("payment_method")` or `table.jsonb("payment_method")`:

```rust
use laravel::db;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, db::Json)]
enum PaymentMethod {
    Card { last4: String },
    BankTransfer,
}

let id = 42;
let method = PaymentMethod::Card { last4: "4242".into() };

db::query!("UPDATE orders SET payment_method = {method} WHERE id = {id}")
    .update()
    .await?;
```

For UUIDs and ULIDs, use `laravel::str::Uuid` and `laravel::str::Ulid`. A `Uuid` binds as a native UUID on PostgreSQL and as text on other databases, and a `Ulid` always binds as text. `IpAddr` binds as text too, so store it in a text column, as the schema builder's `ip_address` column does:

```rust
use std::net::IpAddr;

use laravel::db;
use laravel::str::{self, Ulid, Uuid};

let id: Uuid = str::uuid();
let trace_id: Ulid = str::ulid();
let ip_address: IpAddr = "203.0.113.7".parse()?;

db::query!(
    "INSERT INTO logins (id, trace_id, ip_address) VALUES ({id}, {trace_id}, {ip_address})"
)
.insert()
.await?;
```

<a name="dates-and-timestamps"></a>
### Dates and timestamps

Dates and times use the types in [`laravel::time`](time.md):

```rust
use laravel::db;
use laravel::prelude::*;
use laravel::time::Timestamp;
use laravel::time::civil::Date;

let id = 42;
let ships_on: Date = "2026-11-20".parse()?;
let paid_at = laravel::now().timestamp();

db::query!("UPDATE orders SET ships_on = {ships_on}, paid_at = {paid_at} WHERE id = {id}")
    .update()
    .await?;

let order = db::query!("SELECT ships_on, paid_at FROM orders WHERE id = {id}")
    .select_one()
    .await?
    .or_abort(404)?;

let paid_at: Option<Timestamp> = order.try_get("paid_at")?;
```

| Rust type | What it holds | PostgreSQL | MySQL | SQLite |
| --- | --- | --- | --- | --- |
| `time::civil::Date` | A calendar date | `DATE` | `DATE` | Text |
| `time::civil::Time` | A time of day | `TIME` | `TIME` | Text |
| `time::civil::DateTime` | A date and time, without a timezone | `TIMESTAMP` | `DATETIME` | Text |
| `time::Timestamp` | An instant | `TIMESTAMPTZ` or `TIMESTAMP` | `TIMESTAMP` or `DATETIME` | Text |

Laravel stores times in UTC, so a `Timestamp` field reads the schema builder's `timestamps()` columns on every database, even though some of those columns have no timezone.

<a name="decimals"></a>
### Decimals

For exact decimals such as prices or account balances, use `laravel::numeric::Decimal` rather than floating-point numbers:

```rust
use laravel::db;
use laravel::numeric::Decimal;
use laravel::prelude::*;

let id = 42;
let subtotal: Decimal = "149.99".parse()?;
let tax: Decimal = "12.37".parse()?;
let total = (&subtotal + &tax).round(2);

db::query!("UPDATE orders SET total = {total} WHERE id = {id}")
    .update()
    .await?;

let order = db::query!("SELECT total FROM orders WHERE id = {id}")
    .select_one()
    .await?
    .or_abort(404)?;

let total: Decimal = order.try_get("total")?;
```

`Decimal` supports standard arithmetic (`+`, `-`, `*`, `/`), comparisons, and rounding helpers such as `.round(2)` and `.with_scale(2)`. Borrow operands like `&subtotal + &tax` when you want to reuse them afterward.

`Decimal` maps to `NUMERIC` on PostgreSQL, `DECIMAL` on MySQL, and `NUMERIC` or text on SQLite. Parse decimals from strings rather than floats so they preserve every digit. Because SQLite has no native exact decimal type and stores fractional `NUMERIC` values as floating-point numbers (roughly 15 digits of precision), store higher-precision decimals in a text column on SQLite.

<a name="scalars-streaming-and-multiple-results"></a>
### Streaming results

`select` loads every matching row into memory at once, which can exhaust memory when processing large tables such as a full subscriber list. To process rows one at a time, call `each` with an async closure; iteration stops immediately on the first error:

```rust
use laravel::db;

db::query!("SELECT email FROM subscribers").each(async |row| {
    let email: String = row.try_get("email")?;

    // Send the newsletter...

    Ok(())
}).await?;
```

`each` keeps a connection from the pool until it finishes, so keep slow work out of the closure. The closure can't change variables outside it. To collect rows, keep a running total, or stop early, use `cursor`, which returns a stream of rows:

```rust
use laravel::db;
use laravel::stream::TryStreamExt;

let mut cursor = db::query!("SELECT id, email FROM subscribers ORDER BY id").cursor();
let mut sent = 0;

while let Some(row) = cursor.try_next().await? {
    let email: String = row.try_get("email")?;

    // Send the newsletter...

    sent += 1;
}
```

To map each streamed row directly into a struct deriving `db::FromRow`, use `cursor_as`:

```rust
use laravel::db;
use laravel::stream::TryStreamExt;

#[derive(db::FromRow)]
struct Subscriber {
    id: i64,
    email: String,
}

let mut cursor = db::query!("SELECT id, email FROM subscribers ORDER BY id")
    .cursor_as::<Subscriber>();

while let Some(subscriber) = cursor.try_next().await? {
    tracing::info!(id = subscriber.id, email = %subscriber.email, "Processing subscriber");
}
```

<a name="metadata-errors-and-escaping"></a>
### Handling errors

Query failures return standard `laravel::Error` values, so propagating them with `?` from a handler produces a `500` response. Each error message includes the database error, connection name, driver, and SQL query, such as `no such table: subscribers (Connection: primary, Driver: SQLite, SQL: INSERT INTO subscribers (email) VALUES (?))`. Bound values are omitted from the message, and the error tracks the call site that built the query. To handle specific constraint failures, such as a duplicate email address, inspect the error with `db::is_unique_violation`:

```rust
use laravel::db;
use laravel::prelude::*;

#[laravel::input]
#[validate(anyone)]
pub struct Subscribe {
    #[validate(required, email)]
    email: String,
}

pub async fn subscribe(
    Valid(Subscribe { email }): Valid<Subscribe>,
) -> laravel::Result<Redirect> {
    match db::query!("INSERT INTO subscribers (email) VALUES ({email})").insert().await {
        Ok(_) => {}
        Err(error) if db::is_unique_violation(&error) => {
            // Already subscribed...
        }
        Err(error) => return Err(error),
    }

    Ok(Redirect::back())
}
```

Laravel provides helpers to classify common database errors across PostgreSQL, MySQL, MariaDB, and SQLite:

| Helper | Matches |
| --- | --- |
| `db::is_unique_violation(&error)` | Unique or primary key constraint violation |
| `db::is_foreign_key_violation(&error)` | Foreign key constraint violation |
| `db::is_check_violation(&error)` | `CHECK` constraint violation |
| `db::is_lost_connection(&error)` | Dropped connection, server restart, or failed-over read-only primary |

<a name="transactions"></a>
## Transactions

When transferring funds between two accounts, both updates must succeed or fail together. Use `db::transaction` to run an async closure inside a database transaction on the default connection; Laravel commits automatically when the closure returns `Ok` and rolls back on error:

```rust
use laravel::db;

let (from, to, amount) = (1_i64, 2_i64, 25_i64);

db::transaction(async |tx| {
    db::query!(tx, "UPDATE accounts SET balance = balance - {amount} WHERE id = {from}")
        .update()
        .await?;

    db::query!(tx, "UPDATE accounts SET balance = balance + {amount} WHERE id = {to}")
        .update()
        .await?;

    Ok(())
})
.await?;
```

The closure may borrow your variables and return a value, which `db::transaction` returns after the commit:

```rust
let order_id: i64 = db::transaction(async |tx| {
    let order_id = db::query!(
        tx,
        "INSERT INTO orders (user_id, total) VALUES ({user_id}, {total}) RETURNING id"
    )
        .insert_returning_id()
        .await?
        .expect("inserted order ID");

    db::query!(tx, "INSERT INTO order_items (order_id, sku) VALUES ({order_id}, {sku})")
        .insert()
        .await?;

    Ok(order_id)
})
.await?;
```

To run a transaction on another connection, call `transaction` on that connection: `db::connection("reporting")?.transaction(async |tx| { .. })`.

Inside the closure, every query on the transaction's connection joins the transaction, even queries that don't go through `tx`. A helper function can run a plain `db::query!` or a model query and still see uncommitted rows, and its writes roll back with yours. The database session, cache, and queue stores, the `unique` and `exists` [validation rules](validation.md#database-records), and awaited listeners all participate in the active transaction.

Calling `db::transaction` inside another transaction's closure creates a savepoint. When the inner closure fails, only its writes roll back, and the outer transaction carries on. A function may wrap its own writes in `db::transaction`, and it works the same whether or not you call it inside your transaction.

A few queries behave differently inside a transaction:

- A query from a task started with `task::spawn` fails, because the task could outlive the transaction. Await the work inside the transaction instead, or start it after the commit.
- To write something that must survive a rollback, such as an audit entry, run it on `db::default_connection()?.outside_transaction()`.
- On MySQL and SQLite, a query inside an `each` closure fails, because the cursor holds the transaction's connection. Read the rows with `select` first.
- MySQL commits the transaction when it runs a statement that changes a table, such as `CREATE TABLE`, so keep schema changes out of transactions.

<a name="retrying-concurrency-failures"></a>
### Handling deadlocks

Under high concurrency, two transactions can deadlock and cause the database to abort one of them. `transaction_with_attempts` retries the closure automatically when a deadlock or MySQL/SQLite lock wait timeout occurs, up to the total number of attempts specified:

```rust
use laravel::db;

let id = 42_i64;

db::transaction_with_attempts(3, async |tx| {
    db::query!(tx, "UPDATE accounts SET balance = balance + 1 WHERE id = {id}")
        .update()
        .await?;

    Ok(())
})
.await?;
```

Each attempt runs a fresh copy of the closure, so the closure must be `Clone`. It may borrow your variables, but not change them. Other errors, such as a constraint violation, don't retry. Keep side effects that can't run twice, such as sending an email, out of the closure, and register them as [after-commit work](#after-commit-work-from-business-logic) instead.

<a name="after-commit-work-from-business-logic"></a>
### After-commit work

Some work should happen only once the data it describes is committed, such as sending an order confirmation. `db::after_commit` registers that work from anywhere inside a transaction, without passing the transaction around. This function records an order, and logs it once the order is committed:

```rust
use laravel::db;

pub async fn place_order(user_id: i64, total: i64) -> laravel::Result<()> {
    db::query!("INSERT INTO orders (user_id, total) VALUES ({user_id}, {total})")
        .insert()
        .await?;

    db::after_commit(async move || {
        tracing::info!(user_id, "Order placed");

        Ok(())
    })
    .await
}

db::transaction(async |_| place_order(1, 4_999).await).await?;
```

When no transaction is active, the callback runs immediately. If the transaction rolls back, Laravel discards it. Inside a nested savepoint, the callback waits until the outermost transaction commits.

The callback runs after the connection is released, so it may query the committed data. Its closure must own what it captures, which is why the example uses `async move`. If the callback fails, `db::transaction` returns an `AfterCommitError`, while the committed data remains saved.

After-commit callbacks are held in memory, so they are lost if the process stops before they run. For durable follow-up work, [dispatch a queued job](queues.md) instead. Jobs dispatched inside a transaction automatically wait for the commit, and so do [events](events.md#database-transactions), except for listeners marked `at_dispatch`.

<a name="managing-a-transaction-yourself"></a>
### Managing a transaction yourself

`db::transaction` commits and rolls back for you, and it's the right choice for most code. When you need to decide yourself when to commit or roll back, call `db::begin`, or `begin` on a connection. Calling `begin` on a transaction creates a savepoint:

```rust
use laravel::db;

let mut transaction = db::begin().await?;

db::query!(transaction, "INSERT INTO notes (body) VALUES ('Keep this note')")
    .insert()
    .await?;

let mut savepoint = transaction.begin().await?;

db::query!(savepoint, "INSERT INTO notes (body) VALUES ('Discard this note')")
    .insert()
    .await?;

savepoint.rollback().await?;

transaction.commit().await?;
```

Dropping a transaction you haven't committed rolls it back. Queries that don't go through the transaction, and `db::after_commit`, join it only inside `transaction.scope(async |tx| { .. })`.

<a name="driver-neutral-connections"></a>
## Using multiple connections

`db::query!` runs on your default connection. To run a query on another, look the connection up by name with `db::connection` and pass it before the SQL:

```rust
use laravel::db;

let reporting = db::connection("reporting")?;
let month = "2026-10";

let totals = db::query!(
    reporting,
    "SELECT region, SUM(total) FROM sales WHERE month = {month} GROUP BY region"
)
.select()
.await?;
```

`db::default_connection()` returns the default connection. Connection handles are cheap to clone and do not open a pool until the first query runs. Because Laravel does not translate raw SQL across database engines, you can match on `connection.driver()` when writing database-specific SQL:

```rust
use laravel::db::{self, Driver};

let connection = db::default_connection()?;

let version = match connection.driver() {
    Driver::Postgres => db::query!(connection, "SELECT version()")
        .scalar::<String>()
        .await?,
    Driver::MySql | Driver::MariaDb => db::query!(connection, "SELECT VERSION()")
        .scalar::<String>()
        .await?,
    Driver::Sqlite => db::query!(connection, "SELECT sqlite_version()")
        .scalar::<String>()
        .await?,
};
```

<a name="scoped-default-connections"></a>
### Scoped default connections

Some applications keep each tenant in its own database, so every query in a request must go to that tenant's connection. `db::using_connection` changes the default connection while a future runs, for every query inside it, including the query builder's and your models':

```rust
use laravel::db;

db::using_connection("tenant_42", async {
    let count = db::query!("SELECT COUNT(*) FROM projects").scalar::<i64>().await?;

    // ...

    Ok::<_, laravel::Error>(())
})
.await?;
```

The default goes back to the previous one when the future finishes. Tasks you start with `task::spawn` inherit the override, but raw Tokio tasks don't.

<a name="laziness-and-dynamic-connections"></a>
### Adding connections at runtime

You can register and remove named connections at runtime by injecting `DatabaseManager`. Calling `add_connection` registers a connection lazily without opening its pool until the first query runs, and `remove_connection` unregisters it and closes its pool once active queries finish:

```rust
use laravel::config::database::ConnectionConfig;
use laravel::container::Inject;
use laravel::db::DatabaseManager;

pub async fn connect_shard(database: Inject<DatabaseManager>, shard: &str, url: String) {
    database.add_connection(shard, ConnectionConfig::new(url));
}

pub async fn disconnect_shard(database: Inject<DatabaseManager>, shard: &str) {
    database.remove_connection(shard);
}
```

Registered connections remain in `DatabaseManager` until removed, so keep the number of named connections bounded. For one-off or temporary connections, such as importing from a customer-supplied database, call `database.connect` instead to create an unregistered connection whose pool closes automatically when the handle drops:

```rust
use laravel::config::database::ConnectionConfig;
use laravel::container::Inject;
use laravel::db::{self, DatabaseManager};

pub async fn import_from(
    database: Inject<DatabaseManager>,
    url: String,
) -> laravel::Result<i64> {
    let external = database.connect(ConnectionConfig::new(url))?;

    let count = db::query!(external, "SELECT COUNT(*) FROM customers")
        .scalar::<i64>()
        .await?
        .unwrap_or(0);

    Ok(count)
}
```

<a name="read-and-write-connections"></a>
## Read and write connections

As your traffic grows, you may want to send `SELECT` statements to read replicas and every write to your primary database. List your replicas' hosts in `DB_READ_HOSTS`, separated by commas:

```ini
DATABASE_URL=postgres://app:secret@primary.internal/app
DB_READ_HOSTS=replica-1.internal,replica-2.internal:5433
DB_STICKY=true
```

Each replica connects with `DATABASE_URL`'s credentials, database, and options, and changes only the host, and the port when you give one. Laravel picks a replica at random for each new connection.

Sometimes a replica needs its own credentials, such as a read-only user, or a different database name. For that replica, list its full URL instead of its host, and Laravel uses the URL as written. You may mix both forms in one list:

```ini
DATABASE_URL=postgres://app:secret@primary.internal/app
DB_READ_HOSTS=replica-1.internal,postgres://reader:secret@replica-2.internal/app
```

If your provider gives the primary its own URL, such as a writer endpoint that fails over to a new primary, set it in `DB_WRITE_URL`. Writes and transactions then use `DB_WRITE_URL`, while host-only replicas still take their credentials, database, and options from `DATABASE_URL`:

```ini
DATABASE_URL=postgres://app:secret@db.internal/app
DB_WRITE_URL=postgres://app:secret@writer.db.internal/app
DB_READ_HOSTS=reader-1.db.internal,reader-2.db.internal
```

Every URL on a connection must use the same database driver, so you can't pair a PostgreSQL writer with MySQL replicas. Tests that refresh the database still create their databases from `DATABASE_URL`.

These variables configure the default connection. To give another connection replicas, or to configure them in code, give the connection a `read` endpoint, and optionally a `write` endpoint, in `src/config/database.rs`:

```rust
use laravel::config::database::{ConnectionConfig, Endpoint};

database.add_connection(
    "reporting",
    ConnectionConfig::new("postgres://app:password@reporting/app")
        .read(Endpoint::hosts(["reporting-replica-1", "reporting-replica-2"]))
        .sticky(true),
);
```

`Endpoint::hosts` keeps the connection's credentials, database, and options, and changes only the host. To connect with other credentials, use `Endpoint::new(url)` instead. To read a list in the same format as `DB_READ_HOSTS` from a variable of your own, use `env.get::<Endpoint>("REPORTING_READ_HOSTS")`.

When you configure the default connection in code and call `apply_env`, each of these variables that's set replaces the setting it names, and the connection keeps the settings whose variables aren't set.

Laravel routes each query by the method that runs it. `select`, `select_one`, `scalar`, and cursors read from a replica. Writes, the returning methods, and every query in a transaction use the writer: `DB_WRITE_URL` when it's set, and `DATABASE_URL` otherwise. Raw queries, the query builder, and models all follow these rules.

Replicas can lag briefly behind the writer. With `sticky` enabled, once a request, queued job, or console command writes to the connection, subsequent reads use the writer for the remainder of that request, job, or command so it always reads its own writes. To force a single query onto the writer, such as reading a row written by another request, call `use_write_connection`:

```rust
use laravel::db;

let id = 42_i64;

let order = db::query!("SELECT * FROM orders WHERE id = {id}")
    .use_write_connection()
    .select_one()
    .await?;
```

To send every read to the writer for the rest of the request, call `use_write_connection_when_reading(true)` on the connection.

<a name="preventing-stale-database-reads"></a>
### Preventing stale reads across requests

If a user updates a post and then reloads the page, a read replica may still show the old title. The `sticky` option ends when the update request ends. To send the user's next requests to the writer while replicas catch up, append `PreventStaleDatabaseReads` to the `web` middleware group in `src/app.rs`:

```rust
use laravel::http::middleware::PreventStaleDatabaseReads;

.with_middleware(|middleware, _| {
    middleware.web(|web| {
        web.append(PreventStaleDatabaseReads::default());
    });
})
```

For two seconds after a write to the default connection, the middleware sends reads on that connection to the writer for requests in the same session. If your replicas need more time, pass a duration instead:

```rust
use laravel::time::ToSpan;

web.append(PreventStaleDatabaseReads::new(5.seconds()));
```

The middleware must run after `StartSession`. When you use the database session driver, Laravel loads the session from the writer even before the middleware runs. Reads from other sessions and on other connections keep their usual routing.

<a name="query-diagnostics"></a>
## Listening for queries

To see each query your application runs, such as to log slow ones, register a listener with `db::listen`. Do it in a `booted` callback in `src/app.rs`, or in a service provider's `boot` method:

```rust
use laravel::db;
use laravel::time::ToSpan;

.booted(async |_| {
    db::listen(|query| {
        if query.elapsed > 500.milliseconds() {
            let types: Vec<_> = query
                .bindings
                .iter()
                .map(|binding| binding.type_name)
                .collect();

            tracing::warn!(
                connection = %query.connection,
                sql = %query.sql,
                bindings = ?types,
                elapsed = %query.elapsed,
                location = %query.location,
                "Slow query",
            );
        }
    });
})
```

The listener receives a `QueryInfo` for every successful query across all connections, including the begins, commits, rollbacks, and savepoints of [transactions](#transactions), exposing `connection`, `sql`, `elapsed`, `location`, and `bindings`. Each entry in `query.bindings` provides the parameter's Rust `type_name` while leaving `value` as `None` by default so passwords and tokens stay out of your logs.

<a name="native-sqlx-access"></a>
## Native SQLx access

When you need something Laravel doesn't wrap, such as a type only one database has, use SQLx directly. Laravel re-exports it as `laravel::db::sqlx`. `db::default_connection_for` and `db::connection_for` return a connection for one driver, whose queries bind values with `bind` and return SQLx's own rows:

```rust
use laravel::db::{self, sqlx::{Postgres, Row}};

let connection = db::default_connection_for::<Postgres>()?;

let rows = connection
    .query("SELECT name FROM users WHERE tags @> $1")
    .bind(vec!["beta"])
    .select()
    .await?;

let names = rows.iter().map(|row| row.try_get("name")).collect::<Result<Vec<String>, _>>()?;
```

PostgreSQL numbers its placeholders `$1`, `$2`, and so on, while MySQL and SQLite use `?`. For SQLx's own query functions, check out a native connection from the pool with `acquire`. It goes back to the pool when you drop it, so drop it as soon as you're done:

```rust
let mut native = connection.acquire().await?;

let count: i64 = db::sqlx::query_scalar("SELECT count(*) FROM users")
    .fetch_one(&mut *native)
    .await?;
```

In a transaction that you begin on such a connection, run SQLx queries on `tx.native()` instead, so they join the transaction.

Queries you run on a native connection skip Laravel's query listeners and sticky reads. After writing through one on a sticky connection, call `connection.set_record_modification_state(true)`.

<a name="testing"></a>
## Testing

Tests that touch the database need tables to query and a clean slate each time. New applications call [`refresh_database`](testing.md#refreshing-the-database) in `src/testing.rs` so each test starts from your migrations and rolls back when it ends. For a complete overview of database assertions, seeding, and refreshing the database in tests, see [testing the database](testing.md#testing-the-database).