jrf0110 / dirac

A Node Postgres DB layer built with MoSQL
http://dirac.j0.hn
6 stars 2 forks source link

Relationship directives in table defs #5

Open jrf0110 opened 11 years ago

jrf0110 commented 11 years ago

The purpose of this is to automatically create junction tables if necessary and reason about the relationship between tables. If for instance we have a hasOne relationship, we can safely say get the corresponding records in the the hasOne tables on each query. That is, add a join to whatever queries we're performing. In addition, if there are updates to be made, we can treat a document, say a user with user groups embedded in it, as atomic and when the users array changes, we know how to update related tables.

dirac.register({
  name: 'users'
, hasMany: [ 'groups' ]
, hasOne: [ 'profile' ]
, schema: {
    /* ... */
  }
});

We can automatically create junction tables for hasMany relationships like this:

{
  table: 'books'
, schema: { id, name }
}

{
  table: 'authors'
, schema: { id, name }
}

{
  table: 'books_authors'
, schema: { book_id, author_id }
}

In the case of manyToMany, the junction table schema is the same. We'll just need to detect when a many-to-many relationship exists and only create one version. That is, do not create both books_authors and authors_books when authors specifies hasMany: [ 'books' ] and books specifies `hasMany: [ 'authors' ]``

jrf0110 commented 11 years ago

In addition, if a table has as hasOne relationship, we can safely assume that something like this:

dirac.register({
  name: 'users'
, hasMany: [ 'groups' ]
, hasOne: [ 'profile' ]
, schema: {
    /* ... */
  }
});

dirac.insert({
  email: 'bob@bob.com'
, password: 'password'
, profile: {
    firstName: 'Bob'
  , lastName: 'Bobbo'
  }
});

So, we can extract the profile object because it matches the hasOne relationship, and do two inserts in a transaction. One for the user and for the profile.