Title / Description
Code <?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]; } }
Author
Highlight as C C++ CSS Clojure Delphi ERb Groovy (beta) HAML HTML JSON Java JavaScript PHP Plain text Python Ruby SQL XML YAML diff code