ORM-19: Implement HasMany and HasOne #19

Open
opened 2026-10-13 12:49:40 +01:00 by NoctisWolfshadow · 0 comments
Owner

Depends on: #18

Context

The foreign key lives on the child table (posts.user_id). A relation is declared once as a typed const descriptor, like Column, and an instance method is sugar over it. .of(&parent) returns a small handle holding a copy of the parent's key (it borrows nothing), which behaves like a Query<Child> pre-filtered by the parent.

Tasks

  • HasMany::<P, C>::new(fk: Column<C, i64>, set_fk: fn(&mut C, i64)), const-constructible. HasOne takes the same arguments.
  • .of(&parent) returns HasManyOf<C> / HasOneOf<C>. The handle exposes query() -> Query<C> (C::query().filter(fk.equals(parent_id))) and delegates filter, order_by, limit, offset, all and first.
  • HasMany handle: save(&mut child) sets the FK through set_fk and calls child.save(); create(child) -> Result<C> does the same for a new child.
  • Sugar on the fixtures: user.posts() and user.profile().
  • A parent that is not persisted returns Error::NotPersisted.

Example

impl User {
    pub const POSTS: HasMany<User, Post> = HasMany::new(Post::USER_ID, |p, id| p.user_id = id);
    pub const PROFILE: HasOne<User, Profile> = HasOne::new(Profile::USER_ID, |p, id| p.user_id = id);

    pub fn posts(&self) -> HasManyOf<Post> { Self::POSTS.of(self) }
    pub fn profile(&self) -> HasOneOf<Profile> { Self::PROFILE.of(self) }
}
let user = User::find(1)?.unwrap();

// composes with everything Query supports
let published = user
    .posts()
    .filter(Post::PUBLISHED.equals(true))
    .order_by(Post::TITLE.asc())
    .all()?;
// SELECT id, user_id, title, published FROM posts
//   WHERE user_id = ? AND published = ? ORDER BY title ASC

let profile: Option<Profile> = user.profile().first()?;

// writing through the relation
let mut post = Post::new(0, "Hello", false);
user.posts().save(&mut post)?;               // post.user_id = user.id, then post.save()
let second = user.posts().create(Post::new(0, "Second", true))?;

let nobody = User::new("new", None, 1, true); // never saved
assert!(matches!(nobody.posts().all(), Err(Error::NotPersisted)));

Acceptance criteria

  • Filtering, ordering and first on the handles work.
  • save and create set the FK on the child.
  • A new parent returns NotPersisted.

Notes

If a closure in a const initialiser causes trouble on your toolchain, a named fn set_user_id(p: &mut Post, id: i64) is equivalent.

**Depends on:** #18 ## Context The foreign key lives on the *child* table (`posts.user_id`). A relation is declared once as a typed `const` descriptor, like `Column`, and an instance method is sugar over it. `.of(&parent)` returns a small handle holding a copy of the parent's key (it borrows nothing), which behaves like a `Query<Child>` pre-filtered by the parent. ## Tasks - [ ] `HasMany::<P, C>::new(fk: Column<C, i64>, set_fk: fn(&mut C, i64))`, const-constructible. `HasOne` takes the same arguments. - [ ] `.of(&parent)` returns `HasManyOf<C>` / `HasOneOf<C>`. The handle exposes `query() -> Query<C>` (`C::query().filter(fk.equals(parent_id))`) and delegates `filter`, `order_by`, `limit`, `offset`, `all` and `first`. - [ ] `HasMany` handle: `save(&mut child)` sets the FK through `set_fk` and calls `child.save()`; `create(child) -> Result<C>` does the same for a new child. - [ ] Sugar on the fixtures: `user.posts()` and `user.profile()`. - [ ] A parent that is not persisted returns `Error::NotPersisted`. ## Example ```rust impl User { pub const POSTS: HasMany<User, Post> = HasMany::new(Post::USER_ID, |p, id| p.user_id = id); pub const PROFILE: HasOne<User, Profile> = HasOne::new(Profile::USER_ID, |p, id| p.user_id = id); pub fn posts(&self) -> HasManyOf<Post> { Self::POSTS.of(self) } pub fn profile(&self) -> HasOneOf<Profile> { Self::PROFILE.of(self) } } ``` ```rust let user = User::find(1)?.unwrap(); // composes with everything Query supports let published = user .posts() .filter(Post::PUBLISHED.equals(true)) .order_by(Post::TITLE.asc()) .all()?; // SELECT id, user_id, title, published FROM posts // WHERE user_id = ? AND published = ? ORDER BY title ASC let profile: Option<Profile> = user.profile().first()?; // writing through the relation let mut post = Post::new(0, "Hello", false); user.posts().save(&mut post)?; // post.user_id = user.id, then post.save() let second = user.posts().create(Post::new(0, "Second", true))?; let nobody = User::new("new", None, 1, true); // never saved assert!(matches!(nobody.posts().all(), Err(Error::NotPersisted))); ``` ## Acceptance criteria - [ ] Filtering, ordering and `first` on the handles work. - [ ] `save` and `create` set the FK on the child. - [ ] A new parent returns `NotPersisted`. ## Notes If a closure in a `const` initialiser causes trouble on your toolchain, a named `fn set_user_id(p: &mut Post, id: i64)` is equivalent.
Sign in to join this conversation.
No description provided.