Audit Database Class
Php
code posted
created at 30 Sep 16:59
Edit
|
Back
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 |
<?php class DataBase { protected $_pdo = null; protected $_banco = null; protected $_config = null; public function __construct() { try { $this->setConnection(); if (!$this->hasSchema('audit')) { $this->criarTabelas(); } } catch (\Exception $e) { if (stripos($e->getMessage(), 'SQLSTATE[08006]') !== false) { $this->criarBanco(); $this->setConnection(); $this->criarTabelas(); } else { throw $e; } } } public function __destruct() { $this->_pdo = null; } protected function setConnection($novoBanco = false) { $dbname = \Audit\Registry::get('audit.db.dbname'); $this->_banco = $novoBanco ? $dbname : sprintf('ad_%s', $dbname); $this->_config = $this->getResource()->config->storage->db; $pdo = new \PDO(sprintf($this->_config->dsn, $this->_banco), $this->_config->user, base64_decode($this->_config->pass)); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_CLASS); $pdo->exec("SET client_encoding = 'UTF8';"); $pdo->exec("SET NAMES 'UTF8';"); $this->_pdo = $pdo; } /** * * @return \PDO DB instance */ public function getDB() { return $this->_pdo; } protected function hasSchema($schema) { $sql = " SELECT schema_name FROM information_schema.schemata WHERE catalog_name = '%s' AND schema_name = '%s' LIMIT 1 "; $params = [$this->_banco, $schema]; $sql = vsprintf($sql, $params); $result = $this->getDB()->query($sql)->fetchColumn(0); return (bool) $result; } /** * Begin a transaction if none's active * @return \Siplan\Auditoria\DataBase */ public function begin() { if (!$this->getDB()->inTransaction() && !$this->getDB()->beginTransaction()) { throw new \Exception('Erro ao iniciar a transação para auditoria.'); } return $this; } /** * Commit a transaction if is active * @return \Siplan\Auditoria\DataBase */ public function commit() { if ($this->getDB()->inTransaction()) { $this->getDB()->commit(); } return $this; } /** * Rollback a transaction if is active * @return \Siplan\Auditoria\DataBase */ public function rollback() { if ($this->getDB()->inTransaction()) { $this->getDB()->rollBack(); } return $this; } public function getLastError() { $error = $this->getDB()->errorInfo(); return $error[2]; } } |
2.98 KB in 5 ms with coderay