cbeb7bf950cba101e09c61b31674f848dc82c6ae
[platal.git] / classes / pldbtableentry.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 class PlDBBadValueException extends PlException
23 {
24 public function __construct($value, PlDBTableField $field, $reason)
25 {
26 parent::__construct('Erreur lors de l\'accès à la base de données',
27 'Illegal value '. (is_null($value) ? '(null)' : '(\'' . $value . '\')')
28 . ' for field (\'' . $field->table->table . '.' . $field->name . '\'): '
29 . $reason);
30 }
31 }
32
33 class PlDBNoSuchFieldException extends PlException
34 {
35 public function __construct($field, PlDBTable $table)
36 {
37 parent::__construct('Erreur lors de l\'accès à la base de données',
38 'No such field ' . $field . ' in table ' . $table->table);
39 }
40 }
41
42 class PlDBNoSuchKeyException extends PlException
43 {
44 public function __construct($key, PlDBTable $table)
45 {
46 parent::__construct('Erreur lors de l\'accès à la base de données',
47 'No such key ' . $key . ' in table ' . $table->table);
48 }
49 }
50
51
52 class PlDBIncompleteEntryDescription extends PlException
53 {
54 public function __construct($field, PlDBTable $table)
55 {
56 parent::__construct('Erreur lors de l\'accès à la base de données',
57 'The field ' . $field . ' is required to describe an entry in table '
58 . $table->table);
59 }
60 }
61
62 class PlDBTableField
63 {
64 public $table;
65
66 public $name;
67 public $inPrimaryKey;
68
69 public $type;
70 public $typeLength;
71 public $typeParameters;
72
73 public $allowNull;
74 public $defaultValue;
75 public $autoIncrement;
76
77 private $validator;
78 private $formatter;
79
80 public function __construct(array $column)
81 {
82 $this->name = $column['Field'];
83 $this->typeParameters = explode(' ', str_replace(array('(', ')', ',', '\''), ' ',
84 $column['Type']));
85 $this->type = array_shift($this->typeParameters);
86 if ($this->type == 'enum' || $this->type == 'set') {
87 $this->typeParameters = new PlFlagSet(implode(',', $this->typeParameters));
88 } else if (ctype_digit($this->typeParameters[0])) {
89 $this->typeLength = intval($this->typeParameters[0]);
90 array_shift($this->typeParameters);
91 }
92 $this->allowNull = ($column['Null'] === 'YES');
93 $this->autoIncrement = (strpos($column['Extra'], 'auto_increment') !== false);
94 $this->inPrimaryKey = ($column['Key'] == 'PRI');
95
96 try {
97 $this->defaultValue = $this->format($column['Default']);
98 } catch (PlDBBadValueException $e) {
99 $this->defaultValue = null;
100 }
101 }
102
103 public function registerFormatter($class)
104 {
105 $this->formatter = $class;
106 }
107
108 public function registerValidator($class)
109 {
110 $this->validator = $class;
111 }
112
113 public function format($value, $badNullFallbackToDefault = false)
114 {
115 if (is_null($value)) {
116 if ($this->allowNull || $this->autoIncrement) {
117 return $value;
118 }
119 if ($badNullFallbackToDefault) {
120 return $this->defaultValue;
121 }
122 throw new PlDBBadValueException($value, $this, 'null not allowed');
123 }
124 if (!is_null($this->validator)) {
125 $class = $this->validator;
126 new $class($this, $value);
127 }
128 if (!is_null($this->formatter)) {
129 $class = $this->formatter;
130 $value = new $class($this, $value);
131 } else if ($this->type == 'enum') {
132 if (!$this->typeParameters->hasFlag($value)) {
133 throw new PlDBBadValueException($value, $this, 'invalid value for enum ' . $this->typeParameters->flags());
134 }
135 return $value;
136 } else if ($this->type == 'set') {
137 $value = new PlFlagSet($value);
138 foreach ($value as $flag) {
139 if (!$this->typeParameters->hasFlag($flag)) {
140 throw new PlDBBadValueException($value, $this, 'invalid flag for set ' . $this->typeParameters->flags());
141 }
142 }
143 return $value;
144 } else if (ends_with($this->type, 'int')) {
145 if (!is_int($value) && !ctype_digit($value)) {
146 throw new PlDBBadValueException($value, $this, 'value is not an integer');
147 }
148 $value = intval($value);
149 if (count($this->typeParameters) > 0 && $this->typeParameters[0] == 'unsigned') {
150 if ($value < 0) {
151 throw new PlDBBadValueException($value, $this, 'value is negative in an unsigned field');
152 }
153 }
154 /* TODO: Check bounds */
155 return $value;
156 } else if (ends_with($this->type, 'char')) {
157 if (strlen($value) > $this->typeLength) {
158 throw new PlDBBadValueException($value, $this, 'value is expected to be at most ' . $this->typeLength . ' characters long, ' . strlen($value) . ' given');
159 }
160 return $value;
161 } else if (starts_with($this->type, 'date') || $this->type == 'timestamp') {
162 return new DateFieldFormatter($this, $value);
163 }
164 return $value;
165 }
166 }
167
168 interface PlDBTableFieldValidator
169 {
170 public function __construct(PlDBTableField $field, $value);
171 }
172
173 interface PlDBTableFieldFormatter extends PlDBTableFieldValidator, XDBFormat
174 {
175 }
176
177 class DateFieldFormatter implements PlDBTableFieldFormatter
178 {
179 private $datetime;
180 private $storageFormat;
181
182 public function __construct(PlDBTableField $field, $date)
183 {
184 $this->datetime = make_datetime($date);
185 if (is_null($this->datetime)) {
186 throw new PlDBBadValueException($date, $field, 'value is expected to be a date/time, ' . $date . ' given');
187 }
188 if ($field->type == 'date') {
189 $this->storageFormat = 'Y-m-d';
190 } else if ($field->type == 'datetime') {
191 $this->storageFormat = 'Y-m-d H:i:s';
192 } else {
193 $this->storageFormat = 'U';
194 }
195 }
196
197 public function format()
198 {
199 return XDB::escape($this->datetime->format($this->storageFormat));
200 }
201
202 public function date($format)
203 {
204 return $this->datetime->format($format);
205 }
206 }
207
208 class JSonFieldFormatter implements PlDBTableFieldFormatter, ArrayAccess
209 {
210 private $data;
211
212 public function __construct(PlDBTableField $field, $data)
213 {
214 if (strpos($field->type, 'text') === false) {
215 throw new PlDBBadValueException($data, $field, 'json formatting requires a text field');
216 }
217
218 if (is_string($data)) {
219 $this->data = json_decode($data, true);
220 } else if (is_object($data)) {
221 $this->data = json_decode(json_encode($data), true);
222 } else if (is_array($data)) {
223 $this->data = $data;
224 }
225
226 if (is_null($this->data)) {
227 throw new PlDBBadValueException($data, $field, 'cannot interpret data as json: ' . $data);
228 }
229 }
230
231 public function format()
232 {
233 return XDB::escape(json_encode($this->data));
234 }
235
236 public function offsetExists($offset)
237 {
238 return isset($this->data[$offset]);
239 }
240
241 public function offsetGet($offset)
242 {
243 return $this->data[$offset];
244 }
245
246 public function offsetSet($offset, $value)
247 {
248 $this->data[$offset] = $value;
249 }
250
251 public function offsetUnset($offset)
252 {
253 unset($this->data[$offset]);
254 }
255 }
256
257
258 /** This class aims at providing a simple interface to interact with a single
259 * table of a database. It is implemented as a wrapper around XDB.
260 */
261 class PlDBTable
262 {
263 const PRIMARY_KEY = 'PRIMARY';
264
265 public $table;
266
267 private $schema;
268 private $primaryKey;
269 private $uniqueKeys;
270 private $multipleKeys;
271 private $mutableFields;
272
273 public function __construct($table)
274 {
275 $this->table = $table;
276 $this->schema();
277 }
278
279 private function parseSchema(PlIterator $schema, PlIterator $keys)
280 {
281 $this->schema = array();
282 $this->primaryKey = array();
283 $this->uniqueKeys = array();
284 $this->multipleKeys = array();
285 $this->mutableFields = array();
286 while ($column = $schema->next()) {
287 $field = new PlDBTableField($column);
288 $this->schema[$field->name] = $field;
289 if (!$field->inPrimaryKey) {
290 $this->mutableFields[] = $field->name;
291 }
292 }
293 while ($column = $keys->next()) {
294 $name = $column['Key_name'];
295 $multiple = intval($column['Non_unique']) != 0;
296 $field = $column['Column_name'];
297 if ($multiple) {
298 if (!isset($this->multipleKeys[$name])) {
299 $this->multipleKeys[$name] = array();
300 }
301 $this->multipleKeys[$name][] = $field;
302 } else if ($name == self::PRIMARY_KEY) {
303 $this->primaryKey[] = $field;
304 } else {
305 if (!isset($this->uniqueKeys[$name])) {
306 $this->uniqueKeys[$name] = array();
307 }
308 $this->uniqueKeys[$name][] = $field;
309 }
310 }
311 }
312
313
314 private function schema()
315 {
316 if (!$this->schema) {
317 $schema = XDB::iterator('DESCRIBE ' . $this->table);
318 $keys = XDB::iterator('SHOW INDEX FROM ' . $this->table);
319 $this->parseSchema($schema, $keys);
320 }
321 return $this->schema;
322 }
323
324 private function field($field)
325 {
326 $schema = $this->schema();
327 if (!isset($schema[$field])) {
328 throw new PlDBNoSuchFieldException($field, $this);
329 }
330 return $schema[$field];
331 }
332
333 public function formatField($field, $value)
334 {
335 return $this->field($field)->format($value);
336 }
337
338 public function registerFieldFormatter($field, $class)
339 {
340 return $this->field($field)->registerFormatter($class);
341 }
342
343 public function registerFieldValidator($field, $class)
344 {
345 return $this->field($field)->registerValidator($class);
346 }
347
348
349 public function defaultValue($field)
350 {
351 return $this->field($field)->defaultValue;
352 }
353
354 private function hasKeyField(PlDBTableEntry $entry, array $fields)
355 {
356 foreach ($fields as $field) {
357 if (isset($entry->$field)) {
358 return true;
359 }
360 }
361 return false;
362 }
363
364 private function keyFields($keyName)
365 {
366 if ($keyName == self::PRIMARY_KEY) {
367 return $this->primaryKey;
368 } else if (isset($this->uniqueKeys[$keyName])) {
369 return $this->uniqueKeys[$keyName];
370 } else if (isset($this->multipleKeys[$keyName])) {
371 return $this->multipleKeys[$keyName];
372 }
373 throw new PlDBNoSuchKeyException($keyName, $this);
374 }
375
376 private function bestKeyFields(PlDBTableEntry $entry, $allowMultiple)
377 {
378 if ($this->hasKeyField($entry, $this->primaryKey)) {
379 return $this->primaryKey;
380 }
381 foreach ($this->uniqueKeys as $fields) {
382 if ($this->hasKeyField($entry, $fields)) {
383 return $fields;
384 }
385 }
386 if ($allowMultiple) {
387 foreach ($this->multipleKeys as $fields) {
388 if ($this->hasKeyField($entry, $fields)) {
389 return $fields;
390 }
391 }
392 }
393 return $this->primaryKey;
394 }
395
396 public function key(PlDBTableEntry $entry, array $keyFields)
397 {
398 $key = array();
399 foreach ($keyFields as $field) {
400 if (!isset($entry->$field)) {
401 throw new PlDBIncompleteEntryDescription($field, $this);
402 } else {
403 $key[] = XDB::escape($this->$field);
404 }
405 }
406 return implode('-', $key);
407 }
408
409 public function primaryKey(PlDBTableEntry $entry)
410 {
411 return $this->key($this->keyFields(self::PRIMARY_KEY));
412 }
413
414 private function buildKeyCondition(PlDBTableEntry $entry, array $keyFields, $allowIncomplete)
415 {
416 $condition = array();
417 foreach ($keyFields as $field) {
418 if (!isset($entry->$field)) {
419 if (!$allowIncomplete) {
420 throw new PlDBIncompleteEntryDescription($field, $this);
421 }
422 } else {
423 $condition[] = XDB::format($field . ' = {?}', $entry->$field);
424 }
425 }
426 return implode(' AND ', $condition);
427 }
428
429 public function fetchEntry(PlDBTableEntry $entry)
430 {
431 $result = XDB::rawFetchOneAssoc('SELECT *
432 FROM ' . $this->table . '
433 WHERE ' . $this->buildKeyCondition($entry,
434 $this->bestKeyFields($entry, false),
435 false));
436 if (!$result) {
437 return false;
438 }
439 return $entry->fillFromDBData($result);
440 }
441
442 public function iterateOnCondition(PlDBTableEntry $entry, $condition, $sortField)
443 {
444 if (empty($sortField)) {
445 $sortField = $this->primaryKey;
446 }
447 if (!is_array($sortField)) {
448 $sortField = array($sortField);
449 }
450 $sort = ' ORDER BY ' . implode(', ', $sortField);
451 $it = XDB::rawIterator('SELECT *
452 FROM ' . $this->table . '
453 WHERE ' . $condition . '
454 ' . $sort);
455 return PlIteratorUtils::map($it, array($entry, 'cloneAndFillFromDBData'));
456 }
457
458 public function iterateOnEntry(PlDBTableEntry $entry, $sortField)
459 {
460 return $this->iterateOnCondition($entry,
461 $this->buildKeyCondition($entry,
462 $this->bestKeyFields($entry, true),
463 true),
464 $sortField);
465 }
466
467 const SAVE_INSERT_MISSING = 0x01;
468 const SAVE_UPDATE_EXISTING = 0x02;
469 const SAVE_IGNORE_DUPLICATE = 0x04;
470 public function saveEntry(PlDBTableEntry $entry, $flags)
471 {
472 $flags &= (self::SAVE_INSERT_MISSING | self::SAVE_UPDATE_EXISTING | self::SAVE_IGNORE_DUPLICATE);
473 Platal::assert($flags != 0, "Hey, the flags ($flags) here are so stupid, don't know what to do");
474 if ($flags == self::SAVE_UPDATE_EXISTING) {
475 $values = array();
476 foreach ($this->mutableFields as $field) {
477 if ($entry->hasChanged($field)) {
478 $values[] = XDB::format($field . ' = {?}', $entry->$field);
479 }
480 }
481 if (count($values) > 0) {
482 XDB::rawExecute('UPDATE ' . $this->table . '
483 SET ' . implode(', ', $values) . '
484 WHERE ' . $this->buildKeyCondition($entry,
485 $this->keyFields(self::PRIMARY_KEY),
486 false));
487 }
488 } else {
489 $values = array();
490 foreach ($this->schema as $field=>$type) {
491 if ($entry->hasChanged($field)) {
492 $values[$field] = XDB::escape($entry->$field);
493 }
494 }
495 if (count($values) > 0) {
496 $query = $this->table . ' (' . implode(', ', array_keys($values)) . ')
497 VALUES (' . implode(', ', $values) . ')';
498 if (($flags & self::SAVE_UPDATE_EXISTING)) {
499 $update = array();
500 foreach ($this->mutableFields as $field) {
501 if (isset($values[$field])) {
502 $update[] = "$field = VALUES($field)";
503 }
504 }
505 if (count($update) > 0) {
506 $query = 'INSERT ' . $query;
507 $query .= "\n ON DUPLICATE KEY UPDATE " . implode(', ', $update);
508 } else {
509 $query = 'INSERT IGNORE ' . $query;
510 }
511 } else if (($flags & self::SAVE_IGNORE_DUPLICATE)) {
512 $query = 'INSERT IGNORE ' . $query;
513 } else {
514 $query = 'INSERT ' . $query;
515 }
516 XDB::rawExecute($query);
517 $id = XDB::insertId();
518 if ($id) {
519 foreach ($this->primaryKey as $field) {
520 if ($this->schema[$field]->autoIncrement) {
521 $entry->$field = $id;
522 break;
523 }
524 }
525 }
526 }
527 }
528 }
529
530 public function deleteEntry(PlDBTableEntry $entry, $allowIncomplete)
531 {
532 XDB::rawExecute('DELETE FROM ' . $this->table . '
533 WHERE ' . $this->buildKeyCondition($entry,
534 $this->bestKeyFields($entry, $allowIncomplete),
535 $allowIncomplete));
536 }
537
538 public static function get($name)
539 {
540 return new PlDBTable($name);
541 }
542 }
543
544 class PlDBTableEntry extends PlAbstractIterable
545 {
546 private $table;
547 private $changed;
548 private $fetched = false;
549 private $autoFetch;
550
551 private $data = array();
552
553 public function __construct($table, $autoFetch = false)
554 {
555 if ($table instanceof PlDBTable) {
556 $this->table = $table;
557 } else {
558 $this->table = PlCache::getGlobal('pldbtable_' . $table, array('PlDBTable', 'get'), array($table));
559 }
560 $this->autoFetch = $autoFetch;
561 $this->changed = new PlFlagSet();
562 }
563
564 /** Register a custom formatter for a field.
565 *
566 * A formatter can be used to perform on-the-fly conversion from db storage to a user-friendly format.
567 * For example, if you have a textual field that contain json, you can use a JSonFieldFormatter on this
568 * field to perform automatic decoding when reading from the database (or when assigning the field)
569 * and automatic json_encoding when storing the object back to the db.
570 */
571 protected function registerFieldFormatter($field, $formatterClass)
572 {
573 $this->table->registerFieldFormatter($field, $formatterClass);
574 }
575
576 /** Register a custom validator for a field.
577 *
578 * A validator perform a pre-filter on the value of a field. As opposed to the formatters, it does
579 * not affects how the value is stored in the database.
580 */
581 protected function registerFieldValidator($field, $validatorClass)
582 {
583 $this->table->registerFieldValidator($field, $validatorClass);
584 }
585
586 /** This hook is called when the entry is going to be updated in the db.
587 *
588 * A typical usecase is a class that stores low-level representation of
589 * an object in db and perform a conversion between this low-level representation
590 * and a higher-level representation.
591 *
592 * @return true in case of success
593 */
594 protected function preSave()
595 {
596 return true;
597 }
598
599 /** This hook is called when the entry has been save in the database.
600 *
601 * It can be used to perform post-actions on save like storing extra data
602 * in database or sending a notification.
603 */
604 protected function postSave()
605 {
606 }
607
608 /** This hook is called when the entry is going to be deleted from the db.
609 *
610 * Default behavior is to call preSave().
611 *
612 * @return true in case of success.
613 */
614 protected function preDelete()
615 {
616 return $this->preSave();
617 }
618
619 /** This hook is called when the entry has just been fetched from the db.
620 *
621 * This is the counterpart of @ref preSave and a typical use-case is the conversion
622 * from a high-level representation of the objet to a representation suitable for
623 * storage in the database.
624 *
625 * @return true in case of success.
626 */
627 protected function postFetch()
628 {
629 return true;
630 }
631
632 public function __get($field)
633 {
634 if (isset($this->data[$field])) {
635 return $this->data[$field];
636 } else if (!$this->fetched && $this->autoFetch) {
637 $this->fetch();
638 if (isset($this->data[$field])) {
639 return $this->data[$field];
640 }
641 }
642 return $this->table->defaultValue($field);
643 }
644
645 public function __set($field, $value)
646 {
647 $this->data[$field] = $this->table->formatField($field, $value);
648 $this->changed->addFlag($field);
649 }
650
651 public function __isset($field)
652 {
653 return isset($this->data[$field]);
654 }
655
656 public function primaryKey()
657 {
658 $this->table->primaryKey($this);
659 }
660
661 public function hasChanged($field)
662 {
663 return $this->changed->hasFlag($field);
664 }
665
666 public function fillFromArray(array $data)
667 {
668 foreach ($data as $field => $value) {
669 $this->$field = $value;
670 }
671 }
672
673 public function fillFromDBData(array $data)
674 {
675 $this->fillFromArray($data);
676 $this->changed->clear();
677 return $this->postFetch();
678 }
679
680 public function copy(PlDBTableEntry $other)
681 {
682 Platal::assert($this->table == $other->table,
683 "Trying to fill an entry of table {$this->table->table} with content of {$other->table->table}.");
684 $this->changed = $other->changed;
685 $this->fetched = $other->fetched;
686 $this->data = $other->data;
687 }
688
689 public function cloneAndFillFromDBData(array $data)
690 {
691 $clone = clone $this;
692 $clone->fillFromDBData($data);
693 return $clone;
694 }
695
696 public function fetch()
697 {
698 return $this->table->fetchEntry($this);
699 }
700
701 public function iterate($sortField = null)
702 {
703 return $this->table->iterateOnEntry($this, $sortField);
704 }
705
706 public function iterateOnCondition($condition, $sortField = null)
707 {
708 return $this->table->iterateOnCondition($this, $condition, $sortField);
709 }
710
711 public function save($flags)
712 {
713 if (!$this->preSave()) {
714 return false;
715 }
716 $this->table->saveEntry($this, $flags);
717 $this->changed->clear();
718 $this->postSave();
719 return true;
720 }
721
722 public function update($insertMissing = false)
723 {
724 $flags = PlDBTable::SAVE_UPDATE_EXISTING;
725 if ($insertMissing) {
726 $flags = PlDBTable::SAVE_INSERT_MISSING;
727 }
728 return $this->save($flags);
729 }
730
731 public function insert($allowUpdate = false)
732 {
733 $flags = PlDBTable::SAVE_INSERT_MISSING;
734 if ($allowUpdate) {
735 $flags |= PlDBTable::SAVE_UPDATE_EXISTING;
736 }
737 return $this->save($flags);
738 }
739
740 public function delete()
741 {
742 if (!$this->preDelete()) {
743 return 0;
744 }
745 return $this->table->deleteEntry($this, true);
746 }
747 }
748
749 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
750 ?>