Skip to content

Commit 1a62407

Browse files
committed
Replaced crud macros with functions
1 parent f2376d6 commit 1a62407

3 files changed

Lines changed: 57 additions & 58 deletions

File tree

docs/rorm/crud.md

Lines changed: 47 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
# CRUD
22

3-
To perform database operations, one of the four CRUD macros is invoked.
3+
To perform database operations, one of the four CRUD builders is used.
44

5-
They all take an executor as their first argument (i.e. `&Database` or `&mut Transaction`)
6-
and the model whose table to interact with as its second argument.
7-
8-
The macro evaluates into a builder whose methods can be chained to configure and execute the operation.
5+
They are all started by a function with two arguments.
6+
The first argument is an executor (i.e. `&Database` or `&mut Transaction`)
7+
and the second argument is the model whose table to interact with.
98

109
The following examples are written using these models:
1110

@@ -40,14 +39,14 @@ struct Post {
4039

4140
## Query
4241

43-
In order to retrieve data from the database the `query!` macro is used:
42+
To retrieve data from the database the `rorm::query` builder is used:
4443
```rust
4544
async fn query_example(db: &Database) -> Result<(), rorm::Error> {
46-
let all_users: Vec<User> = query!(db, User)
45+
let all_users: Vec<User> = rorm::query(db, User)
4746
.all()
4847
.await?;
4948

50-
let bob: Option<User> = query!(db, User)
49+
let bob: Option<User> = rorm::query(db, User)
5150
.condition(User.username.equals("bob"))
5251
.optional()
5352
.await;
@@ -59,25 +58,25 @@ async fn query_example(db: &Database) -> Result<(), rorm::Error> {
5958
}
6059
```
6160

62-
The last method called on the macro specifies how the query is resolved. The following four are available:
61+
The last method called on the builder specifies how the query is resolved. The following four are available:
6362

6463
### `all()`
6564
Executes the query in a future which resolves to all rows matching the query.
6665
```rust
67-
let all_users: Vec<User> = query!(&db, User).all().await.unwrap();
66+
let all_users: Vec<User> = rorm::query(&db, User).all().await.unwrap();
6867
```
6968

7069
### `one()`
7170
Executes the query in a future which resolves to exactly one row.
7271
(If no matching row is found, this will be treated as an error)
7372
```rust
74-
let user: User = query!(&db, User).one().await.unwrap();
73+
let user: User = rorm::query(&db, User).one().await.unwrap();
7574
```
7675

7776
### `optional()`
7877
Executes the query in a future which resolves to at most one row.
7978
```rust
80-
let user: Option<User> = query!(&db, User).optional().await.unwrap();
79+
let user: Option<User> = rorm::query(&db, User).optional().await.unwrap();
8180
```
8281

8382
### `stream()`
@@ -110,7 +109,7 @@ Non-exhaustive list of commonly used ones:
110109

111110
Conditions can then be combined using the `or!` and `and!` macros:
112111
```rust
113-
query!(db, User)
112+
rorm::query(db, User)
114113
.condition(and!(
115114
User.username.equals("alice"),
116115
User.password.equals(leaked_pw)
@@ -120,16 +119,16 @@ query!(db, User)
120119

121120
### Customize what to select
122121

123-
In its most basic usage (`query!(db, User)`) the query will select every column and return them in the model's struct.
122+
In its most basic usage (`rorm::query(db, User)`) the query will select every column and return them in the model's struct.
124123

125-
This can be customized by changing the macro's second argument.
124+
This can be customized by changing the function's second argument.
126125

127126
!!! note
128-
The `query!` macro is somewhat unique in regard to its second argument.
127+
The `rorm::query` builder is somewhat unique in regard to its second argument.
129128

130-
The other macros won't behave comparibly.
129+
The other builders won't behave comparibly.
131130

132-
As simplest alternative a `Patch` can be specified instead of the whole `Model` to only select some columns:
131+
As the simplest alternative a `Patch` can be specified instead of the whole `Model` to only select some columns:
133132

134133
```rust
135134
#[derive(Patch)]
@@ -141,7 +140,7 @@ struct UserWithoutPassword {
141140
}
142141

143142
// Query every field from the struct UserWithoutPassword
144-
let users: Vec<UserWithoutPassword> = query!(db, UserWithoutPassword).all().await?;
143+
let users: Vec<UserWithoutPassword> = rorm::query(db, UserWithoutPassword).all().await?;
145144
```
146145

147146
This can get quite annoying when you have to specify a struct for every combination of fields you might want to query together.
@@ -150,13 +149,13 @@ Therefore, you can use the field syntax to query tuples of fields:
150149
```rust
151150
// Only query the user's id and username
152151
let users: Vec<(i64, String)> =
153-
query!(db, (User.id, User.username)).all().await?;
152+
rorm::query(db, (User.id, User.username)).all().await?;
154153
```
155154

156155
This syntax also work with relations:
157156
```rust
158157
let posts: Vec<(String, String)> =
159-
query!(db, (Post.message, Post.user.username)).all().await?;
158+
rorm::query(db, (Post.message, Post.user.username)).all().await?;
160159
```
161160

162161
When you want to select your relations' fields and there are a lot of them, specifying them all like this can get quite verbose.
@@ -165,7 +164,7 @@ To mitigate this, there is a syntax combining individual fields with patches:
165164

166165
```rust
167166
let posts: Vec<(String, UserWithoutPassword)> =
168-
query!(db, (Post.message, Post.user as UserWithoutPassword)).all().await?;
167+
rorm::query(db, (Post.message, Post.user.query_as(UserWithoutPassword))).all().await?;
169168
```
170169

171170
#### Limit & offset
@@ -175,18 +174,18 @@ to the SQL query. Note that `.limit()` can not be combined with `.one()`, since
175174
Also, the `.offset()` can not be used without a limit. The following examples illustrate possible uses:
176175

177176
```rust
178-
query!(db, Post).limit(10).all().await?;
179-
query!(db, Post).offset(13).one().await?;
180-
query!(db, Post).limit(10).offset(42).all().await?;
181-
query!(db, Post).limit(100).offset(1337).stream();
177+
rorm::query(db, Post).limit(10).all().await?;
178+
rorm::query(db, Post).offset(13).one().await?;
179+
rorm::query(db, Post).limit(10).offset(42).all().await?;
180+
rorm::query(db, Post).limit(100).offset(1337).stream();
182181
```
183182

184183
There is also the `.range()` function which provides a convenient way to add both the limit and offset.
185184
Mixing a range with the previous functions for limit and offset is not allowed.
186185
Thus, the following example will return at most 10 elements since it corresponds to limit 10 and offset 30:
187186

188187
```rust
189-
query!(db, Post).range(30..40).all().await?;
188+
rorm::query(db, Post).range(30..40).all().await?;
190189
```
191190

192191
#### Ordering
@@ -195,7 +194,7 @@ TODO: `order_...`
195194

196195
## Insert
197196

198-
In order to create new rows in the database, the `insert!` macro is used:
197+
To create new rows in the database, the `rorm::insert` builder is used:
199198

200199
```rust
201200
#[derive(Patch)]
@@ -214,14 +213,14 @@ struct NewPost {
214213

215214
async fn insert_example(db: &Database) -> Result<(), rorm::Error> {
216215
// insert a single user
217-
insert!(db, NewUser).single(&NewUser {
216+
rorm::insert(db, NewUser).single(&NewUser {
218217
username: "alice".to_string(),
219218
password: "Secure-123".to_string(),
220219
}).await?;
221220

222221
// insert a collection of user posts
223222
let posts: Vec<> = vec![...];
224-
insert!(db, NewPost).bulk(&posts).await?;
223+
rorm::insert(db, NewPost).bulk(&posts).await?;
225224

226225
Ok(())
227226
}
@@ -238,7 +237,7 @@ But what if you need the values of fields which are set by the database?
238237

239238
### Returning
240239

241-
The `insert!` macro returns the whole model it just inserted:
240+
The `rorm::insert` builder returns the whole model it just inserted:
242241

243242
```rust
244243
#[derive(Patch)]
@@ -249,38 +248,38 @@ struct NewUser {
249248
}
250249

251250
// Note that the type `User` is returned instead of just a `NewUser`
252-
let new_user: User = insert!(db, NewUser).single(&NewUser {..}).await?;
251+
let new_user: User = rorm::insert(db, NewUser).single(&NewUser {..}).await?;
253252
```
254253

255-
To customize the behaviour, a family of `.return_...()` methods are provided:
254+
To customize the behavior, a family of `.return_...()` methods are provided:
256255
```rust
257256
pub async fn show_various_returns(db: &Database, user: &NewUser) -> Result<(), Error> {
258257
// Return model instance by default
259-
let _: User = insert!(db, NewUser)
258+
let _: User = rorm::insert(db, NewUser)
260259
.single(user)
261260
.await?;
262261

263262
// Return a patch's instance instead of whole model
264263
// (including the one used to insert and the model itself)
265-
let _: AnotherUserPatch = insert!(db, NewUser)
264+
let _: AnotherUserPatch = rorm::insert(db, NewUser)
266265
.return_patch::<UserPatch>()
267266
.single(user)
268267
.await?;
269268

270269
// Return a tuple of fields
271-
let _: (i64, String) = insert!(db, NewUser)
270+
let _: (i64, String) = rorm::insert(db, NewUser)
272271
.return_tuple((User.id, User.name))
273272
.single(user)
274273
.await?;
275274

276275
// Return the model's primary key
277-
let _: i64 = insert!(db, NewUser)
276+
let _: i64 = rorm::insert(db, NewUser)
278277
.return_primary_key()
279278
.single(user)
280279
.await?;
281280

282281
// Return nothing
283-
let _: () = insert!(db, NewUser)
282+
let _: () = rorm::insert(db, NewUser)
284283
.return_nothing()
285284
.single(user)
286285
.await?;
@@ -291,11 +290,11 @@ pub async fn show_various_returns(db: &Database, user: &NewUser) -> Result<(), E
291290

292291
## Update
293292

294-
In order to change models' fields the `update!` macro is used:
293+
To change models' fields the `rorm::update` builder is used:
295294

296295
```rust
297296
pub async fn set_good_password(db: &Database) -> Result<(), rorm::Error> {
298-
update!(db, User)
297+
rorm::update(db, User)
299298
.set(User.password, "I am way more secure™".to_string())
300299
.condition(User.password.equals("password"))
301300
.await?;
@@ -307,7 +306,7 @@ pub async fn set_good_password(db: &Database) -> Result<(), rorm::Error> {
307306

308307
Before executing the query, `set` has to be called at least once
309308
to set a value for a column (the first call changes the builder's type).
310-
Otherwise the query wouldn't do anything.
309+
Otherwise, the query wouldn't do anything.
311310

312311
This can be limiting when your calls are made conditionally.
313312

@@ -325,7 +324,7 @@ async fn update_user(
325324
optional_new_username: Option<String>,
326325
optional_new_password: Option<String>
327326
) -> Result<(), rorm::Error> {
328-
let mut updater = update!(db, User).begin_dyn_set();
327+
let mut updater = rorm::update(db, User).begin_dyn_set();
329328

330329
if let Some(new_username) = optional_new_username {
331330
updater = updater.set(User.username, new_username);
@@ -351,7 +350,7 @@ async fn update_user(
351350
optional_new_username: Option<String>,
352351
optional_new_password: Option<String>
353352
) -> Result<(), rorm::Error> {
354-
let updater = update!(db, User)
353+
let updater = rorm::update(db, User)
355354
.begin_dyn_set()
356355
.set_if(User.username, optional_new_username)
357356
.set_if(User.password, optional_new_password);
@@ -367,30 +366,30 @@ async fn update_user(
367366

368367
## Delete
369368

370-
In order to delete rows from a table, the `delete!` macro is used:
369+
To delete rows from a table, the `rorm::delete` builder is used:
371370

372371
```rust
373372
pub async fn delete_single_user(db: &Database, user: &UserPatch) -> Result<(), rorm::Error> {
374-
delete!(db, User)
373+
rorm::delete(db, User)
375374
.single(user)
376375
.await?;
377376
Ok(())
378377
}
379378
pub async fn delete_many_users(db: &Database, users: &[UserPatch]) -> Result<(), rorm::Error> {
380-
delete!(db, User)
379+
rorm::delete(db, User)
381380
.bulk(users)
382381
.await?;
383382
Ok(())
384383
}
385384
pub async fn delete_underage(db: &Database) -> Result<(), rorm::Error> {
386-
let num_deleted: u64 = delete!(db, User)
385+
let num_deleted: u64 = rorm::delete(db, User)
387386
.condition(User.age.less_equals(18))
388387
.await?;
389388
Ok(())
390389
}
391390
```
392391

393-
A `delete!` is quite simple. It expects only one of four methods which specify what to delete:
392+
A `rorm::delete` is quite simple. It expects only one of four methods which specify what to delete:
394393

395394
### `.single(...)`
396395
To delete a single row, use the `single` method and pass it the model to delete.

docs/rorm/full_example.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ delete some. Note that this is just the most basic functionality, but
88
```rust
99
use std::fs::read_to_string;
1010

11-
use rorm::{delete, insert, update, query, Database};
11+
use rorm::Database;
1212
use rorm::config::DatabaseConfig;
1313
use serde::Deserialize;
1414

@@ -41,7 +41,7 @@ async fn main() {
4141
.expect("error connecting to the database");
4242

4343
// Query all users from the database
44-
for user in query!(&db, User)
44+
for user in rorm::query(&db, User)
4545
.all()
4646
.await
4747
.expect("querying failed")
@@ -53,7 +53,7 @@ async fn main() {
5353
}
5454

5555
// Add three new users to the database
56-
insert!(&db, UserNew)
56+
rorm::insert(&db, UserNew)
5757
.bulk(&[
5858
UserNew {
5959
username: "foo".to_string(),
@@ -71,22 +71,22 @@ async fn main() {
7171
.await;
7272

7373
// Update the second user by increasing its age
74-
let all_users = query!(&db, User).all().await.expect("error");
75-
update!(&db, User)
74+
let all_users = rorm::query(&db, User).all().await.expect("error");
75+
rorm::update(&db, User)
7676
.set(User.age, all_users[2].age + 1)
7777
.condition(User.id.equals(all_users[2].id))
7878
.await
7979
.expect("error");
8080

8181
// Delete some user with age 69 or older than 100 years
82-
let zero_aged_user = query!(&db, User)
82+
let zero_aged_user = rorm::query(&db, User)
8383
.condition(or!(
8484
User.age.greater(100),
8585
User.age.equals(69)
8686
))
8787
.one()
8888
.await
8989
.expect("error");
90-
delete!(&db, User).single(&zero_aged_user).await;
90+
rorm::delete(&db, User).single(&zero_aged_user).await;
9191
}
9292
```

docs/rorm/transactions.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ pub async fn create_user(
6565
let mut tx = db.start_transaction().await?;
6666

6767
// Check if the username is already taken
68-
let is_taken = query!(&mut tx, (User.id,))
68+
let is_taken = rorm::query(&mut tx, User.id)
6969
.condition(User.username.equals(&username))
7070
.optional()
7171
.await?
@@ -76,7 +76,7 @@ pub async fn create_user(
7676
}
7777

7878
// Insert the new user
79-
let id = insert!(&mut tx, UserInsert)
79+
let id = rorm::insert(&mut tx, UserInsert)
8080
.return_primary_key()
8181
.single(&UserInsert { username })
8282
.await
@@ -114,7 +114,7 @@ async fn create_user(username: String, exe: impl Executor<'_>) -> Result<(), ror
114114

115115
// It can be used very similar to a normal transaction
116116
// through `get_transaction`
117-
insert!(guard.get_transaction(), UserInsert)
117+
rorm::insert(guard.get_transaction(), UserInsert)
118118
.return_primary_key()
119119
.single(&UserInsert { username })
120120
.await?;

0 commit comments

Comments
 (0)