keelson-gen 0.1.1

keelson's code generator: introspect a live schema, emit readable model .rs files against keelson-models.
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
// @generated by keelson-gen. DO NOT EDIT.
// Regenerate from the schema instead; hand-written code (hooks included)
// belongs outside this directory.

/// The model marker `comments::table()` hangs off.
#[derive(Debug, Clone, Copy)]
pub struct Comments;
/// One row of `comments`.
#[derive(Debug, Clone, PartialEq)]
pub struct Comment {
    pub id: i32,
    pub post_id: i32,
    pub user_id: Option<i32>,
    pub body: String,
    pub created_at: chrono::NaiveDateTime,
    /// Relations, filled by `preload`/`then_load` mods; empty otherwise.
    pub rel: Rel,
}
/// `comments`' relations.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Rel {
    /// Belongs-to `posts`, via `comments.post_id`.
    pub post: Option<Box<super::posts::Post>>,
    /// Belongs-to `users`, via `comments.user_id`.
    pub user: Option<Box<super::users::User>>,
}
impl keelson_exec::FromRow for Comment {
    fn from_row(row: &mut keelson_exec::Row) -> Result<Self, keelson_exec::ExecError> {
        Ok(Comment {
            id: row.take("id")?,
            post_id: row.take("post_id")?,
            user_id: row.take("user_id")?,
            body: row.take("body")?,
            created_at: row.take("created_at")?,
            rel: Rel::default(),
        })
    }
}
/// The three-state setter: unset fields stay out of the statement.
#[derive(Debug, Clone, Default)]
pub struct Setter {
    pub id: keelson_models::Set<i32>,
    pub post_id: keelson_models::Set<i32>,
    pub user_id: keelson_models::Set<i32>,
    pub body: keelson_models::Set<String>,
    pub created_at: keelson_models::Set<chrono::NaiveDateTime>,
}
/// The entry point: `comments::table().query(…)` / `.insert(…)` / ….
pub fn table() -> Comments {
    Comments
}
pub fn id() -> keelson_models::Column<i32> {
    keelson_models::Column::new("comments", "id")
}
pub fn post_id() -> keelson_models::Column<i32> {
    keelson_models::Column::new("comments", "post_id")
}
pub fn user_id() -> keelson_models::Column<i32> {
    keelson_models::Column::new("comments", "user_id")
}
pub fn body() -> keelson_models::Column<String> {
    keelson_models::Column::new("comments", "body")
}
pub fn created_at() -> keelson_models::Column<chrono::NaiveDateTime> {
    keelson_models::Column::new("comments", "created_at")
}
#[allow(clippy::type_complexity)]
fn all_columns() -> (
    keelson_models::Column<i32>,
    keelson_models::Column<i32>,
    keelson_models::Column<i32>,
    keelson_models::Column<String>,
    keelson_models::Column<chrono::NaiveDateTime>,
) {
    (id(), post_id(), user_id(), body(), created_at())
}
impl keelson_models::View for Comments {
    type Row = Comment;
    type Select = keelson_mysql::SelectQuery;
    fn base_select() -> Self::Select {
        keelson_mysql::select((
            keelson_mysql::select::columns(all_columns()),
            keelson_mysql::select::from(keelson_mysql::quote("comments")),
        ))
    }
}
impl keelson_models::Table for Comments {
    type Pk = i32;
    type Setter = Setter;
    type Insert = keelson_mysql::InsertQuery;
    type Update = keelson_mysql::UpdateQuery;
    type Delete = keelson_mysql::DeleteQuery;
    fn insert_query(s: Setter) -> Self::Insert {
        let mut cols: Vec<&'static str> = Vec::new();
        let mut vals: Vec<keelson_core::expr::Expr> = Vec::new();
        s.id.push_into("id", &mut cols, &mut vals);
        s.post_id.push_into("post_id", &mut cols, &mut vals);
        s.user_id.push_into("user_id", &mut cols, &mut vals);
        s.body.push_into("body", &mut cols, &mut vals);
        s.created_at.push_into("created_at", &mut cols, &mut vals);
        let mut q = keelson_mysql::insert(
            keelson_mysql::insert::into(keelson_mysql::quote("comments")).columns(cols),
        );
        if !vals.is_empty() {
            q.apply(keelson_mysql::insert::values(vals));
        }
        q
    }
    fn update_query() -> Self::Update {
        keelson_mysql::update(
            keelson_mysql::update::table(keelson_mysql::quote("comments")),
        )
    }
    fn apply_setter(s: Setter, q: &mut Self::Update) {
        if let Some(v) = s.id.into_expr() {
            q.apply(keelson_mysql::update::set_col("id").to(v));
        }
        if let Some(v) = s.post_id.into_expr() {
            q.apply(keelson_mysql::update::set_col("post_id").to(v));
        }
        if let Some(v) = s.user_id.into_expr() {
            q.apply(keelson_mysql::update::set_col("user_id").to(v));
        }
        if let Some(v) = s.body.into_expr() {
            q.apply(keelson_mysql::update::set_col("body").to(v));
        }
        if let Some(v) = s.created_at.into_expr() {
            q.apply(keelson_mysql::update::set_col("created_at").to(v));
        }
    }
    fn delete_query() -> Self::Delete {
        keelson_mysql::delete(
            keelson_mysql::delete::from(keelson_mysql::quote("comments")),
        )
    }
    fn pk(row: &Comment) -> Self::Pk {
        row.id
    }
}
impl Comments {
    /// A `SELECT` over this model — the dialect-generic path.
    pub fn query(
        self,
        mods: impl keelson_core::Mod<keelson_models::ModelSelect<Comments>>,
    ) -> keelson_models::ModelSelect<Comments> {
        keelson_models::ModelTable::<Comments>::new().query(mods)
    }
    /// An `INSERT` of the setter's set fields, read back by key.
    pub fn insert(self, setter: Setter) -> Insert {
        Insert { setter, mods: Vec::new() }
    }
    /// An `UPDATE` of the setter's set fields — `exec` only.
    pub fn update(
        self,
        setter: Setter,
        mods: impl keelson_core::Mod<keelson_models::ModelUpdate<Comments>>,
    ) -> Update {
        Update(keelson_models::ModelTable::<Comments>::new().update(setter, mods))
    }
    /// A `DELETE` — `exec` only.
    pub fn delete(
        self,
        mods: impl keelson_core::Mod<keelson_models::ModelDelete<Comments>>,
    ) -> Delete {
        Delete(keelson_models::ModelTable::<Comments>::new().delete(mods))
    }
}
/// A pending `INSERT` on `comments`: the setter, held unbuilt so `before_insert` can still rewrite it, plus the deferred Layer 1 mods.
pub struct Insert {
    setter: Setter,
    #[allow(clippy::type_complexity)]
    mods: Vec<Box<dyn FnOnce(&mut keelson_mysql::InsertQuery) + Send>>,
}
impl std::fmt::Debug for Insert {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Insert")
            .field("setter", &self.setter)
            .field("mods", &self.mods.len())
            .finish()
    }
}
impl Insert {
    /// Defer Layer 1 mods onto the eventual statement.
    #[must_use]
    pub fn with(
        mut self,
        mods: impl keelson_core::Mod<keelson_mysql::InsertQuery> + Send + 'static,
    ) -> Self {
        self.mods.push(Box::new(move |q| mods.apply(q)));
        self
    }
    /// Insert, then read the row back by key. **Not** `RETURNING`: the two statements are not atomic — see the module's dialect notes.
    pub async fn one(
        self,
        db: &dyn keelson_exec::Executor,
    ) -> Result<Comment, keelson_exec::ExecError> {
        use keelson_exec::Execute as _;
        let Insert { mut setter, mods } = self;
        <Comments as keelson_models::Table>::before_insert(db, &mut setter).await?;
        let k0 = match &setter.id {
            keelson_models::Set::Value(v) => Some(*v),
            _ => None,
        };
        let mut q = <Comments as keelson_models::Table>::insert_query(setter);
        for m in mods {
            m(&mut q);
        }
        let done = q.execute(db).await?;
        let k0: i32 = k0
            .or_else(|| {
                done
                    .last_insert_id
                    .and_then(|id| {
                        <i32 as std::convert::TryFrom<i64>>::try_from(id).ok()
                    })
            })
            .ok_or_else(|| keelson_exec::ExecError::other(
                "comments: the INSERT set no `id` and MySQL reported no last_insert_id, so the inserted row cannot be read back",
            ))?;
        let row: Comment = by_pk(k0).fetch_one(db).await?;
        <Comments as keelson_models::Table>::after_insert(db, std::slice::from_ref(&row))
            .await?;
        Ok(row)
    }
    /// Insert for the side effect. `after_insert` still runs, with an empty row slice.
    pub async fn exec(
        self,
        db: &dyn keelson_exec::Executor,
    ) -> Result<keelson_exec::ExecResult, keelson_exec::ExecError> {
        use keelson_exec::Execute as _;
        let Insert { mut setter, mods } = self;
        <Comments as keelson_models::Table>::before_insert(db, &mut setter).await?;
        let mut q = <Comments as keelson_models::Table>::insert_query(setter);
        for m in mods {
            m(&mut q);
        }
        let done = q.execute(db).await?;
        <Comments as keelson_models::Table>::after_insert(db, &[]).await?;
        Ok(done)
    }
}
/// The keyed read-back: `comments`'s own columns, filtered by primary key. This is what stands in for `RETURNING` — a second statement, emitted as a function so its SQL is judged like any other.
pub fn by_pk(k0: i32) -> keelson_mysql::SelectQuery {
    keelson_mysql::select((
        keelson_mysql::select::columns(all_columns()),
        keelson_mysql::select::from(keelson_mysql::quote("comments")),
        id().eq(k0),
    ))
}
/// A pending `UPDATE`. `exec` only: with no `RETURNING` there is nothing for an `all` verb to decode.
#[derive(Debug)]
pub struct Update(keelson_models::ModelUpdate<Comments>);
impl Update {
    /// Apply mods written against the concrete statement.
    pub fn apply(&mut self, mods: impl keelson_core::Mod<keelson_mysql::UpdateQuery>) {
        self.0.apply(mods);
    }
    /// Update for the side effect; answers how many rows changed.
    pub async fn exec(
        self,
        db: &dyn keelson_exec::Executor,
    ) -> Result<keelson_exec::ExecResult, keelson_exec::ExecError> {
        self.0.exec(db).await
    }
}
/// A pending `DELETE`. `exec` only, for the same reason as `Update`.
#[derive(Debug)]
pub struct Delete(keelson_models::ModelDelete<Comments>);
impl Delete {
    /// Apply mods written against the concrete statement.
    pub fn apply(&mut self, mods: impl keelson_core::Mod<keelson_mysql::DeleteQuery>) {
        self.0.apply(mods);
    }
    /// Delete for the side effect; answers how many rows went.
    pub async fn exec(
        self,
        db: &dyn keelson_exec::Executor,
    ) -> Result<keelson_exec::ExecResult, keelson_exec::ExecError> {
        self.0.exec(db).await
    }
}
/// Preload mods: the relation joins into the *same* query — no second statement, and deliberately no `.then(…)`. A level below a join has no distinct child set to key on, so a nested path is spelled with `then_load` (see `keelson_models::ThenLoad`).
pub mod preload {
    /// Same-query `LEFT JOIN` preload of the to-one `post`.
    pub fn post() -> impl keelson_core::Mod<
        keelson_models::ModelSelect<super::Comments>,
    > {
        keelson_core::mod_fn(|q: &mut keelson_models::ModelSelect<super::Comments>| {
            use keelson_mysql::Chain as _;
            use keelson_mysql::Mod as _;
            (
                keelson_mysql::select::left_join(keelson_mysql::quote("posts"))
                    .on(
                        keelson_mysql::quote(("posts", "id"))
                            .eq(keelson_mysql::quote(("comments", "post_id"))),
                    ),
                keelson_mysql::select::preload_columns((
                    keelson_mysql::quote(("posts", "id")).as_("post.id"),
                    keelson_mysql::quote(("posts", "user_id")).as_("post.user_id"),
                    keelson_mysql::quote(("posts", "title")).as_("post.title"),
                    keelson_mysql::quote(("posts", "status")).as_("post.status"),
                    keelson_mysql::quote(("posts", "views")).as_("post.views"),
                    keelson_mysql::quote(("posts", "published_at"))
                        .as_("post.published_at"),
                )),
            )
                .apply(q);
            q.add_mapper_mod(
                keelson_models::mapper_mod(|row, parent: &mut super::Comment| {
                    parent.rel.post = post_from_preload(row)?.map(Box::new);
                    Ok(())
                }),
            );
        })
    }
    /// Decode the prefixed columns; the joined key column decides a `LEFT JOIN` miss.
    pub fn post_from_preload(
        row: &mut keelson_exec::Row,
    ) -> Result<Option<super::super::posts::Post>, keelson_exec::ExecError> {
        if matches!(row.value("post.id"), None | Some(keelson_mysql::Value::Null)) {
            return Ok(None);
        }
        Ok(
            Some(super::super::posts::Post {
                id: row.take("post.id")?,
                user_id: row.take("post.user_id")?,
                title: row.take("post.title")?,
                status: row.take("post.status")?,
                views: row.take("post.views")?,
                published_at: row.take("post.published_at")?,
                rel: super::super::posts::Rel::default(),
            }),
        )
    }
    /// Same-query `LEFT JOIN` preload of the to-one `user`.
    pub fn user() -> impl keelson_core::Mod<
        keelson_models::ModelSelect<super::Comments>,
    > {
        keelson_core::mod_fn(|q: &mut keelson_models::ModelSelect<super::Comments>| {
            use keelson_mysql::Chain as _;
            use keelson_mysql::Mod as _;
            (
                keelson_mysql::select::left_join(keelson_mysql::quote("users"))
                    .on(
                        keelson_mysql::quote(("users", "id"))
                            .eq(keelson_mysql::quote(("comments", "user_id"))),
                    ),
                keelson_mysql::select::preload_columns((
                    keelson_mysql::quote(("users", "id")).as_("user.id"),
                    keelson_mysql::quote(("users", "name")).as_("user.name"),
                    keelson_mysql::quote(("users", "email")).as_("user.email"),
                    keelson_mysql::quote(("users", "age")).as_("user.age"),
                    keelson_mysql::quote(("users", "is_active")).as_("user.is_active"),
                    keelson_mysql::quote(("users", "created_at")).as_("user.created_at"),
                )),
            )
                .apply(q);
            q.add_mapper_mod(
                keelson_models::mapper_mod(|row, parent: &mut super::Comment| {
                    parent.rel.user = user_from_preload(row)?.map(Box::new);
                    Ok(())
                }),
            );
        })
    }
    /// Decode the prefixed columns; the joined key column decides a `LEFT JOIN` miss.
    pub fn user_from_preload(
        row: &mut keelson_exec::Row,
    ) -> Result<Option<super::super::users::User>, keelson_exec::ExecError> {
        if matches!(row.value("user.id"), None | Some(keelson_mysql::Value::Null)) {
            return Ok(None);
        }
        Ok(
            Some(super::super::users::User {
                id: row.take("user.id")?,
                name: row.take("user.name")?,
                email: row.take("user.email")?,
                age: row.take("user.age")?,
                is_active: row.take("user.is_active")?,
                created_at: row.take("user.created_at")?,
                rel: super::super::users::Rel::default(),
            }),
        )
    }
}
/// Then-load mods: one keyed, batched query per level of a load path — `then_load::a().then(b::then_load::c())` is two levels, two queries, checked by the compiler.
pub mod then_load {
    /// Load each row's `post` (to-one), one keyed query per batch of keys — `.then(…)` hangs the next level of the path off this one.
    pub fn post() -> keelson_models::ThenLoad<
        super::Comments,
        super::super::posts::Posts,
        i32,
    > {
        keelson_models::ThenLoad::new(
            |rows: &[super::Comment]| rows.iter().map(|r| r.post_id).collect(),
            |keys, q| keelson_core::Mod::apply(super::super::posts::id().in_(keys), q),
            |rows: &mut [super::Comment], related| {
                keelson_models::attach_to_one(
                    rows,
                    related,
                    |r| r.post_id,
                    |c| c.id,
                    |r, c| {
                        r.rel.post = c.map(Box::new);
                    },
                );
            },
        )
    }
    /// Load each row's `user` (to-one), one keyed query per batch of keys — `.then(…)` hangs the next level of the path off this one.
    pub fn user() -> keelson_models::ThenLoad<
        super::Comments,
        super::super::users::Users,
        i32,
    > {
        keelson_models::ThenLoad::new(
            |rows: &[super::Comment]| rows.iter().filter_map(|r| r.user_id).collect(),
            |keys, q| keelson_core::Mod::apply(super::super::users::id().in_(keys), q),
            |rows: &mut [super::Comment], related| {
                keelson_models::attach_to_one(
                    rows,
                    related,
                    |r| r.user_id,
                    |c| Some(c.id),
                    |r, c| {
                        r.rel.user = c.map(Box::new);
                    },
                );
            },
        )
    }
}