swlkr / rizzle

MIT License
14 stars 2 forks source link

Relational queries #3

Open swlkr opened 1 year ago

swlkr commented 1 year ago

Return relationships when with is called, kind of like a join but it returns a Vec<T> on a given row field and a T of the given foreign key:

#[derive(Table)]
#[rizzle(table = "users")]
struct Users {
  #[rizzle(primary_key)]
  id: sqlite::Integer,

  #[rizzle(not_null)]
  name: sqlite::Text,

  #[rizzle(references = "posts(user_id)")]
  posts: sqlite::Many
}

#[derive(Table)]
#[rizzle(table = "posts")]
struct Posts {
  #[rizzle(primary_key)]
  id: sqlite::Integer,

  #[rizzle(not_null)]
  body: sqlite::Text,

  #[rizzle(references = "users(id)")]
  user_id: sqlite::Integer
}

#[derive(Row)]
struct User {
  id: i64,
  body: String,
  posts: Vec<Post>
}

#[derive(Row)]
struct Post {
 id: i64,
 body: String,
 user: User
}

let rows: Vec<User> = db.select().from(users).with(posts).r#where(eq(users.id, 1)).all().await?;
swlkr commented 1 year ago

There is a first draft at this but it's not quite right: https://github.com/swlkr/rizzle/blob/dc84380905822a148be5b5a448dc4c0833e587d0/src/lib.rs#L1589-L1661

swlkr commented 1 year ago

I didn't like how this turned out so I'm abandoning for now, i'll have to come up with some other way to do this without relying on serde_json