Mercurial > urweb
annotate demo/more/orm.ur @ 988:d923b47e483d
Basic CRUD operations in Orm
author | Adam Chlipala <adamc@hcoop.net> |
---|---|
date | Mon, 05 Oct 2009 17:00:04 -0400 |
parents | 6dd122f10c0c |
children | 0bdc4d538f1c |
rev | line source |
---|---|
adamc@987 | 1 con link = fn t :: Type => unit |
adamc@987 | 2 |
adamc@987 | 3 con meta = fn col :: Type => { |
adamc@987 | 4 Link : link col, |
adamc@987 | 5 Inj : sql_injectable col |
adamc@987 | 6 } |
adamc@987 | 7 |
adamc@987 | 8 functor Table(M : sig |
adamc@987 | 9 con cols :: {Type} |
adamc@987 | 10 val cols : $(map meta cols) |
adamc@987 | 11 constraint [Id] ~ cols |
adamc@987 | 12 val folder : folder cols |
adamc@987 | 13 end) = struct |
adamc@987 | 14 type id = int |
adamc@987 | 15 val inj = _ |
adamc@987 | 16 val id : meta id = {Link = (), |
adamc@987 | 17 Inj = inj} |
adamc@987 | 18 |
adamc@987 | 19 sequence s |
adamc@987 | 20 table t : ([Id = id] ++ M.cols) |
adamc@987 | 21 |
adamc@988 | 22 type row = $([Id = id] ++ M.cols) |
adamc@988 | 23 |
adamc@988 | 24 fun ensql [avail] (r : $M.cols) : $(map (sql_exp avail [] []) M.cols) = |
adamc@988 | 25 map2 [meta] [Top.id] [sql_exp avail [] []] |
adamc@988 | 26 (fn [t] meta v => @sql_inject meta.Inj v) |
adamc@988 | 27 [_] M.folder M.cols r |
adamc@988 | 28 |
adamc@987 | 29 fun create (r : $M.cols) = |
adamc@987 | 30 id <- nextval s; |
adamc@988 | 31 dml (insert t ({Id = sql_inject id} ++ ensql r)); |
adamc@988 | 32 return ({Id = id} ++ r) |
adamc@988 | 33 |
adamc@988 | 34 fun delete r = dml (DELETE FROM t WHERE t.Id = {[r.Id]}) |
adamc@988 | 35 |
adamc@988 | 36 fun save r = dml (update [M.cols] ! (ensql (r -- #Id)) t (WHERE T.Id = {[r.Id]})) |
adamc@988 | 37 |
adamc@988 | 38 fun lookup id = |
adamc@988 | 39 ro <- oneOrNoRows (SELECT * FROM t WHERE t.Id = {[id]}); |
adamc@988 | 40 return (Option.mp (fn r => r.T) ro) |
adamc@988 | 41 |
adamc@988 | 42 val list = query (SELECT * FROM t) (fn r ls => return (r.T :: ls)) [] |
adamc@987 | 43 end |