sql.urs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. (** Common metaprogramming patterns for SQL syntax construction *)
  2. val sqexps : env ::: {{Type}} -> fields ::: {Type} -> folder fields -> $(map sql_injectable fields)
  3. -> $fields -> $(map (sql_exp env [] []) fields)
  4. (* Convert a record of Ur values into a record of SQL expressions *)
  5. val selector : tn :: Name -> fs ::: {Type} -> ofs ::: {Type} -> [fs ~ ofs]
  6. => folder fs -> $(map sql_injectable fs) -> $fs
  7. -> sql_exp [tn = ofs ++ fs] [] [] bool
  8. (* Build a boolean SQL expression expressing equality of some fields of a table
  9. * row with a record of Ur values *)
  10. val joiner : tn1 :: Name -> tn2 :: Name -> fs ::: {Type} -> ofs1 ::: {Type} -> ofs2 ::: {Type}
  11. -> [[tn1] ~ [tn2]] => [fs ~ ofs1] => [fs ~ ofs2]
  12. => folder fs
  13. -> sql_exp [tn1 = ofs1 ++ fs, tn2 = ofs2 ++ fs] [] [] bool
  14. (* Declare equality of same-named columns from two tables. *)
  15. val insertIfMissing : keyCols ::: {Type} -> otherCols ::: {Type} -> otherKeys ::: {{Unit}}
  16. -> [keyCols ~ otherCols] => [[Pkey] ~ otherKeys]
  17. => folder keyCols -> $(map sql_injectable keyCols)
  18. -> folder otherCols -> $(map sql_injectable otherCols)
  19. -> sql_table (keyCols ++ otherCols) ([Pkey = map (fn _ => ()) keyCols] ++ otherKeys)
  20. -> $(keyCols ++ otherCols)
  21. -> transaction bool
  22. (* Insert a row into an SQL table if its key isn't already present, returning [False] iff the key was already present *)
  23. val deleteByKey : keyCols ::: {Type} -> otherCols ::: {Type} -> otherKeys ::: {{Unit}}
  24. -> [keyCols ~ otherCols] => [[Pkey] ~ otherKeys]
  25. => folder keyCols -> $(map sql_injectable keyCols)
  26. -> sql_table (keyCols ++ otherCols) ([Pkey = map (fn _ => ()) keyCols] ++ otherKeys)
  27. -> $keyCols
  28. -> transaction {}
  29. (* Delete a row from a table by matching its primary key against a given record. *)
  30. val lookup : keyCols ::: {Type} -> otherCols ::: {Type} -> otherKeys ::: {{Unit}}
  31. -> [keyCols ~ otherCols] => [[Pkey] ~ otherKeys]
  32. => folder keyCols -> $(map sql_injectable keyCols)
  33. -> sql_table (keyCols ++ otherCols) ([Pkey = map (fn _ => ()) keyCols] ++ otherKeys)
  34. -> $keyCols -> transaction (option $otherCols)
  35. (* Get the further columns associated with a table key. *)
  36. val listify : lead :: Name -> cols ::: {Type} -> rest ::: {{Type}} -> [[lead] ~ rest]
  37. => folder cols -> $(map eq cols)
  38. -> sql_query [] [] ([lead = cols] ++ rest) []
  39. -> transaction (list ($cols * list $(map (fn ts => $ts) rest)))
  40. (* Shrink a set of table rows by summarizing into lists, keyed off of a lead table *)