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;
77 public function __construct(array $column)
79 $this->name
= $column['Field'];
80 $this->typeParameters
= explode(' ', str_replace(array('(', ')', ',', '\''), ' ',
82 $this->type
= array_shift($this->typeParameters
);
83 if ($this->type
== 'enum' ||
$this->type
== 'set') {
84 $this->typeParameters
= new PlFlagSet(implode(',', $this->typeParameters
));
85 } else if (ctype_digit($this->typeParameters
[0])) {
86 $this->typeLength
= intval($this->typeParameters
[0]);
87 array_shift($this->typeParameters
);
89 $this->allowNull
= ($column['Null'] === 'YES');
90 $this->autoIncrement
= (strpos($column['Extra'], 'auto_increment') !== false
);
91 $this->inPrimaryKey
= ($column['Key'] == 'PRI');
94 $this->defaultValue
= $this->format($column['Default']);
95 } catch (PlDBBadValueException
$e) {
96 $this->defaultValue
= null
;
100 public function format($value, $badNullFallbackToDefault = false
)
102 if (is_null($value)) {
103 if ($this->allowNull ||
$this->autoIncrement
) {
106 if ($badNullFallbackToDefault) {
107 return $this->defaultValue
;
109 throw new PlDBBadValueException($value, $this, 'null not allowed');
110 } else if ($this->type
== 'enum') {
111 if (!$this->typeParameters
->hasFlag($value)) {
112 throw new PlDBBadValueException($value, $this, 'invalid value for enum ' . $this->typeParameters
->flags());
115 } else if ($this->type
== 'set') {
116 $value = new PlFlagSet($value);
117 foreach ($value as $flag) {
118 if (!$this->typeParameters
->hasFlag($flag)) {
119 throw new PlDBBadValueException($value, $this, 'invalid flag for set ' . $this->typeParameters
->flags());
123 } else if (ends_with($this->type
, 'int')) {
124 if (!is_int($value) && !ctype_digit($value)) {
125 throw new PlDBBadValueException($value, $this, 'value is not an integer');
127 $value = intval($value);
128 if (count($this->typeParameters
) > 0 && $this->typeParameters
[0] == 'unsigned') {
130 throw new PlDBBadValueException($value, $this, 'value is negative in an unsigned field');
133 /* TODO: Check bounds */
135 } else if ($this->type
== 'varchar') {
136 if (strlen($value) > $this->typeLength
) {
137 throw new PlDBBadValueException($value, $this, 'value is expected to be at most ' . $this->typeLength
. ' characters long, ' . strlen($value) . ' given');
140 } else if ($this->type
== 'char') {
141 if (strlen($value) != $this->typeLength
) {
142 throw new PlDBBadValueException($value, $this, 'value is expected to be ' . $this->typeLength
. ' characters long, ' . strlen($value) . ' given');
145 } else if (starts_with($this->type
, 'date') ||
$this->type
== 'timestamp') {
147 $value = make_datetime($value);
148 if (is_null($value)) {
149 throw new PlDBBadValueException($date, $this, 'value is expected to be a date/time, ' . $date . ' given');
151 if ($this->type
== 'date') {
152 $value = new DateFormatter($value, 'Y-m-d');
153 } else if ($this->type
== 'datetime') {
154 $value = new DateFormatter($value, 'Y-m-d H:i:s');
156 $value = new DateFormatter($value, 'U');
163 class DateFormatter
implements XDBFormat
166 private $storageFormat;
168 public function __construct(DateTime
$date, $storageFormat)
170 $this->datetime
= $date;
171 $this->storageFormat
= $storageFormat;
174 public function format()
176 return XDB
::escape($this->datetime
->format($this->storageFormat
));
179 public function date($format)
181 return $this->datetime
->format($format);
186 /** This class aims at providing a simple interface to interact with a single
187 * table of a database. It is implemented as a wrapper around XDB.
191 const PRIMARY_KEY
= 'PRIMARY';
198 private $multipleKeys;
199 private $mutableFields;
201 public function __construct($table)
203 $this->table
= $table;
207 private function parseSchema(PlIterator
$schema, PlIterator
$keys)
209 $this->schema
= array();
210 $this->primaryKey
= array();
211 $this->uniqueKeys
= array();
212 $this->multipleKeys
= array();
213 $this->mutableFields
= array();
214 while ($column = $schema->next()) {
215 $field = new PlDBTableField($column);
216 $this->schema
[$field->name
] = $field;
217 if (!$field->inPrimaryKey
) {
218 $this->mutableFields
[] = $field->name
;
221 while ($column = $keys->next()) {
222 $name = $column['Key_name'];
223 $multiple = intval($column['Non_unique']) != 0;
224 $field = $column['Column_name'];
226 if (!isset($this->multipleKeys
[$name])) {
227 $this->multipleKeys
[$name] = array();
229 $this->multipleKeys
[$name][] = $field;
230 } else if ($name == self
::PRIMARY_KEY
) {
231 $this->primaryKey
[] = $field;
233 if (!isset($this->uniqueKeys
[$name])) {
234 $this->uniqueKeys
[$name] = array();
236 $this->uniqueKeys
[$name][] = $field;
242 private function schema()
244 if (!$this->schema
) {
245 $schema = XDB
::iterator('DESCRIBE ' . $this->table
);
246 $keys = XDB
::iterator('SHOW INDEX FROM ' . $this->table
);
247 $this->parseSchema($schema, $keys);
249 return $this->schema
;
252 private function field($field)
254 $schema = $this->schema();
255 if (!isset($schema[$field])) {
256 throw new PlDBNoSuchFieldException($field, $this);
258 return $schema[$field];
261 public function formatField($field, $value)
263 return $this->field($field)->format($value);
266 public function defaultValue($field)
268 return $this->field($field)->defaultValue
;
271 private function hasKeyField(PlDBTableEntry
$entry, array $fields)
273 foreach ($fields as $field) {
274 if (isset($entry->$field)) {
281 private function keyFields($keyName)
283 if ($keyName == self
::PRIMARY_KEY
) {
284 return $this->primaryKey
;
285 } else if (isset($this->uniqueKeys
[$keyName])) {
286 return $this->uniqueKeys
[$keyName];
287 } else if (isset($this->multipleKeys
[$keyName])) {
288 return $this->multipleKeys
[$keyName];
290 throw new PlDBNoSuchKeyException($keyName, $this);
293 private function bestKeyFields(PlDBTableEntry
$entry, $allowMultiple)
295 if ($this->hasKeyField($entry, $this->primaryKey
)) {
296 return $this->primaryKey
;
298 foreach ($this->uniqueKeys
as $fields) {
299 if ($this->hasKeyField($entry, $fields)) {
303 if ($allowMultiple) {
304 foreach ($this->multipleKeys
as $fields) {
305 if ($this->hasKeyField($entry, $fields)) {
310 return $this->primaryKey
;
313 public function key(PlDBTableEntry
$entry, array $keyFields)
316 foreach ($keyFields as $field) {
317 if (!isset($entry->$field)) {
318 throw new PlDBIncompleteEntryDescription($field, $this);
320 $key[] = XDB
::escape($this->$field);
323 return implode('-', $key);
326 public function primaryKey(PlDBTableEntry
$entry)
328 return $this->key($this->keyFields(self
::PRIMARY_KEY
));
331 private function buildKeyCondition(PlDBTableEntry
$entry, array $keyFields, $allowIncomplete)
333 $condition = array();
334 foreach ($keyFields as $field) {
335 if (!isset($entry->$field)) {
336 if (!$allowIncomplete) {
337 throw new PlDBIncompleteEntryDescription($field, $this);
340 $condition[] = XDB
::format($field . ' = {?}', $entry->$field);
343 return implode(' AND ', $condition);
346 public function fetchEntry(PlDBTableEntry
$entry)
348 $result = XDB
::rawFetchOneAssoc('SELECT *
349 FROM ' . $this->table
. '
350 WHERE ' . $this->buildKeyCondition($entry,
351 $this->bestKeyFields($entry, false
),
356 return $entry->fillFromDBData($result);
359 public function iterateOnCondition(PlDBTableEntry
$entry, $condition, $sortField)
361 if (empty($sortField)) {
362 $sortField = $this->primaryKey
;
364 if (!is_array($sortField)) {
365 $sortField = array($sortField);
367 $sort = ' ORDER BY ' . implode(', ', $sortField);
368 $it = XDB
::rawIterator('SELECT *
369 FROM ' . $this->table
. '
370 WHERE ' . $condition . '
372 return PlIteratorUtils
::map($it, array($entry, 'cloneAndFillFromDBData'));
375 public function iterateOnEntry(PlDBTableEntry
$entry, $sortField)
377 return $this->iterateOnCondition($entry,
378 $this->buildKeyCondition($entry,
379 $this->bestKeyFields($entry, true
),
384 const SAVE_INSERT_MISSING
= 0x01;
385 const SAVE_UPDATE_EXISTING
= 0x02;
386 const SAVE_IGNORE_DUPLICATE
= 0x04;
387 public function saveEntry(PlDBTableEntry
$entry, $flags)
389 $flags &= (self
::SAVE_INSERT_MISSING | self
::SAVE_UPDATE_EXISTING | self
::SAVE_IGNORE_DUPLICATE
);
390 Platal
::assert($flags != 0, "Hey, the flags ($flags) here are so stupid, don't know what to do");
391 if ($flags == self
::SAVE_UPDATE_EXISTING
) {
393 foreach ($this->mutableFields
as $field) {
394 if ($entry->hasChanged($field)) {
395 $values[] = XDB
::format($field . ' = {?}', $entry->$field);
398 if (count($values) > 0) {
399 XDB
::rawExecute('UPDATE ' . $this->table
. '
400 SET ' . implode(', ', $values) . '
401 WHERE ' . $this->buildKeyCondition($entry,
402 $this->keyFields(self
::PRIMARY_KEY
),
407 foreach ($this->schema
as $field=>$type) {
408 if ($entry->hasChanged($field)) {
409 $values[$field] = XDB
::escape($entry->$field);
412 if (count($values) > 0) {
413 $query = $this->table
. ' (' . implode(', ', array_keys($values)) . ')
414 VALUES (' . implode(', ', $values) . ')';
415 if (($flags & self
::SAVE_UPDATE_EXISTING
)) {
417 foreach ($this->mutableFields
as $field) {
418 if (isset($values[$field])) {
419 $update[] = "$field = VALUES($field)";
422 if (count($update) > 0) {
423 $query = 'INSERT ' . $query;
424 $query .= "\n ON DUPLICATE KEY UPDATE " . implode(', ', $update);
426 $query = 'INSERT IGNORE ' . $query;
428 } else if (($flags & self
::SAVE_IGNORE_DUPLICATE
)) {
429 $query = 'INSERT IGNORE ' . $query;
431 $query = 'INSERT ' . $query;
433 XDB
::rawExecute($query);
434 $id = XDB
::insertId();
436 foreach ($this->primaryKey
as $field) {
437 if ($this->schema
[$field]->autoIncrement
) {
438 $entry->$field = $id;
447 public function deleteEntry(PlDBTableEntry
$entry, $allowIncomplete)
449 XDB
::rawExecute('DELETE FROM ' . $this->table
. '
450 WHERE ' . $this->buildKeyCondition($entry,
451 $this->bestKeyFields($entry, $allowIncomplete),
455 public static function get($name)
457 return new PlDBTable($name);
461 class PlDBTableEntry
extends PlAbstractIterable
465 private $fetched = false
;
468 private $data = array();
470 public function __construct($table, $autoFetch = false
)
472 if ($table instanceof PlDBTable
) {
473 $this->table
= $table;
475 $this->table
= PlCache
::getGlobal('pldbtable_' . $table, array('PlDBTable', 'get'), array($table));
477 $this->autoFetch
= $autoFetch;
478 $this->changed
= new PlFlagSet();
481 /** This hook is called when the entry is going to be updated in the db.
483 * A typical usecase is a class that stores low-level representation of
484 * an object in db and perform a conversion between this low-level representation
485 * and a higher-level representation.
487 * @return true in case of success
489 protected function preSave()
494 /** This hook is called when the entry has been save in the database.
496 * It can be used to perform post-actions on save like storing extra data
497 * in database or sending a notification.
499 protected function postSave()
503 /** This hook is called when the entry is going to be deleted from the db.
505 * Default behavior is to call preSave().
507 * @return true in case of success.
509 protected function preDelete()
511 return $this->preSave();
514 /** This hook is called when the entry has just been fetched from the db.
516 * This is the counterpart of @ref preSave and a typical use-case is the conversion
517 * from a high-level representation of the objet to a representation suitable for
518 * storage in the database.
520 * @return true in case of success.
522 protected function postFetch()
527 public function __get($field)
529 if (isset($this->data
[$field])) {
530 return $this->data
[$field];
531 } else if (!$this->fetched
&& $this->autoFetch
) {
533 if (isset($this->data
[$field])) {
534 return $this->data
[$field];
537 return $this->table
->defaultValue($field);
540 public function __set($field, $value)
542 $this->data
[$field] = $this->table
->formatField($field, $value);
543 $this->changed
->addFlag($field);
546 public function __isset($field)
548 return isset($this->data
[$field]);
551 public function primaryKey()
553 $this->table
->primaryKey($this);
556 public function hasChanged($field)
558 return $this->changed
->hasFlag($field);
561 public function fillFromArray(array $data)
563 foreach ($data as $field => $value) {
564 $this->$field = $value;
568 public function fillFromDBData(array $data)
570 $this->fillFromArray($data);
571 $this->changed
->clear();
572 return $this->postFetch();
575 public function copy(PlDBTableEntry
$other)
577 Platal
::assert($this->table
== $other->table
,
578 "Trying to fill an entry of table {$this->table} with content of {$other->table}.");
579 $this->changed
= $other->changed
;
580 $this->fetched
= $other->fetched
;
581 $this->data
= $other->data
;
584 public function cloneAndFillFromDBData(array $data)
586 $clone = clone $this;
587 $clone->fillFromDBData($data);
591 public function fetch()
593 return $this->table
->fetchEntry($this);
596 public function iterate($sortField = null
)
598 return $this->table
->iterateOnEntry($this, $sortField);
601 public function iterateOnCondition($condition, $sortField = null
)
603 return $this->table
->iterateOnCondition($this, $condition, $sortField);
606 public function save($flags)
608 if (!$this->preSave()) {
611 $this->table
->saveEntry($this, $flags);
612 $this->changed
->clear();
617 public function update($insertMissing = false
)
619 $flags = PlDBTable
::SAVE_UPDATE_EXISTING
;
620 if ($insertMissing) {
621 $flags = PlDBTable
::SAVE_INSERT_MISSING
;
623 return $this->save($flags);
626 public function insert($allowUpdate = false
)
628 $flags = PlDBTable
::SAVE_INSERT_MISSING
;
630 $flags |
= PlDBTable
::SAVE_UPDATE_EXISTING
;
632 return $this->save($flags);
635 public function delete()
637 if (!$this->preDelete()) {
640 return $this->table
->deleteEntry($this, true
);
644 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: