leafo / lapis

A web framework for Lua and OpenResty written in MoonScript
http://leafo.net/lapis/
MIT License
3.12k stars 247 forks source link

Feature Request: Foreign Key constraint option in schema types #787

Open karai17 opened 4 months ago

karai17 commented 4 months ago

From my understanding, Lapis' scheme type foreign_key is just an alias for integer and does not create an actual constraint. the only way to add a foreign key constraint to the database using Lapis' migration and db utilities is to manually add the constraint as an sql fragement:

schema.create_table("comments", {
  { "id",       types.integer { unique=true, primary_key=true }},
  { "post_id",  types.integer },
  { "body",     types.text },

  "FOREIGN KEY (post_id) REFERENCES posts"
})

However, given that there is already a primary_key option, a foreign_key option makes sense:

schema.create_table("comments", {
  { "id",       types.integer { unique=true, primary_key=true }},
  { "post_id",  types.integer { foreign_key="posts" }}, -- if foreign_key is boolean TRUE, infer table from column name: post_id -> posts
  { "body",     types.text }
})

I assume that using primary_key on multiple columns correctly combines them into a composite key, so doing the same with foreign_key should work the same way. If this is not the case and you must use an sql fragment to create composite keys, then feature parity makes sense in that regard.