2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 class PlDBBadValueException
extends PlException
24 public function __construct($value, PlDBTableField
$field, $reason)
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
. '\'): '
33 class PlDBNoSuchFieldException
extends PlException
35 public function __construct($field, PlDBTable
$table)
37 parent
::__construct('Erreur lors de l\'accès à la base de données',
38 'No such field ' . $field . ' in table ' . $table->table
);
42 class PlDBNoSuchKeyException
extends PlException
44 public function __construct($key, PlDBTable
$table)
46 parent
::__construct('Erreur lors de l\'accès à la base de données',
47 'No such key ' . $key . ' in table ' . $table->table
);
52 class PlDBIncompleteEntryDescription
extends PlException
54 public function __construct($field, PlDBTable
$table)
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 '
71 public $typeParameters;
75 public $autoIncrement;
79 public function __construct(array $column)
81 $this->name
= $column['Field'];
82 $this->typeParameters
= explode(' ', str_replace(array('(', ')', ',', '\''), ' ',
84 $this->type
= array_shift($this->typeParameters
);
85 if ($this->type
== 'enum' ||
$this->type
== 'set') {
86 $this->typeParameters
= new PlFlagSet(implode(',', $this->typeParameters
));
87 } else if (ctype_digit($this->typeParameters
[0])) {
88 $this->typeLength
= intval($this->typeParameters
[0]);
89 array_shift($this->typeParameters
);
91 $this->allowNull
= ($column['Null'] === 'YES');
92 $this->autoIncrement
= (strpos($column['Extra'], 'auto_increment') !== false
);
93 $this->inPrimaryKey
= ($column['Key'] == 'PRI');
96 $this->defaultValue
= $this->format($column['Default']);
97 } catch (PlDBBadValueException
$e) {
98 $this->defaultValue
= null
;
102 public function registerFormatter($class)
104 $this->formatter
= $class;
107 public function format($value, $badNullFallbackToDefault = false
)
109 if (is_null($value)) {
110 if ($this->allowNull ||
$this->autoIncrement
) {
113 if ($badNullFallbackToDefault) {
114 return $this->defaultValue
;
116 throw new PlDBBadValueException($value, $this, 'null not allowed');
117 } else if (!is_null($this->formatter
)) {
118 $class = $this->formatter
;
119 $value = new $class($this, $value);
120 } else if ($this->type
== 'enum') {
121 if (!$this->typeParameters
->hasFlag($value)) {
122 throw new PlDBBadValueException($value, $this, 'invalid value for enum ' . $this->typeParameters
->flags());
125 } else if ($this->type
== 'set') {
126 $value = new PlFlagSet($value);
127 foreach ($value as $flag) {
128 if (!$this->typeParameters
->hasFlag($flag)) {
129 throw new PlDBBadValueException($value, $this, 'invalid flag for set ' . $this->typeParameters
->flags());
133 } else if (ends_with($this->type
, 'int')) {
134 if (!is_int($value) && !ctype_digit($value)) {
135 throw new PlDBBadValueException($value, $this, 'value is not an integer');
137 $value = intval($value);
138 if (count($this->typeParameters
) > 0 && $this->typeParameters
[0] == 'unsigned') {
140 throw new PlDBBadValueException($value, $this, 'value is negative in an unsigned field');
143 /* TODO: Check bounds */
145 } else if (ends_with($this->type
, 'char')) {
146 if (strlen($value) > $this->typeLength
) {
147 throw new PlDBBadValueException($value, $this, 'value is expected to be at most ' . $this->typeLength
. ' characters long, ' . strlen($value) . ' given');
150 } else if (starts_with($this->type
, 'date') ||
$this->type
== 'timestamp') {
151 return new DateFieldFormatter($this, $value);
157 interface PlDBTableFieldFormatter
extends XDBFormat
159 public function __construct(PlDBTableField
$field, $value);
162 class DateFieldFormatter
implements PlDBTableFieldFormatter
165 private $storageFormat;
167 public function __construct(PlDBTableField
$field, $date)
170 $this->datetime
= make_datetime($value);
171 if (is_null($this->datetime
)) {
172 throw new PlDBBadValueException($date, $field, 'value is expected to be a date/time, ' . $date . ' given');
174 if ($field->type
== 'date') {
175 $this->storageFormat
= 'Y-m-d';
176 } else if ($field->type
== 'datetime') {
177 $this->storageFormat
= 'Y-m-d H:i:s';
179 $this->storageFormat
= 'U';
183 public function format()
185 return XDB
::escape($this->datetime
->format($this->storageFormat
));
188 public function date($format)
190 return $this->datetime
->format($format);
194 class JSonFieldFormatter
implements PlDBTableFieldFormatter
, ArrayAccess
198 public function __construct(PlDBTableField
$field, $data)
200 if (strpos($field->type
, 'text') === false
) {
201 throw new PlDBBadValueException($data, $field, 'json formatting requires a text field');
204 if (is_string($data)) {
205 $this->data
= json_decode($data, true
);
206 } else if (is_object($data)) {
207 $this->data
= json_decode(json_encode($data), true
);
208 } else if (is_array($data)) {
212 if (is_null($this->data
)) {
213 throw new PlDBBadValueException($data, $field, 'cannot interpret data as json: ' . $data);
217 public function format()
219 return XDB
::escape(json_encode($this->data
));
222 public function offsetExists($offset)
224 return isset($this->data
[$offset]);
227 public function offsetGet($offset)
229 return $this->data
[$offset];
232 public function offsetSet($offset, $value)
234 $this->data
[$offset] = $value;
237 public function offsetUnset($offset)
239 unset($this->data
[$offset]);
244 /** This class aims at providing a simple interface to interact with a single
245 * table of a database. It is implemented as a wrapper around XDB.
249 const PRIMARY_KEY
= 'PRIMARY';
256 private $multipleKeys;
257 private $mutableFields;
259 public function __construct($table)
261 $this->table
= $table;
265 private function parseSchema(PlIterator
$schema, PlIterator
$keys)
267 $this->schema
= array();
268 $this->primaryKey
= array();
269 $this->uniqueKeys
= array();
270 $this->multipleKeys
= array();
271 $this->mutableFields
= array();
272 while ($column = $schema->next()) {
273 $field = new PlDBTableField($column);
274 $this->schema
[$field->name
] = $field;
275 if (!$field->inPrimaryKey
) {
276 $this->mutableFields
[] = $field->name
;
279 while ($column = $keys->next()) {
280 $name = $column['Key_name'];
281 $multiple = intval($column['Non_unique']) != 0;
282 $field = $column['Column_name'];
284 if (!isset($this->multipleKeys
[$name])) {
285 $this->multipleKeys
[$name] = array();
287 $this->multipleKeys
[$name][] = $field;
288 } else if ($name == self
::PRIMARY_KEY
) {
289 $this->primaryKey
[] = $field;
291 if (!isset($this->uniqueKeys
[$name])) {
292 $this->uniqueKeys
[$name] = array();
294 $this->uniqueKeys
[$name][] = $field;
300 private function schema()
302 if (!$this->schema
) {
303 $schema = XDB
::iterator('DESCRIBE ' . $this->table
);
304 $keys = XDB
::iterator('SHOW INDEX FROM ' . $this->table
);
305 $this->parseSchema($schema, $keys);
307 return $this->schema
;
310 private function field($field)
312 $schema = $this->schema();
313 if (!isset($schema[$field])) {
314 throw new PlDBNoSuchFieldException($field, $this);
316 return $schema[$field];
319 public function formatField($field, $value)
321 return $this->field($field)->format($value);
324 public function registerFieldFormatter($field, $class)
326 return $this->field($field)->registerFormatter($class);
329 public function defaultValue($field)
331 return $this->field($field)->defaultValue
;
334 private function hasKeyField(PlDBTableEntry
$entry, array $fields)
336 foreach ($fields as $field) {
337 if (isset($entry->$field)) {
344 private function keyFields($keyName)
346 if ($keyName == self
::PRIMARY_KEY
) {
347 return $this->primaryKey
;
348 } else if (isset($this->uniqueKeys
[$keyName])) {
349 return $this->uniqueKeys
[$keyName];
350 } else if (isset($this->multipleKeys
[$keyName])) {
351 return $this->multipleKeys
[$keyName];
353 throw new PlDBNoSuchKeyException($keyName, $this);
356 private function bestKeyFields(PlDBTableEntry
$entry, $allowMultiple)
358 if ($this->hasKeyField($entry, $this->primaryKey
)) {
359 return $this->primaryKey
;
361 foreach ($this->uniqueKeys
as $fields) {
362 if ($this->hasKeyField($entry, $fields)) {
366 if ($allowMultiple) {
367 foreach ($this->multipleKeys
as $fields) {
368 if ($this->hasKeyField($entry, $fields)) {
373 return $this->primaryKey
;
376 public function key(PlDBTableEntry
$entry, array $keyFields)
379 foreach ($keyFields as $field) {
380 if (!isset($entry->$field)) {
381 throw new PlDBIncompleteEntryDescription($field, $this);
383 $key[] = XDB
::escape($this->$field);
386 return implode('-', $key);
389 public function primaryKey(PlDBTableEntry
$entry)
391 return $this->key($this->keyFields(self
::PRIMARY_KEY
));
394 private function buildKeyCondition(PlDBTableEntry
$entry, array $keyFields, $allowIncomplete)
396 $condition = array();
397 foreach ($keyFields as $field) {
398 if (!isset($entry->$field)) {
399 if (!$allowIncomplete) {
400 throw new PlDBIncompleteEntryDescription($field, $this);
403 $condition[] = XDB
::format($field . ' = {?}', $entry->$field);
406 return implode(' AND ', $condition);
409 public function fetchEntry(PlDBTableEntry
$entry)
411 $result = XDB
::rawFetchOneAssoc('SELECT *
412 FROM ' . $this->table
. '
413 WHERE ' . $this->buildKeyCondition($entry,
414 $this->bestKeyFields($entry, false
),
419 return $entry->fillFromDBData($result);
422 public function iterateOnCondition(PlDBTableEntry
$entry, $condition, $sortField)
424 if (empty($sortField)) {
425 $sortField = $this->primaryKey
;
427 if (!is_array($sortField)) {
428 $sortField = array($sortField);
430 $sort = ' ORDER BY ' . implode(', ', $sortField);
431 $it = XDB
::rawIterator('SELECT *
432 FROM ' . $this->table
. '
433 WHERE ' . $condition . '
435 return PlIteratorUtils
::map($it, array($entry, 'cloneAndFillFromDBData'));
438 public function iterateOnEntry(PlDBTableEntry
$entry, $sortField)
440 return $this->iterateOnCondition($entry,
441 $this->buildKeyCondition($entry,
442 $this->bestKeyFields($entry, true
),
447 const SAVE_INSERT_MISSING
= 0x01;
448 const SAVE_UPDATE_EXISTING
= 0x02;
449 const SAVE_IGNORE_DUPLICATE
= 0x04;
450 public function saveEntry(PlDBTableEntry
$entry, $flags)
452 $flags &= (self
::SAVE_INSERT_MISSING | self
::SAVE_UPDATE_EXISTING | self
::SAVE_IGNORE_DUPLICATE
);
453 Platal
::assert($flags != 0, "Hey, the flags ($flags) here are so stupid, don't know what to do");
454 if ($flags == self
::SAVE_UPDATE_EXISTING
) {
456 foreach ($this->mutableFields
as $field) {
457 if ($entry->hasChanged($field)) {
458 $values[] = XDB
::format($field . ' = {?}', $entry->$field);
461 if (count($values) > 0) {
462 XDB
::rawExecute('UPDATE ' . $this->table
. '
463 SET ' . implode(', ', $values) . '
464 WHERE ' . $this->buildKeyCondition($entry,
465 $this->keyFields(self
::PRIMARY_KEY
),
470 foreach ($this->schema
as $field=>$type) {
471 if ($entry->hasChanged($field)) {
472 $values[$field] = XDB
::escape($entry->$field);
475 if (count($values) > 0) {
476 $query = $this->table
. ' (' . implode(', ', array_keys($values)) . ')
477 VALUES (' . implode(', ', $values) . ')';
478 if (($flags & self
::SAVE_UPDATE_EXISTING
)) {
480 foreach ($this->mutableFields
as $field) {
481 if (isset($values[$field])) {
482 $update[] = "$field = VALUES($field)";
485 if (count($update) > 0) {
486 $query = 'INSERT ' . $query;
487 $query .= "\n ON DUPLICATE KEY UPDATE " . implode(', ', $update);
489 $query = 'INSERT IGNORE ' . $query;
491 } else if (($flags & self
::SAVE_IGNORE_DUPLICATE
)) {
492 $query = 'INSERT IGNORE ' . $query;
494 $query = 'INSERT ' . $query;
496 XDB
::rawExecute($query);
497 $id = XDB
::insertId();
499 foreach ($this->primaryKey
as $field) {
500 if ($this->schema
[$field]->autoIncrement
) {
501 $entry->$field = $id;
510 public function deleteEntry(PlDBTableEntry
$entry, $allowIncomplete)
512 XDB
::rawExecute('DELETE FROM ' . $this->table
. '
513 WHERE ' . $this->buildKeyCondition($entry,
514 $this->bestKeyFields($entry, $allowIncomplete),
518 public static function get($name)
520 return new PlDBTable($name);
524 class PlDBTableEntry
extends PlAbstractIterable
528 private $fetched = false
;
531 private $data = array();
533 public function __construct($table, $autoFetch = false
)
535 if ($table instanceof PlDBTable
) {
536 $this->table
= $table;
538 $this->table
= PlCache
::getGlobal('pldbtable_' . $table, array('PlDBTable', 'get'), array($table));
540 $this->autoFetch
= $autoFetch;
541 $this->changed
= new PlFlagSet();
544 /** Register a custom formatter for a field.
546 * A formatter can be used to perform on-the-fly conversion from db storage to a user-friendly format.
547 * For example, if you have a textual field that contain json, you can use a JSonFieldFormatter on this
548 * field to perform automatic decoding when reading from the database (or when assigning the field)
549 * and automatic json_encoding when storing the object back to the db.
551 protected function registerFieldFormatter($field, $formatterClass)
553 $this->table
->registerFieldFormatter($field, $formatterClass);
556 /** This hook is called when the entry is going to be updated in the db.
558 * A typical usecase is a class that stores low-level representation of
559 * an object in db and perform a conversion between this low-level representation
560 * and a higher-level representation.
562 * @return true in case of success
564 protected function preSave()
569 /** This hook is called when the entry has been save in the database.
571 * It can be used to perform post-actions on save like storing extra data
572 * in database or sending a notification.
574 protected function postSave()
578 /** This hook is called when the entry is going to be deleted from the db.
580 * Default behavior is to call preSave().
582 * @return true in case of success.
584 protected function preDelete()
586 return $this->preSave();
589 /** This hook is called when the entry has just been fetched from the db.
591 * This is the counterpart of @ref preSave and a typical use-case is the conversion
592 * from a high-level representation of the objet to a representation suitable for
593 * storage in the database.
595 * @return true in case of success.
597 protected function postFetch()
602 public function __get($field)
604 if (isset($this->data
[$field])) {
605 return $this->data
[$field];
606 } else if (!$this->fetched
&& $this->autoFetch
) {
608 if (isset($this->data
[$field])) {
609 return $this->data
[$field];
612 return $this->table
->defaultValue($field);
615 public function __set($field, $value)
617 $this->data
[$field] = $this->table
->formatField($field, $value);
618 $this->changed
->addFlag($field);
621 public function __isset($field)
623 return isset($this->data
[$field]);
626 public function primaryKey()
628 $this->table
->primaryKey($this);
631 public function hasChanged($field)
633 return $this->changed
->hasFlag($field);
636 public function fillFromArray(array $data)
638 foreach ($data as $field => $value) {
639 $this->$field = $value;
643 public function fillFromDBData(array $data)
645 $this->fillFromArray($data);
646 $this->changed
->clear();
647 return $this->postFetch();
650 public function copy(PlDBTableEntry
$other)
652 Platal
::assert($this->table
== $other->table
,
653 "Trying to fill an entry of table {$this->table} with content of {$other->table}.");
654 $this->changed
= $other->changed
;
655 $this->fetched
= $other->fetched
;
656 $this->data
= $other->data
;
659 public function cloneAndFillFromDBData(array $data)
661 $clone = clone $this;
662 $clone->fillFromDBData($data);
666 public function fetch()
668 return $this->table
->fetchEntry($this);
671 public function iterate($sortField = null
)
673 return $this->table
->iterateOnEntry($this, $sortField);
676 public function iterateOnCondition($condition, $sortField = null
)
678 return $this->table
->iterateOnCondition($this, $condition, $sortField);
681 public function save($flags)
683 if (!$this->preSave()) {
686 $this->table
->saveEntry($this, $flags);
687 $this->changed
->clear();
692 public function update($insertMissing = false
)
694 $flags = PlDBTable
::SAVE_UPDATE_EXISTING
;
695 if ($insertMissing) {
696 $flags = PlDBTable
::SAVE_INSERT_MISSING
;
698 return $this->save($flags);
701 public function insert($allowUpdate = false
)
703 $flags = PlDBTable
::SAVE_INSERT_MISSING
;
705 $flags |
= PlDBTable
::SAVE_UPDATE_EXISTING
;
707 return $this->save($flags);
710 public function delete()
712 if (!$this->preDelete()) {
715 return $this->table
->deleteEntry($this, true
);
719 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: