8785481999-07-01Henrik Grubbström (Grubba) /*
981f832005-04-10Martin Nilsson  * $Id: sql_util.pmod,v 1.13 2005/04/10 03:38:54 nilsson Exp $
8785481999-07-01Henrik Grubbström (Grubba)  * * Some SQL utility functions. * They are kept here to avoid circular references. * * Henrik Grubbström 1999-07-01 */
a580e12000-09-27Fredrik Hübinette (Hubbe) #pike __REAL_VERSION__
a20af62000-09-26Fredrik Hübinette (Hubbe) 
36d2b82001-09-06Martin Nilsson //! Some SQL utility functions
8785481999-07-01Henrik Grubbström (Grubba) 
36d2b82001-09-06Martin Nilsson //! Quote a string so that it can safely be put in a query. //! //! @param s //! String to quote.
8785481999-07-01Henrik Grubbström (Grubba) string quote(string s) {
18096f2003-08-22Martin Nilsson  return replace(s, "\'", "\'\'");
8785481999-07-01Henrik Grubbström (Grubba) }
36d2b82001-09-06Martin Nilsson //! Throw an error in case an unimplemented function is called.
485cb11999-07-01Henrik Grubbström (Grubba) void fallback()
8785481999-07-01Henrik Grubbström (Grubba) {
5d16962003-04-22Martin Nilsson  error( "Function not supported in this database." );
8785481999-07-01Henrik Grubbström (Grubba) }
6458a72000-04-29Francesco Chemolli 
580be42001-12-04Martin Nilsson //! Build a raw SQL query, given the cooked query and the variable bindings
36d2b82001-09-06Martin Nilsson //! It's meant to be used as an emulation engine for those drivers not //! providing such a behaviour directly (i.e. Oracle). //! The raw query can contain some variables (identified by prefixing
580be42001-12-04Martin Nilsson //! a colon to a name or a number (i.e. ":var" or ":2"). They will be
36d2b82001-09-06Martin Nilsson //! replaced by the corresponding value in the mapping. //! //! @param query
580be42001-12-04Martin Nilsson //! The query.
36d2b82001-09-06Martin Nilsson //! //! @param bindings //! Optional mapping containing the variable bindings. Make sure that //! no confusion is possible in the query. If necessary, change the //! variables' names.
4903d52000-04-29Francesco Chemolli string emulate_bindings(string query, mapping(string|int:mixed)|void bindings, void|object driver)
6458a72000-04-29Francesco Chemolli { array(string)k, v; if (!bindings) return query;
580be42001-12-04Martin Nilsson  function my_quote=(driver&&driver->quote?driver->quote:quote);
981f832005-04-10Martin Nilsson  v=map(values(bindings), lambda(mixed m) { if(multisetp(m)) m = indices(m)[0]; return (stringp(m)? "'"+my_quote(m)+"'" : (string)m); });
580be42001-12-04Martin Nilsson  // Throws if mapping key is empty string.
981f832005-04-10Martin Nilsson  k=map(indices(bindings),lambda(string s){ return ( (stringp(s)&&s[0]==':') ? s : ":"+s); });
6458a72000-04-29Francesco Chemolli  return replace(query,k,v); }