Overview
Comment: | DB: nouveaux noms de méthodes, utilisation d'objets en retour, simplification, lazy loading, etc. |
---|---|
Downloads: | Tarball | ZIP archive | SQL archive |
Timelines: | family | ancestors | descendants | both | dev |
Files: | files | file ages | folders |
SHA1: |
37e2badee254d4f94cb1a1e7013523d6 |
User & Date: | bohwaz on 2017-03-17 03:47:20 |
Other Links: | branch diff | manifest | tags |
Context
2017-03-17
| ||
04:46 | Gérer les objets aussi check-in: ce44c3d07c user: bohwaz tags: dev | |
03:47 | DB: nouveaux noms de méthodes, utilisation d'objets en retour, simplification, lazy loading, etc. check-in: 37e2badee2 user: bohwaz tags: dev | |
2017-03-09
| ||
05:01 | Ajout possibilité légende optionnelle pour fichiers (wiki), cf. [d7d50365514d2f84573773614877a8556dab5ee0] check-in: 8bf795cd47 user: bohwaz tags: dev | |
Changes
Modified src/include/lib/Garradin/DB.php from [51ccbaed54] to [599bdd31e0].
1 2 3 4 | <?php namespace Garradin; | | > > > > | > > > > > > > > > > > > > > > > > > | > | | > > | > | > > > > > > > | | | | | | > | < < < | < < < < < < < < < | < | < < | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | | | | > | | | | > | | | | > | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | <?php namespace Garradin; class DB { static protected $_instance = null; /** * Instance SQLite3 * @var SQLite3 */ protected $db = null; /** * Options d'initialisation de SQLite3 * @var null */ protected $flags = null; /** * Transaction en cours? * @var integer */ protected $transaction = 0; /** * Modes de retour des résultats */ const NUM = \SQLITE3_NUM; const ASSOC = \SQLITE3_ASSOC; const BOTH = \SQLITE3_BOTH; const OBJ = 4; // SQLITE3_ASSOC, NUM and BOTH are 1, 2 and 3, so let's start at 4 /** * Format de date utilisé pour le stockage */ const DATE_FORMAT = 'Y-m-d H:i:s'; static public function getInstance($create = false) { return self::$_instance ?: self::$_instance = new DB($create); } private function __clone() { // Désactiver le clonage, car on ne veut qu'une seule instance } public function __construct($create = false) { $this->flags = \SQLITE3_OPEN_READWRITE; if ($create) { $this->flags |= \SQLITE3_OPEN_CREATE; } // Ne pas se connecter ici, on ne se connectera que quand une requête sera faite } public function connect() { if ($this->db) { return true; } $this->db = new \SQLite3(DB_FILE, $this->flags); $this->db->enableExceptions(true); // Le timeout par défaut est 0, on le met à 1 seconde, si ça ne suffit pas on augmentera plus tard $this->db->busyTimeout(1000); // Activer les contraintes des foreign keys $this->db->exec('PRAGMA foreign_keys = ON;'); $this->db->createFunction('transliterate_to_ascii', ['Garradin\Utils', 'transliterateToAscii']); $this->db->createFunction('base64', 'base64_encode'); $this->db->createFunction('rank', ['\KD2\DB', 'sqlite_rank']); $this->db->createFunction('haversine_distance', ['\KD2\DB', 'sqlite_haversine']); } public function escape($str) { // escapeString n'est pas binary safe: https://bugs.php.net/bug.php?id=62361 $str = str_replace("\0", "\\0", $str); $this->connect(); return $this->db->escapeString($str); } public function quote($str) { return '\'' . $this->escape($str) . '\''; } public function begin() { if (!$this->transaction) { $this->connect(); $this->db->exec('BEGIN;'); } $this->transaction++; return $this->transaction == 1 ? true : false; } public function commit() { if ($this->transaction == 1) { $this->connect(); $this->db->exec('END;'); } if ($this->transaction > 0) { $this->transaction--; } return $this->transaction ? false : true; } public function rollback() { $this->connect(); $this->db->exec('ROLLBACK;'); $this->transaction = 0; return true; } protected function getArgType(&$arg, $name = '') { switch (gettype($arg)) { case 'double': return \SQLITE3_FLOAT; case 'integer': case 'boolean': |
︙ | ︙ | |||
163 164 165 166 167 168 169 170 171 172 173 174 | && in_array($arg[0], [\SQLITE3_FLOAT, \SQLITE3_INTEGER, \SQLITE3_NULL, \SQLITE3_TEXT, \SQLITE3_BLOB])) { $type = $arg[0]; $arg = $arg[1]; return $type; } default: throw new \InvalidArgumentException('Argument '.$name.' is of invalid type '.gettype($arg)); } } | > > > > > > | > | | 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | && in_array($arg[0], [\SQLITE3_FLOAT, \SQLITE3_INTEGER, \SQLITE3_NULL, \SQLITE3_TEXT, \SQLITE3_BLOB])) { $type = $arg[0]; $arg = $arg[1]; return $type; } case 'object': if ($arg instanceof \DateTime) { $arg = $arg->format(self::DATE_FORMAT); return \SQLITE3_TEXT; } default: throw new \InvalidArgumentException('Argument '.$name.' is of invalid type '.gettype($arg)); } } public function query($query, Array $args = []) { $this->connect(); $statement = $this->db->prepare($query); $nb = $statement->paramCount(); if (!empty($args)) { if (is_array($args) && count($args) == 1 && is_array(current($args))) { $args = current($args); |
︙ | ︙ | |||
211 212 213 214 215 216 217 | $type = $this->getArgType($value, $key); $statement->bindValue(':'.$key, $value, $type); } } } try { | > > > > | | | | | < < | < < < < < < < < < | > | < | < < < | < < | | < < < < | > | | > | > > | | > > | > | > > | > | | > > | | < < < | > | | | | | > > > | < | < < < < < < < < < | | | < | | | | < | < < | < < < | | 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | $type = $this->getArgType($value, $key); $statement->bindValue(':'.$key, $value, $type); } } } try { // Return a boolean for write queries to avoid accidental duplicate execution // see https://bugs.php.net/bug.php?id=64531 $result = $statement->execute(); return $statement->readOnly() ? $result : (bool) $result; } catch (\Exception $e) { throw new \RuntimeException($e->getMessage() . "\n" . $query . "\n" . json_encode($args, true)); } } public function get($query) { $args = array_slice(func_get_args(), 2); return $this->fetch($this->query($query, $args), self::OBJ); } public function getAssoc($query) { $args = array_slice(func_get_args(), 1); return $this->fetchAssoc($this->query($query, $args)); } public function getAssocKey($query) { $args = array_slice(func_get_args(), 2); return $this->fetchAssocKey($this->query($query, $args), self::OBJ); } public function insert($table, Array $fields) { $fields_names = array_keys($fields); $query = sprintf('INSERT INTO %s (%s) VALUES (:%s);', $table, implode(', ', $fields_names), implode(', :', $fields_names)); return $this->query($query, $fields); } public function update($table, Array $fields, $where) { // No fields to update? no need to do a query if (empty($fields)) { return false; } $args = array_slice(func_get_args(), 3); $column_updates = []; foreach ($fields as $key=>$value) { $key = 'field_' . $key; // Append to arguments $args[$key] = $value; $column_updates[] = sprintf('%s = :%s', $key, $key); } $column_updates = implode(', ', $column_updates); $query = sprintf('UPDATE %s SET %s WHERE %s;', $table, $column_updates, $where); return $this->query($query, $args); } public function delete($table, $where) { $query = sprintf('DELETE FROM %s WHERE %s;', $table, $where); return $this->query($query, array_slice(func_get_args(), 2)); } public function exec($query) { return $this->query($query, array_slice(func_get_args(), 1)); } public function first($query) { $res = $this->query($query, array_slice(func_get_args(), 2)); $row = $res->fetchArray($all_columns ? SQLITE3_ASSOC : SQLITE3_NUM); $res->finalize(); return is_array($row) ? (object) $row : false; } public function firstColumn($query) { $res = $this->query($query, array_slice(func_get_args(), 1)); $row = $res->fetchArray(\SQLITE3_NUM); return count($row) > 0 ? $row[0] : false; } public function fetch(\SQLite3Result $result, $mode = null) { $as_obj = false; if ($mode === self::OBJ) { $as_obj = true; $mode = self::ASSOC; |
︙ | ︙ | |||
351 352 353 354 355 356 357 | $result->finalize(); unset($result, $row); return $out; } | | > | | 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | $result->finalize(); unset($result, $row); return $out; } protected function fetchAssoc(\SQLite3Result $result) { $out = []; while ($row = $result->fetchArray(\SQLITE3_NUM)) { // FIXME: use generator $out[$row[0]] = $row[1]; } $result->finalize(); unset($result, $row); return $out; } protected function fetchAssocKey(\SQLite3Result $result, $mode = null) { $as_obj = false; if ($mode === self::OBJ) { $as_obj = true; $mode = self::ASSOC; |
︙ | ︙ | |||
391 392 393 394 395 396 397 | $result->finalize(); unset($result, $row); return $out; } | | | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | $result->finalize(); unset($result, $row); return $out; } public function countRows(\SQLite3Result $result) { $i = 0; while ($result->fetchArray(\SQLITE3_NUM)) { $i++; } $result->reset(); return $i; } public function prepare($query) { return $this->db->prepare($query); } /** * @deprecated */ public function simpleInsert($table, Array $fields) { return $this->insert($table, $fields); } /** * @deprecated */ public function simpleUpdate($table, Array $fields, $where) { return $this->update($table, $fields, $where); } /** * @deprecated */ public function simpleExec($query) { return $this->simpleStatement($query, array_slice(func_get_args(), 1)); } /** * @deprecated */ public function escapeString($str) { return $this->escape($str); } /** * @deprecated */ public function simpleStatement($query, Array $args = []) { return $this->statement($query, $args); } /** * @deprecated */ public function simpleStatementFetch($query, $mode = null) { $args = array_slice(func_get_args(), 2); return $this->fetch($this->query($query, $args), $mode); } /** * @deprecated */ public function simpleStatementFetchAssoc($query) { $args = array_slice(func_get_args(), 1); return $this->fetchAssoc($this->query($query, $args)); } /** * @deprecated */ public function simpleStatementFetchAssocKey($query, $mode = null) { $args = array_slice(func_get_args(), 2); return $this->fetchAssocKey($this->query($query, $args), $mode); } /** * @deprecated */ public function queryFetch($query, $mode = null) { return $this->fetch($this->query($query), $mode); } /** * @deprecated */ public function queryFetchAssoc($query) { return $this->fetchAssoc($this->query($query)); } /** * @deprecated */ public function queryFetchAssocKey($query, $mode = null) { return $this->fetchAssocKey($this->query($query), $mode); } /** * @deprecated */ public function simpleQuerySingle($query, $all_columns = false) { $res = $this->query($query, array_slice(func_get_args(), 2)); $row = $res->fetchArray($all_columns ? SQLITE3_ASSOC : SQLITE3_NUM); $res->finalize(); if (!$all_columns) { if (isset($row[0])) { return $row[0]; } return false; } else { return $row; } } } |