keelson-gen 0.1.0

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

/// The model marker `messages::table()` hangs off.
#[derive(Debug, Clone, Copy)]
pub struct Messages;
/// One row of `messages`.
#[derive(Debug, Clone, PartialEq)]
pub struct Message {
    pub id: i64,
    pub thread_id: i64,
    pub body: String,
    /// Relations, filled by `preload`/`then_load` mods; empty otherwise.
    pub rel: Rel,
}
/// `messages`' relations.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Rel {
    /// Belongs-to `threads`, via `messages.thread_id`.
    pub thread: Option<Box<super::threads::Thread>>,
    /// Has-many `threads`, via `threads.first_message_id`.
    pub threads: Vec<super::threads::Thread>,
}
impl keelson_exec::FromRow for Message {
    fn from_row(row: &mut keelson_exec::Row) -> Result<Self, keelson_exec::ExecError> {
        Ok(Message {
            id: row.take("id")?,
            thread_id: row.take("thread_id")?,
            body: row.take("body")?,
            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<i64>,
    pub thread_id: keelson_models::Set<i64>,
    pub body: keelson_models::Set<String>,
}
/// The entry point: `messages::table().query(…)` / `.insert(…)` / ….
pub fn table() -> keelson_models::ModelTable<Messages> {
    keelson_models::ModelTable::new()
}
pub fn id() -> keelson_models::Column<i64> {
    keelson_models::Column::new("messages", "id")
}
pub fn thread_id() -> keelson_models::Column<i64> {
    keelson_models::Column::new("messages", "thread_id")
}
pub fn body() -> keelson_models::Column<String> {
    keelson_models::Column::new("messages", "body")
}
#[allow(clippy::type_complexity)]
fn all_columns() -> (
    keelson_models::Column<i64>,
    keelson_models::Column<i64>,
    keelson_models::Column<String>,
) {
    (id(), thread_id(), body())
}
impl keelson_models::View for Messages {
    type Row = Message;
    type Select = keelson_sqlite::SelectQuery;
    fn base_select() -> Self::Select {
        keelson_sqlite::select((
            keelson_sqlite::select::columns(all_columns()),
            keelson_sqlite::select::from(keelson_sqlite::quote("messages")),
        ))
    }
}
impl keelson_models::Table for Messages {
    type Pk = i64;
    type Setter = Setter;
    type Insert = keelson_sqlite::InsertQuery;
    type Update = keelson_sqlite::UpdateQuery;
    type Delete = keelson_sqlite::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.thread_id.push_into("thread_id", &mut cols, &mut vals);
        s.body.push_into("body", &mut cols, &mut vals);
        let mut q = keelson_sqlite::insert((
            keelson_sqlite::insert::into(keelson_sqlite::quote("messages"))
                .columns(cols),
            keelson_sqlite::insert::returning(all_columns()),
        ));
        if !vals.is_empty() {
            q.apply(keelson_sqlite::insert::values(vals));
        }
        q
    }
    fn update_query() -> Self::Update {
        keelson_sqlite::update(
            keelson_sqlite::update::table(keelson_sqlite::quote("messages")),
        )
    }
    fn apply_setter(s: Setter, q: &mut Self::Update) {
        if let Some(v) = s.id.into_expr() {
            q.apply(keelson_sqlite::update::set_col("id").to(v));
        }
        if let Some(v) = s.thread_id.into_expr() {
            q.apply(keelson_sqlite::update::set_col("thread_id").to(v));
        }
        if let Some(v) = s.body.into_expr() {
            q.apply(keelson_sqlite::update::set_col("body").to(v));
        }
    }
    fn delete_query() -> Self::Delete {
        keelson_sqlite::delete(
            keelson_sqlite::delete::from(keelson_sqlite::quote("messages")),
        )
    }
    fn pk(row: &Message) -> Self::Pk {
        row.id
    }
}
/// 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 `thread`.
    pub fn thread() -> impl keelson_core::Mod<
        keelson_models::ModelSelect<super::Messages>,
    > {
        keelson_core::mod_fn(|q: &mut keelson_models::ModelSelect<super::Messages>| {
            use keelson_sqlite::Chain as _;
            use keelson_sqlite::Mod as _;
            (
                keelson_sqlite::select::left_join(keelson_sqlite::quote("threads"))
                    .on(
                        keelson_sqlite::quote(("threads", "id"))
                            .eq(keelson_sqlite::quote(("messages", "thread_id"))),
                    ),
                keelson_sqlite::select::preload_columns((
                    keelson_sqlite::quote(("threads", "id")).as_("thread.id"),
                    keelson_sqlite::quote(("threads", "title")).as_("thread.title"),
                    keelson_sqlite::quote(("threads", "first_message_id"))
                        .as_("thread.first_message_id"),
                )),
            )
                .apply(q);
            q.add_mapper_mod(
                keelson_models::mapper_mod(|row, parent: &mut super::Message| {
                    parent.rel.thread = thread_from_preload(row)?.map(Box::new);
                    Ok(())
                }),
            );
        })
    }
    /// Decode the prefixed columns; the joined key column decides a `LEFT JOIN` miss.
    pub fn thread_from_preload(
        row: &mut keelson_exec::Row,
    ) -> Result<Option<super::super::threads::Thread>, keelson_exec::ExecError> {
        if matches!(row.value("thread.id"), None | Some(keelson_sqlite::Value::Null)) {
            return Ok(None);
        }
        Ok(
            Some(super::super::threads::Thread {
                id: row.take("thread.id")?,
                title: row.take("thread.title")?,
                first_message_id: row.take("thread.first_message_id")?,
                rel: super::super::threads::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 `thread` (to-one), one keyed query per batch of keys — `.then(…)` hangs the next level of the path off this one.
    pub fn thread() -> keelson_models::ThenLoad<
        super::Messages,
        super::super::threads::Threads,
        i64,
    > {
        keelson_models::ThenLoad::new(
            |rows: &[super::Message]| rows.iter().map(|r| r.thread_id).collect(),
            |keys, q| keelson_core::Mod::apply(super::super::threads::id().in_(keys), q),
            |rows: &mut [super::Message], related| {
                keelson_models::attach_to_one(
                    rows,
                    related,
                    |r| r.thread_id,
                    |c| c.id,
                    |r, c| {
                        r.rel.thread = c.map(Box::new);
                    },
                );
            },
        )
    }
    /// Load each row's `threads` (to-many), one keyed query per batch of keys — `.then(…)` hangs the next level of the path off this one.
    pub fn threads() -> keelson_models::ThenLoad<
        super::Messages,
        super::super::threads::Threads,
        i64,
    > {
        keelson_models::ThenLoad::new(
            |rows: &[super::Message]| rows.iter().map(|r| r.id).collect(),
            |keys, q| keelson_core::Mod::apply(
                super::super::threads::first_message_id().in_(keys),
                q,
            ),
            |rows: &mut [super::Message], related| {
                keelson_models::attach_to_many(
                    rows,
                    related,
                    |r| Some(r.id),
                    |c| c.first_message_id,
                    |r, cs| {
                        r.rel.threads = cs;
                    },
                );
            },
        )
    }
}