The real release 0.46 :-)
[awl.git] / inc / DataUpdate.php
blob4a675271e1385c63b5fd2f6c3b4d357c8650f532
1 <?php
2 /**
3 * Some functions and a base class to help with updating records.
5 * This subpackage provides some functions that are useful around single
6 * record database activities such as insert and update.
8 * @package awl
9 * @subpackage DataUpdate
10 * @author Andrew McMillan <andrew@mcmillan.net.nz>
11 * @copyright Catalyst IT Ltd, Morphoss Ltd <http://www.morphoss.com/>
12 * @license http://gnu.org/copyleft/gpl.html GNU GPL v2 or later
15 require_once('AWLUtilities.php');
16 require_once('AwlQuery.php');
19 /**
20 * Build SQL INSERT/UPDATE statement from an associative array of fieldnames => values.
21 * @param array $obj The object of fieldnames => values.
22 * @param string $type The word "update" or something else (which implies "insert").
23 * @param string $tablename The name of the table being updated.
24 * @param string $where What the "WHERE ..." clause needs to be for an UPDATE statement.
25 * @param string $fprefix An optional string which all fieldnames in $assoc are prefixed with.
26 * @return string An SQL Update or Insert statement with all fields/values from the array.
28 function sql_from_object( $obj, $type, $tablename, $where, $fprefix = "" ) {
29 $fields = get_fields($tablename);
30 $update = strtolower($type) == "update";
31 if ( $update )
32 $sql = "UPDATE $tablename SET ";
33 else
34 $sql = "INSERT INTO $tablename (";
36 $flst = "";
37 $vlst = "";
38 foreach( $fields as $fn => $typ ) {
39 // $prefixed_fn = $fprefix . $fn;
40 dbg_error_log( "DataUpdate", ":sql_from_object: %s => %s (%s)", $fn, $typ, (isset($obj->{$fn})?$obj->{$fn}:"[undefined value]"));
41 if ( !isset($obj->{$fn}) && isset($obj->{"xxxx$fn"}) ) {
42 // Sometimes we will have prepended 'xxxx' to the field name so that the field
43 // name differs from the column name in the database.
44 $obj->{$fn} = $obj->{"xxxx$fn"};
46 if ( !isset($obj->{$fn}) ) continue;
47 $value = str_replace( "'", "''", str_replace("\\", "\\\\", $obj->{$fn}));
48 if ( $fn == "password" ) {
49 if ( $value == "******" || $value == "" ) continue;
50 if ( !preg_match('/\*[0-9a-z]+\*[0-9a-z{}]+/i', $value ) )
51 $value = (function_exists("session_salted_sha1")
52 ? session_salted_sha1($value)
53 : (function_exists('session_salted_md5')
54 ? session_salted_md5($value)
55 : md5($value)
59 if ( preg_match('{^(time|date|interval)}i', $typ ) && $value == "" ) {
60 $value = "NULL";
62 else if ( preg_match('{^bool}i', $typ) ) {
63 $value = ( $value == false || $value == "f" || $value == "off" || $value == "no" ? "FALSE"
64 : ( $value == true || $value == "t" || $value == "on" || $value == "yes" ? "TRUE"
65 : "NULL" ));
67 else if ( preg_match('{^interval}i', $typ) ) {
68 $value = "'$value'::$typ";
70 else if ( preg_match('{^int}i', $typ) ) {
71 $value = ($value == '' || $value === null ? 'NULL' : intval( $value ));
73 else if ( preg_match('{^bit}i', $typ) ) {
74 $value = ($value == '' || $value === null ? 'NULL' : "'$value'");
76 else if ( preg_match('{^(text|varchar)}i', $typ) ) {
77 $value = "'$value'";
79 else
80 $value = "'$value'::$typ";
82 if ( $update )
83 $flst .= ", $fn = $value";
84 else {
85 $flst .= ", $fn";
86 $vlst .= ", $value";
89 $flst = substr($flst,2);
90 $vlst = substr($vlst,2);
91 $sql .= $flst;
92 if ( $update ) {
93 $sql .= " $where; ";
95 else {
96 $sql .= ") VALUES( $vlst ); ";
98 return $sql;
103 * Build SQL INSERT/UPDATE statement from the $_POST associative array
104 * @param string $type The word "update" or something else (which implies "insert").
105 * @param string $tablename The name of the table being updated.
106 * @param string $where What the "WHERE ..." clause needs to be for an UPDATE statement.
107 * @param string $fprefix An optional string which all fieldnames in $assoc are prefixed with.
108 * @return string An SQL Update or Insert statement with all fields/values from the array.
110 function sql_from_post( $type, $tablename, $where, $fprefix = "" ) {
111 $fakeobject = (object) $_POST;
112 return sql_from_object( $fakeobject, $type, $tablename, $where, $fprefix );
117 * A Base class to use for records which will be read/written from the database.
118 * @package awl
120 class DBRecord
122 /**#@+
123 * @access private
126 * The database table that this record goes in
127 * @var string
129 var $Table;
132 * The field names for the record. The array index is the field name
133 * and the array value is the field type.
134 * @var array
136 var $Fields;
139 * The keys for the record as an array of key => value pairs
140 * @var array
142 var $Keys;
145 * The field values for the record
146 * @var object
148 var $Values;
151 * The type of database write we will want: either "update" or "insert"
152 * @var object
154 var $WriteType;
157 * A list of associated other tables.
158 * @var array of string
160 var $OtherTable;
163 * The field names for each of the other tables associated. The array index
164 * is the table name, the string is a list of field names (and perhaps aliases)
165 * to stuff into the target list for the SELECT.
166 * @var array of string
168 var $OtherTargets;
171 * An array of JOIN ... clauses. The first array index is the table name and the array value
172 * is the JOIN clause like "LEFT JOIN tn t1 USING (myforeignkey)".
173 * @var array of string
175 var $OtherJoin;
178 * An array of partial WHERE clauses. These will be combined (if present) with the key
179 * where clause on the main table.
180 * @var array of string
182 var $OtherWhere;
184 /**#@-*/
186 /**#@+
187 * @access public
190 * The mode we are in for any form
191 * @var object
193 var $EditMode;
195 /**#@-*/
198 * Really numbingly simple construction.
200 function DBRecord( ) {
201 dbg_error_log( "DBRecord", ":Constructor: called" );
202 $this->WriteType = "insert";
203 $this->EditMode = false;
204 $this->prefix = "";
205 $values = (object) array();
206 $this->Values = &$values;
210 * This will read the record from the database if it's available, and
211 * the $keys parameter is a non-empty array.
212 * @param string $table The name of the database table
213 * @param array $keys An associative array containing fieldname => value pairs for the record key.
215 function Initialise( $table, $keys = array() ) {
216 dbg_error_log( "DBRecord", ":Initialise: called" );
217 $this->Table = $table;
218 $this->Fields = get_fields($this->Table);
219 $this->Keys = $keys;
220 $this->WriteType = "insert";
224 * This will join an additional table to the maintained set
225 * @param string $table The name of the database table
226 * @param array $keys An associative array containing fieldname => value pairs for the record key.
227 * @param string $join A PostgreSQL join clause.
228 * @param string $prefix A field prefix to use for these fields to distinguish them from fields
229 * in other joined tables with the same name.
231 function AddTable( $table, $target_list, $join_clause, $and_where ) {
232 dbg_error_log( "DBRecord", ":AddTable: $table called" );
233 $this->OtherTable[] = $table;
234 $this->OtherTargets[$table] = $target_list;
235 $this->OtherJoin[$table] = $join_clause;
236 $this->OtherWhere[$table] = $and_where;
240 * This will assign $_POST values to the internal Values object for each
241 * field that exists in the Fields array.
243 function PostToValues( $prefix = "" ) {
244 foreach ( $this->Fields AS $fname => $ftype ) {
245 @dbg_error_log( "DBRecord", ":PostToValues: %s => %s", $fname, $_POST["$prefix$fname"] );
246 if ( isset($_POST["$prefix$fname"]) ) {
247 $this->Set($fname, $_POST["$prefix$fname"]);
248 @dbg_error_log( "DBRecord", ":PostToValues: %s => %s", $fname, $_POST["$prefix$fname"] );
254 * Builds a table join clause
255 * @return string A simple SQL target join clause excluding the primary table.
257 function _BuildJoinClause() {
258 $clause = "";
259 foreach( $this->OtherJoins AS $t => $join ) {
260 if ( ! preg_match( '/^\s*$/', $join ) ) {
261 $clause .= ( $clause == "" ? "" : " " ) . $join;
265 return $clause;
269 * Builds a field target list
270 * @return string A simple SQL target field list for each field, possibly including prefixes.
272 function _BuildFieldList() {
273 $list = "";
274 foreach( $this->Fields AS $fname => $ftype ) {
275 $list .= ( $list == "" ? "" : ", " );
276 $list .= "$fname" . ( $this->prefix == "" ? "" : " AS \"$this->prefix$fname\"" );
279 foreach( $this->OtherTargets AS $t => $targets ) {
280 if ( ! preg_match( '/^\s*$/', $targets ) ) {
281 $list .= ( $list == "" ? "" : ", " ) . $targets;
285 return $list;
289 * Builds a where clause to match the supplied keys
290 * @param boolean $overwrite_values Controls whether the data values for the key fields will be forced to match the key values
291 * @return string A simple SQL where clause, including the initial "WHERE", for each key / value.
293 function _BuildWhereClause($overwrite_values=false) {
294 $where = "";
295 foreach( $this->Keys AS $k => $v ) {
296 // At least assign the key fields...
297 if ( $overwrite_values ) $this->Values->{$k} = $v;
298 // And build the WHERE clause
299 $where .= ( $where == '' ? 'WHERE ' : ' AND ' );
300 $where .= $k . '=' . AwlQuery::quote($v);
303 if ( isset($this->OtherWhere) && is_array($this->OtherWhere) ) {
304 foreach( $this->OtherWhere AS $t => $and_where ) {
305 if ( ! preg_match( '/^\s*$/', $and_where ) ) {
306 $where .= ($where == '' ? 'WHERE ' : ' AND (' ) . $and_where . ')';
311 return $where;
315 * Sets a single field in the record
316 * @param string $fname The name of the field to set the value for
317 * @param string $fval The value to set the field to
318 * @return mixed The new value of the field (i.e. $fval).
320 function Set($fname, $fval) {
321 dbg_error_log( "DBRecord", ":Set: %s => %s", $fname, $fval );
322 $this->Values->{$fname} = $fval;
323 return $fval;
327 * Returns a single field from the record
328 * @param string $fname The name of the field to set the value for
329 * @return mixed The current value of the field.
331 function Get($fname) {
332 @dbg_error_log( "DBRecord", ":Get: %s => %s", $fname, $this->Values->{$fname} );
333 return (isset($this->Values->{$fname}) ? $this->Values->{$fname} : null);
337 * Unsets a single field from the record
338 * @param string $fname The name of the field to unset the value for
339 * @return mixed The current value of the field.
341 function Undefine($fname) {
342 if ( !isset($this->Values->{$fname}) ) return null;
343 $current = $this->Values->{$fname};
344 dbg_error_log( 'DBRecord', ': Unset: %s =was> %s', $fname, $current );
345 unset($this->Values->{$fname});
346 return $current;
350 * To write the record to the database
351 * @return boolean Success.
353 function Write() {
354 dbg_error_log( "DBRecord", ":Write: %s record as %s.", $this->Table, $this->WriteType );
355 $sql = sql_from_object( $this->Values, $this->WriteType, $this->Table, $this->_BuildWhereClause(), $this->prefix );
356 $qry = new AwlQuery($sql);
357 return $qry->Exec( "DBRecord", __LINE__, __FILE__ );
361 * To read the record from the database.
362 * If we don't have any keys then the record will be blank.
363 * @return boolean Whether we actually read a record.
365 function Read() {
366 $i_read_the_record = false;
367 $values = (object) array();
368 $this->EditMode = true;
369 $where = $this->_BuildWhereClause(true);
370 if ( "" != $where ) {
371 // $fieldlist = $this->_BuildFieldList();
372 $fieldlist = "*";
373 // $join = $this->_BuildJoinClause(true);
374 $sql = "SELECT $fieldlist FROM $this->Table $where";
375 $qry = new AwlQuery($sql);
376 if ( $qry->Exec( "DBRecord", __LINE__, __FILE__ ) && $qry->rows() > 0 ) {
377 $i_read_the_record = true;
378 $values = $qry->Fetch();
379 $this->EditMode = false; // Default to not editing if we read the record.
380 dbg_error_log( "DBRecord", ":Read: Read %s record from table.", $this->Table, $this->WriteType );
383 $this->Values = &$values;
384 $this->WriteType = ( $i_read_the_record ? "update" : "insert" );
385 dbg_error_log( "DBRecord", ":Read: Record %s write type is %s.", $this->Table, $this->WriteType );
386 return $i_read_the_record;