Skip to content

Commit 3a9cc9e

Browse files
committed
Add filter() support, update pagination
1 parent 007ace8 commit 3a9cc9e

4 files changed

Lines changed: 254 additions & 69 deletions

File tree

README.md

Lines changed: 110 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,20 @@
44

55
A utility to generate database structs and querying code from diesel schema files. Primarily built for [create-rust-app](https://github.com/Wulf/create-rust-app).
66

7+
**Why?**
8+
79
Currently, it's more advantageous to generate code over deriving code with macros because intellisense and autocompletion isn't quite there when it comes to macro expansion.
810

11+
**Migrating from v0 to v1? See migration notes below.**
12+
13+
## Features
14+
15+
- Supports `diesel-async` (enable `async` feature flag)
16+
- Generates structs based on your `schema.rs` file (see the `test/simple_table` folder for sample output)
17+
- Optionally generates CRUD functions and helper methods
18+
- Use as a binary or library (read more below)
19+
- Many options (see `GenerationConfig` in `lib.rs`) -- you have the ability to customize generated code for specific tables; or entirely ignore a specific table!
20+
921
## Demo
1022

1123
Given the following schema:
@@ -30,20 +42,47 @@ cargo dsync -i schema.rs -o models
3042
Now we have everything we need!
3143

3244
```rust
33-
use models::todos;
34-
3545
async fn demo(db: Connection) {
36-
let created_todo = todos::create(&mut db, todos::CreateTodo {
46+
/*
47+
CRUD examples
48+
*/
49+
let created_todo = Todo::create(db, CreateTodo {
3750
text: "Create a demo",
3851
completed: false,
39-
}).await?;
40-
41-
let todos_list = todos::paginate(&mut db, 1, 10).await?;
42-
43-
let updated_todo = todos::update(&mut db, created_todo.id, UpdateTodo {
52+
})?;
53+
54+
let todos_list = Todo::paginate(db, 1, 10)?;
55+
56+
let read_todo = Todo::read(db, created_todo.id)?;
57+
58+
let updated_todo = Todo::update(db, created_todo.id, UpdateTodo {
4459
text: created_todo.text,
4560
completed: true,
46-
}).await?;
61+
})?;
62+
63+
let deleted_todo = Todo::delete(db, created_todo.id)?;
64+
65+
/*
66+
Use the "Filter" helper
67+
--> Works well with intellisense! <--
68+
--> Easily create reusable/portable queries! <--
69+
70+
(Support for date/time and other types coming soon)
71+
*/
72+
73+
// example: fetch incomplete todos
74+
let query = Todo::filter(TodoFilter {
75+
completed: Some(false),
76+
..Default::default()
77+
});
78+
let items: Vec<Todo> = query.load(db)?;
79+
80+
// example: delete completed todos
81+
let query = Todo::filter(TodoFilter {
82+
completed: Some(true),
83+
..Default::default()
84+
})
85+
diesel::delete(query).execute(db)?;
4786
}
4887
```
4988

@@ -59,66 +98,76 @@ For a complete example, see [`test/simple_table/schema.rs`](test/simple_table/sc
5998

6099
2. Create a new binary in your project which uses the crate (for example, `bin/dsync.rs`)
61100

62-
```rust
63-
use std::{collections::HashMap, path::PathBuf};
64-
use dsync::{GenerationConfig, TableOptions};
65-
66-
pub fn main() {
67-
let dir = env!("CARGO_MANIFEST_DIR");
68-
69-
dsync::generate_files(
70-
PathBuf::from_iter([dir, "src/schema.rs"]),
71-
PathBuf::from_iter([dir, "src/models"]),
72-
GenerationConfig { /* ... your generation options ... */ }
73-
);
74-
}
75-
```
101+
```rust
102+
use std::{collections::HashMap, path::PathBuf};
103+
use dsync::{GenerationConfig, TableOptions};
104+
105+
pub fn main() {
106+
let dir = env!("CARGO_MANIFEST_DIR");
107+
108+
dsync::generate_files(
109+
PathBuf::from_iter([dir, "src/schema.rs"]),
110+
PathBuf::from_iter([dir, "src/models"]),
111+
GenerationConfig { /* ... your generation options ... */ }
112+
);
113+
}
114+
```
76115
77116
3. Create a `Cargo.toml` binary entry:
78117
79-
```toml
80-
[[bin]]
81-
name = "dsync"
82-
path = "bin/dsync.rs"
83-
```
118+
```toml
119+
[[bin]]
120+
name = "dsync"
121+
path = "bin/dsync.rs"
122+
```
84123
85124
4. Execute!
86125
87-
```sh
88-
cargo run --bin dsync
89-
```
126+
```sh
127+
cargo run --bin dsync
128+
```
90129
91-
**Protip**: to use `cargo dsync`, create an alias in `.cargo/config`:
92-
93-
```toml
94-
[alias]
95-
dsync="run --bin dsync"
96-
```
130+
**Protip**: to use `cargo dsync`, create an alias in `.cargo/config`:
131+
132+
```toml
133+
[alias]
134+
dsync="run --bin dsync"
135+
```
97136
98137
### Pre-built binary
99138
100139
Setting up a custom binary allows you to completely customize the generation; however, if complete customization isn't necessary, you can install the CLI directly
101140
(you'll have to make sure you keep it up-to-date by running this periodically):
102141
103142
```sh
104-
cargo install dsync
143+
cargo install dsync
105144
```
106145
107146
**CLI Usage**
108147
109-
* `-i`: input argument: path to schema file
110-
* `-o`: output argument: path to directory where generated code should be written
111-
* `-c`: connection type (for example: `diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>`)
112-
* `-g`: (optional) list of columns that are automatically generated by create/update triggers (for example, `created_at`, `updated_at`)
113-
* `--tsync`: (optional) adds `#[tsync]` attribute to generated structs (see <https://github.com/Wulf/tsync>)
114-
* `--model-path`: (optional) set a custom model import path, default `crate::models::`
115-
* `--schema-path`: (optional) set a custom schema import path, default `crate::schema::`
116-
* `--no-serde`: (optional) if set, does not output any serde related code
117-
* `--no-crud`: (optional) Do not generate the CRUD functions for generated models
118-
* `--create-str`: (optional) Set which string type to use for `Create*` structs (possible are `string`, `str`, `cow`)
119-
* `--update-str`: (optional) Set which string type to use for `Update*` structs (possible are `string`, `str`, `cow`)
120-
* `--single-model-file`: (optional) Generate only a single model file, instead of a directory with `mod.rs` and `generated.rs`
121-
* note: the CLI has fail-safes to prevent accidental file overwriting
148+
- `-i`: input argument: path to schema file
149+
- `-o`: output argument: path to directory where generated code should be written
150+
- `-c`: connection type that implements `diesel::connection::Connection`. For example:
151+
- `diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>`,
152+
- `diesel::pg::PgConnection`
153+
- `diesel::sqlite::SqliteConnection`
154+
- `diesel::mysql::MysqlConnection`
155+
- or, your custom diesel connection type!
156+
- `-g`: (optional) list of columns that are automatically generated by create/update triggers (for example, `created_at`, `updated_at`)
157+
- `--tsync`: (optional) adds `#[tsync]` attribute to generated structs (see <https://github.com/Wulf/tsync>)
158+
- `--model-path`: (optional) set a custom model import path, default `crate::models::`
159+
- `--schema-path`: (optional) set a custom schema import path, default `crate::schema::`
160+
- `--no-serde`: (optional) if set, does not output any serde related code
161+
- `--no-crud`: (optional) Do not generate the CRUD functions for generated models
162+
- `--create-str`: (optional) Set which string type to use for `Create*` structs (possible are `string`, `str`, `cow`)
163+
- `--update-str`: (optional) Set which string type to use for `Update*` structs (possible are `string`, `str`, `cow`)
164+
- `--single-model-file`: (optional) Generate only a single model file, instead of a directory with `mod.rs` and `generated.rs`
165+
- `--diesel-backend`: (optional) Specifies the diesel backend type (something which implements `diesel::backend::Backend`). For example:
166+
- `diesel::pg::Pg`,
167+
- `diesel::sqlite::Sqlite`,
168+
- `diesel::mysql::Mysql`,
169+
- or your own type!
170+
- note: the CLI has fail-safes to prevent accidental file overwriting
122171
123172
```sh
124173
dsync -i src/schema.rs -o src/models
@@ -130,6 +179,16 @@ See `dsync --help` for more information.
130179
131180
Feel free to open tickets for support or feature requests.
132181
182+
## Migrating from v0 to v1
183+
184+
- For those that use plural table names: English-based pluralization is no longer handled. If you had a table named `todos`, dsync will not generate a struct named `Todo` anymore, but instead, `struct Todos` will be generated. It might be easier to rename your tables entirely to singular case.
185+
- Replace all instances of `/* This file is generated and managed by dsync */` with `/* @generated and managed by dsync */` in your generated model files.
186+
- If using `dsync` as a library, add `..Default::default()` at the end of your args for the `GenerationConfig` struct. It sets the following new params to their default values:
187+
- `once_common_structs: true`,
188+
- `once_connection_type: true`,
189+
- `diesel_backend: "diesel::pg::Pg"`,
190+
- #[tsync] attributes are no longer included by default. To enable them, change the default table config options or supply `--tsync` if using the CLI.
191+
133192
## Development/Testing
134193
135194
Use `./test/test_all.sh` to run tests.

src/bin/main.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,18 @@ pub struct MainOptions {
102102
/// Generate the "ConnectionType" type only once in a "common.rs" file
103103
#[arg(long = "once-connection-type")]
104104
pub once_connection_type: bool,
105+
106+
/// Set which diesel backend to use (something which implements `diesel::backend::Backend`)
107+
/// Deisel provides the following backends:
108+
/// - `diesel::pg::Pg`
109+
/// - `diesel::sqlite::Sqlite`
110+
/// - `diesel::mysql::Mysql`
111+
///
112+
/// See `crate::GenerationConfig::diesel_backend` for more details.
113+
///
114+
/// Default is "diesel::pg::Pg"
115+
#[arg(long = "diesel-backend", default_value = "diesel::pg::Pg")]
116+
pub diesel_backend: String,
105117
}
106118

107119
#[derive(Debug, ValueEnum, Clone, PartialEq, Default)]
@@ -203,6 +215,7 @@ fn actual_main() -> dsync::Result<()> {
203215
model_path: args.model_path,
204216
once_common_structs: args.once_common_structs,
205217
once_connection_type: args.once_connection_type,
218+
diesel_backend: args.diesel_backend,
206219
},
207220
)?;
208221

0 commit comments

Comments
 (0)