Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #load "extLib.cma"
- open Printf
- type change = { fn: string; ov: string; nv: string; }
- class change_log = object (self)
- val changes = DynArray.create ()
- method add_change fn ov nv = DynArray.add changes {fn=fn;ov=ov;nv=nv;}
- method add_maybe fn ov nv = if ov != nv then self#add_change fn ov nv
- method changes = changes
- method for_update =
- let do_f_eq_v x = x.fn ^ "='" ^ x.nv ^ "'" in
- let do_pair acc x =
- if String.length acc > 0 then acc ^ "," ^ (do_f_eq_v x)
- else (do_f_eq_v x)
- in
- DynArray.fold_left do_pair "" changes
- end ;;
- class base_model = object (self)
- val changes = new change_log
- method before_insert = ()
- method before_update = ()
- method after_insert = ()
- method after_update = ()
- end ;;
- (* Dynamically generated base user class. Program reads the database structure
- and generates the model classes *)
- class base_user = object (self)
- inherit base_model
- val mutable id = 0
- val mutable code = ""
- val mutable password = ""
- val mutable first_name = ""
- val mutable last_name = ""
- val mutable version = 0
- method save =
- match id with
- | 0 ->
- self#before_insert ;
- sprintf "INSERT INTO users \
- (code,password,first_name,last_name,version) VALUES \
- ('%s','%s','%s','%s',%i)" code password first_name last_name
- version
- | n ->
- self#before_update ;
- "UPDATE users SET " ^ changes#for_update ^ " WHERE id=" ^
- (string_of_int id)
- method id = id
- method set_id x =
- changes#add_maybe "id" (string_of_int id) (string_of_int x) ;
- id <- x
- method code = code
- method set_code x =
- changes#add_maybe "code" code x ;
- code <- x
- method password = password
- method set_password x =
- changes#add_maybe "password" password x ;
- password <- x
- method first_name = first_name
- method set_first_name x =
- changes#add_maybe "first_name" first_name x ;
- first_name <- x
- method last_name = last_name
- method set_last_name x =
- changes#add_maybe "last_name" last_name x ;
- last_name <- x
- method version = version
- method set_version x =
- changes#add_maybe "version" (string_of_int version) (string_of_int x) ;
- version <- x
- end ;;
- class user = object (self)
- inherit base_user
- method before_insert = version <- 1
- method before_update = version <- version + 1
- method full_name = first_name ^ " " ^ last_name
- method blinded_name = sprintf "%s %c." first_name last_name.[0]
- end ;;
- let u = new user ;;
- printf "%s\n" u#save ;;
- u#set_id 10 ;;
- u#set_code "john" ;;
- u#set_first_name "John" ;;
- u#set_last_name "Doe" ;;
- printf "%s\n" u#save ;;
- printf "%s\n" u#blinded_name ;;
Add Comment
Please, Sign In to add comment