Mailing List Archive: 49091 messages
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search
 

[REBOL] RWT: db-logic

From: maarten::koopmans::surfnet::nl at: 3-Mar-2003 19:45

REBOL [] ; Anonymous context for database functions. context [ ; Stuff that could be moved out of this script database-scheme: "mysql" database-connect-retries: 5 dbport: none cmdport: none sql-reduce: func [ {Reduces a REBOL value to it's SQL representation} val /local sql-val ] [ either any [ integer? val decimal? val ] [ sql-val: to string! val ] [ sql-val: copy {'} append sql-val either date? val [ format-date val ] [ replace to string! val {'} {''} ] append sql-val {'} ] return sql-val ] reduce-query: func [ {Reduces a block query to its string equivalent. The block query contains a template portion with ? characters at the places where values need to be filled in.} bl [block!] {Block containing the template and the values to fill in.} /local template dummy-char reduced-block ] [ dummy-char: to char! 0 reduced-block: reduce bl template: to string! first reduced-block foreach val next reduced-block [ if found? find template "?" [ replace template "?" replace/all sql-reduce val #"?" dummy-char ] ] return replace/all template dummy-char #"?" ] format-date: func [ {Formats a date as a string suitable for use with the database.} time [date!] ] [ return rejoin [ time/year {-} time/month {-} time/day { } either time/time [ time/time ][ {00:00:00} ] ] ] system/words/init-db: func [ {Initializes the database connection if it is not already open.} [catch] /local err ] [ ; Only init the connection if it is not yet open. if dbport [ return true ] loop database-connect-retries [ if error? set/any 'err try [ dbport: open database-url if dbport [ cmdport: dbport insert cmdport "set autocommit=0" return true ] ] [ err: disarm err ] ] throw make error! join {Unable to open database connection: } mold err ] system/words/close-db: func [ {Closes the database connection if it is open.} ] [ if cmdport [ close cmdport ] ;if dbport [ close dbport ] dbport: none cmdport: none ] system/words/query-db: func [ {Sends a query to the database server for execution. If the statement contains a 'select' statement, the results are returned.} [catch] statement [block! string!] {The statement to execute.} /local data ] [ if not dbport [ throw make error! "*** Database port is not open!" ] ;insert cmdport either block? statement ; [ reduce-query statement ] ; [ statement ] insert cmdport statement if find mold statement "select" [ data: copy cmdport return either data [ data ] [ copy [] ] ] ] ]