public static function castPdo(\PDO $c, array $a, Stub $stub, $isNested) { $a = array(); $errmode = $c->getAttribute(\PDO::ATTR_ERRMODE); $c->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); foreach (self::$pdoAttributes as $attr => $values) { if (!isset($attr[0])) { $attr = $values; $values = array(); } try { $a[$attr] = 'ERRMODE' === $attr ? $errmode : $c->getAttribute(constant("PDO::ATTR_{$attr}")); if ($values && isset($values[$a[$attr]])) { $a[$attr] = new ConstStub($values[$a[$attr]], $a[$attr]); } } catch (\Exception $m) { } } $m = "~"; $a = (array) $c + array($m . 'inTransaction' => method_exists($c, 'inTransaction'), $m . 'errorInfo' => $c->errorInfo(), $m . 'attributes' => $a); if ($a[$m . 'inTransaction']) { $a[$m . 'inTransaction'] = $c->inTransaction(); } else { unset($a[$m . 'inTransaction']); } if (!isset($a[$m . 'errorInfo'][1], $a[$m . 'errorInfo'][2])) { unset($a[$m . 'errorInfo']); } $c->setAttribute(\PDO::ATTR_ERRMODE, $errmode); return $a; }
protected function configure() { $this->pdo = new \PDO($this->getOption('dsn'), $this->getOption('username'), $this->getOption('password')); $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $this->driverName = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME); $this->configureDriver(); }
/** * executes all the update classes */ private function _performUpdates() { foreach ($this->_availableUpdates as $rev => $updateList) { foreach ($updateList as $u) { if (!empty($u[3]) && $this->_conn->getAttribute(PDO::ATTR_DRIVER_NAME) != $u[3]) { continue; } $updateFormat = $u[5]; $this->_conn->beginTransaction(); try { $instance = null; if ($updateFormat == 'sql') { require_once 'Indechse/Maintain/Update/SqlExecute.php'; $instance = new Indechse_Maintain_Update_SqlExecute($this->_conn, $rev); $instance->setSql(file_get_contents($this->_updateLocation . '/' . $u[0])); } else { $className = 'Update_' . $u[4]; require_once $this->_updateLocation . '/' . $u[0]; $instance = new $className($this->_conn, $rev); } $instance->update(); $this->_markUpdateComplete($rev, $u[4] . '.' . $u[5]); $this->_conn->commit(); } catch (Exception $ex) { $this->_conn->rollBack(); throw new Exception(sprintf("Update %s (%d) failed with message: %s", $u[0], $rev, $ex->getMessage()), $ex->getCode(), $ex); } } } }
public static function castPdo(\PDO $c, array $a, Stub $stub, $isNested) { $attr = array(); $errmode = $c->getAttribute(\PDO::ATTR_ERRMODE); $c->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); foreach (self::$pdoAttributes as $k => $v) { if (!isset($k[0])) { $k = $v; $v = array(); } try { $attr[$k] = 'ERRMODE' === $k ? $errmode : $c->getAttribute(constant('PDO::ATTR_' . $k)); if ($v && isset($v[$attr[$k]])) { $attr[$k] = new ConstStub($v[$attr[$k]], $attr[$k]); } } catch (\Exception $e) { } } $prefix = Caster::PREFIX_VIRTUAL; $a += array($prefix . 'inTransaction' => method_exists($c, 'inTransaction'), $prefix . 'errorInfo' => $c->errorInfo(), $prefix . 'attributes' => new EnumStub($attr)); if ($a[$prefix . 'inTransaction']) { $a[$prefix . 'inTransaction'] = $c->inTransaction(); } else { unset($a[$prefix . 'inTransaction']); } if (!isset($a[$prefix . 'errorInfo'][1], $a[$prefix . 'errorInfo'][2])) { unset($a[$prefix . 'errorInfo']); } $c->setAttribute(\PDO::ATTR_ERRMODE, $errmode); return $a; }
/** * Connect to a database via FS_PDO * * @param mixed $dsn data source for database connection (array or string) * @param $login * @param $password */ public function connect_db($dsn, $login, $password) { try { $this->db = new PDO($dsn, $login, $password); } catch (PDOException $e) { $this->debug($e->getMessage()); $this->file_not_found(); //program terminates in function file_not_found() } $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $driver = $this->db->getAttribute(PDO::ATTR_DRIVER_NAME); $this->debug("our driver is {$driver}"); switch ($driver) { case 'mysql': $quoter = '`'; break; case 'pgsql': if (DEFAULT_DSN_SCHEMA) { $this->db->exec('SET SEARCH_PATH=' . DEFAULT_DSN_SCHEMA); } $quoter = '"'; break; default: $quoter = ''; break; } define('DB_FIELD_QUOTE', $quoter); }
/** * Note if your table name is a reserved word for your target DB you should quote it in the appropriate way e.g. * for MySQL enclose the name in `backticks`. * * @param \PDO $pdo * @param string $tableName */ public function __construct(\PDO $pdo, $tableName) { $this->pdo = $pdo; $this->tableName = $tableName; if (\PDO::ERRMODE_EXCEPTION !== $this->pdo->getAttribute(\PDO::ATTR_ERRMODE)) { throw new WriterException('Please set the pdo error mode to PDO::ERRMODE_EXCEPTION'); } }
/** * Returns the driver of database * * @return string */ public function getDriver() { try { return $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME); } catch (PDOException $e) { ConnectionException::pdoError($e->getMessage(), $e->getCode()); } }
/** * Get a PDO attribute * * @param int $attr * @return bool * @throws DatabaseException */ public function pdoGetAttribute(int $attr) { try { return $this->pdo->getAttribute($attr); } catch (\PDOException $e) { throw DatabaseException::pdoError($e->getMessage()); } }
/** * Get the server software version. * * @return string */ public function getServerVersion() { try { $version = $this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION); } catch (\PDOException $e) { return NULL; } return $version; }
/** * Initializes database connection * * @param $pixie * @param string $config Name of the connection to initialize * @return \PHPixie\DB\PDOV\Connection */ public function __construct($pixie, $config) { parent::__construct($pixie, $config); $this->conn = new \PDO($pixie->config->get("db.{$config}.connection"), $pixie->config->get("db.{$config}.user", ''), $pixie->config->get("db.{$config}.password", '')); $this->conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $this->db_type = strtolower(str_replace('PDO_', '', $this->conn->getAttribute(\PDO::ATTR_DRIVER_NAME))); if ($this->db_type != 'sqlite') { $this->conn->exec("SET NAMES utf8"); } }
/** * @param \PDO $connection * @param string $cacheTableName * @param \MToolkit\Core\MObject $parent * @throws \Exception */ public function __construct(\PDO $connection, $cacheTableName = 'MToolkitCache', MObject $parent = null) { parent::__construct($parent); if ($connection->getAttribute(\PDO::ATTR_DRIVER_NAME) != 'sqlite') { throw new \Exception('Invalid database connection, required sqlite, passed ' . $connection->getAttribute(\PDO::ATTR_DRIVER_NAME)); } $this->connection = $connection; $this->cacheTableName = $cacheTableName; $this->init(); }
public final function __construct(\PDO $_connection) { $this->current_driver = $_connection->getAttribute(\PDO::ATTR_DRIVER_NAME); if (!in_array($this->current_driver, $this->approved_pdo_drivers)) { throw new \Exception("Incorrect PDO connection"); } if ($_connection->getAttribute(\PDO::ATTR_DRIVER_NAME) == self::DRIVER_SQLITE) { $this->sql_select_lock_rows = ""; } $this->sql_select_lock_rows = $this->current_driver != self::DRIVER_SQLITE ? " FOR UPDATE" : ""; $this->connection = $_connection; }
/** * Retrieves the table adapter based on the driver used to initialise the PDO object * * @param string $tableName */ public function getAdapter($tableName) { switch ($this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME)) { case 'mysql': $adapter = new MySQL($this->pdo, $tableName); break; case 'sqlite': default: $adapter = new SQLite($this->pdo, $tableName); break; } return $adapter; }
/** * Creates a login attempt and queues it. * * @param string $username * @param string $password * @var \PDO $pdo * @throws Exception */ public function __construct($username, $password, \PDO $pdo) { $this->pdo = $pdo; if ($this->pdo->getAttribute(PDO::ATTR_ERRMODE) !== PDO::ERRMODE_EXCEPTION) { $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } $this->username = $username; $this->password = $password; if (!$this->isQueueSizeExceeded()) { $this->addToQueue(); } else { throw new Exception("Queue size has been exceeded.", 503); } }
private function _is_connected() { if ($this->_connection) { return $this->_connection->getAttribute(\PDO::ATTR_CONNECTION_STATUS); } return false; }
/** * @param string $table * @return array * @throws DBException */ private function getFullFields($table) { if (isset($this->tableToFields[$table])) { return $this->tableToFields[$table]; } $driver = $this->db->getAttribute(\PDO::ATTR_DRIVER_NAME); $fields = []; if ($driver == 'sqlite') { $sql = "PRAGMA table_info('" . $table . "');"; $key = "name"; } elseif ($driver == 'mysql') { $sql = "DESCRIBE " . $table . ";"; $key = "Field"; } else { $sql = "SELECT column_name FROM information_schema.columns WHERE table_name = '" . $table . "';"; $key = "column_name"; } if (false !== ($list = $this->run($sql))) { foreach ($list as $record) { $fields[] = $record[$key]; } } $this->tableToFields[$table] = $fields; return $fields; }
/** * 连接数据库 */ private function connectDB($dbarr) { $keyName = $this->name . '_' . $dbarr['sec']; if (!isset($this->pdos[$keyName])) { if (!$dbarr) { throw new \InvalidArgumentException('数据库不存在'); } $dsn = "mysql:host={$dbarr['host']};port={$dbarr['port']};dbname={$dbarr['db']};charset=utf8mb4"; $pdo = new \PDO($dsn, $dbarr['user'], $dbarr['pass']); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $status = $pdo->getAttribute(\PDO::ATTR_SERVER_INFO); //重连机制 if (strpos($status, 'MySQL server has gone away') === false) { $pdo = new \PDO($dsn, $dbarr['user'], $dbarr['pass']); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); } $pdo->query('set names utf8mb4'); $this->pdos[$keyName] = $pdo; } else { $status = $this->pdos[$keyName]->getAttribute(\PDO::ATTR_SERVER_INFO); if (strpos($status, 'MySQL server has gone away') !== false) { $pdo = new \PDO($dsn, $dbarr['user'], $dbarr['pass']); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $pdo->query('set names utf8mb4'); $this->pdos[$keyName] = $pdo; } } return $this->pdos[$keyName]; }
/** * Get the current PDO Driver name * * @return string */ public function driver_name() { // Make sure the database is connected $this->_connection or $this->connect(); // Getting driver name return $this->_connection->getAttribute(\PDO::ATTR_DRIVER_NAME); }
/** * {@inheritdoc} */ public function write($id, $data) { // get table/column $dbTable = $this->dbOptions['db_table']; $dbDataCol = $this->dbOptions['db_data_col']; $dbIdCol = $this->dbOptions['db_id_col']; $dbTimeCol = $this->dbOptions['db_time_col']; $sql = 'mysql' === $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME) ? "INSERT INTO {$dbTable} ({$dbIdCol}, {$dbDataCol}, {$dbTimeCol}) VALUES (:id, :data, :time) " . "ON DUPLICATE KEY UPDATE {$dbDataCol} = VALUES({$dbDataCol}), {$dbTimeCol} = CASE WHEN {$dbTimeCol} = :time THEN (VALUES({$dbTimeCol}) + 1) ELSE VALUES({$dbTimeCol}) END" : "UPDATE {$dbTable} SET {$dbDataCol} = :data, {$dbTimeCol} = :time WHERE {$dbIdCol} = :id"; try { //session data can contain non binary safe characters so we need to encode it $encoded = base64_encode($data); $stmt = $this->pdo->prepare($sql); $stmt->bindParam(':id', $id, \PDO::PARAM_STR); $stmt->bindParam(':data', $encoded, \PDO::PARAM_STR); $stmt->bindValue(':time', time(), \PDO::PARAM_INT); $stmt->execute(); if (!$stmt->rowCount()) { // No session exists in the database to update. This happens when we have called // session_regenerate_id() $this->createNewSession($id, $data); } } catch (\PDOException $e) { throw new \RuntimeException(sprintf('PDOException was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e); } return true; }
/** * Get the value of an attribute. Uses an element of the Attributes array if available, falling back to parent. * * @param mixed $attr The attribute whose value is to be fetched. * @return mixed The value of the attribute. */ public function getAttribute($attr) { if (isset($this->attributes[$attr])) { return $this->attributes[$attr]; } return parent::getAttribute($attr); }
/** * Get slave PDO connection driver. * * @return mixed */ public function getSlaveDriver() { if (!$this->slave instanceof PDO) { $this->slave = $this->getSlavePdo(); } return $this->slave->getAttribute(PDO::ATTR_DRIVER_NAME); }
protected function _backupData($store) { switch ($this->_serverLocation) { case 'local': $this->_out->logNotice("doing 'local' data backup"); $this->_backupDataFromLocal($store); break; case 'remote': $this->_out->logNotice("doing 'remote' data backup"); $this->_backupDataFromRemote($store); break; default: // try to detect best possibility $s = $this->_db->getAttribute(PDO::ATTR_CONNECTION_STATUS); $this->_out->logNotice("connection status: {$s}"); if (stripos($s, "localhost") === false && stripos($s, "127.0.0.1") === false) { // remote $this->_out->logNotice("detected 'remote' data backup"); $this->_backupDataFromRemote($store); } else { // maybe local will work try { $this->_out->logNotice("trying 'local' data backup"); $this->_backupDataFromLocal($store); } catch (Exception $ex) { $this->_out->logNotice("fallback to 'remote' data backup"); $this->_backupDataFromRemote($store); } } } }
/** * Connect * * @throws Exception\DbException */ public function connect() { if ($this->_dbh instanceof \PDO) { return; } try { $key = $this->startProfiler('connection'); $this->_dbh = new \PDO($this->_dsn, $this->_username, $this->_password, $this->_driverOptions); $this->_dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $this->_driverName = strtolower($this->_dbh->getAttribute(\PDO::ATTR_DRIVER_NAME)); $this->endProfiler($key); } catch (\PDOException $e) { $this->endProfiler($key); throw new Exception\DbException($e->getMessage(), $e->getCode(), $e); } }
/** * Checks if the driver supports quoting * * @return bool */ public function supportsQuoting() { if (!$this->isConnected()) { $this->connect(); } return $this->_PdoConnection->getAttribute(PDO::ATTR_DRIVER_NAME) !== 'odbc'; }
public function __construct(\PDO $conn, $tableName) { if ('pgsql' != $conn->getAttribute(\PDO::ATTR_DRIVER_NAME)) { throw new \InvalidArgumentException('Invalid PDO driver specified.'); } parent::__construct($conn, $tableName); }
/** * returns the drivername for the current PDO-Instance * * @return string PDO driver */ public final function _getDriver() { $drivername = $this->_conn->getAttribute(PDO::ATTR_DRIVER_NAME); $driver = null; switch ($drivername) { case 'pgsql': $driver = self::DRIVER_PGSQL; break; case 'mysql': $driver = self::DRIVER_MYSQL; break; default: throw Exception("unsupported PDO driver '{$drivername}'"); } return $driver; }
/** * Initialize the SQL datastore. */ protected function __construct() { $config = SimpleSAML_Configuration::getInstance(); $dsn = $config->getString('store.sql.dsn'); $username = $config->getString('store.sql.username', NULL); $password = $config->getString('store.sql.password', NULL); $this->prefix = $config->getString('store.sql.prefix', 'simpleSAMLphp'); $this->pdo = new PDO($dsn, $username, $password); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->driver = $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME); if ($this->driver === 'mysql') { $this->pdo->exec('SET time_zone = "+00:00"'); } $this->initTableVersionTable(); $this->initKVTable(); }
/** * gathers Warning info from \PDO * @param string $sqlQueryString SQL query string with placeholders * @param array $options options passed to query * @return string */ private function _getWarnings($sqlQueryString, $options = []) { if ($this->_databaseServer === self::DB_MYSQL) { $stm = $this->_pdo->query('SHOW WARNINGS'); $sqlWarnings = $stm->fetchAll(\PDO::FETCH_ASSOC); } else { $sqlWarnings = [['Message' => 'WarningReporting not impl. for ' . $this->_pdo->getAttribute(\PDO::ATTR_DRIVER_NAME)]]; } if (count($sqlWarnings) > 0) { $warnings = "Query:\n{$sqlQueryString}\n"; if (!empty($options)) { $warnings .= "Params: ("; foreach ($options as $key => $value) { $warnings .= $key . '=' . json_encode($value) . ', '; } $warnings = substr($warnings, 0, -2) . ")\n"; } $warnings .= "Produced Warnings:"; foreach ($sqlWarnings as $warn) { $warnings .= "\n* " . $warn['Message']; } return $warnings; } return ''; }
protected function connect($settings) { if (defined('\\PDO::ATTR_DRIVER_NAME')) { $emulate_prepares_below_version = '5.1.17'; $dsndefaults = array_fill_keys(['host', 'port', 'unix_socket', 'dbname', 'charset'], null); $dsnarr = array_intersect_key($settings, $dsndefaults); $dsnarr += $dsndefaults; // connection options I like $options = array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC); // connection charset handling for old php versions if ($dsnarr['charset'] and version_compare(PHP_VERSION, '5.3.6', '<')) { $options[\PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $dsnarr['charset']; } $dsnpairs = array(); foreach ($dsnarr as $k => $v) { if ($v === null) { continue; } $dsnpairs[] = "{$k}={$v}"; } $dsn = 'mysql:' . implode(';', $dsnpairs); $dbh = new \PDO($dsn, $settings['user'], $settings['pass'], $options); // Set prepared statement emulation depending on server version $serverversion = $dbh->getAttribute(\PDO::ATTR_SERVER_VERSION); $emulate_prepares = version_compare($serverversion, $emulate_prepares_below_version, '<'); $dbh->setAttribute(\PDO::ATTR_EMULATE_PREPARES, $emulate_prepares); $this->pdo = $dbh; } else { echo 'PDO unavailable'; } }
/** * Tests MySQL connection * * @return void */ public function testMySQL() { try { $pdo = new PDO( "mysql:host=" . TESTSUITE_SERVER . ";dbname=" . TESTSUITE_DATABASE, TESTSUITE_USER, TESTSUITE_PASSWORD ); $this->assertNull( $pdo->errorCode(), "Error when trying to connect to database" ); //$pdo->beginTransaction(); $test = $pdo->exec("SHOW TABLES;"); //$pdo->commit(); $this->assertEquals( 0, $pdo->errorCode(), 'Error trying to show tables for database' ); } catch (Exception $e) { $this->fail("Error: ".$e->getMessage()); } // Check id MySQL server is 5 version preg_match( "/^(\d+)?\.(\d+)?\.(\*|\d+)/", $pdo->getAttribute(constant("PDO::ATTR_SERVER_VERSION")), $version_parts ); $this->assertEquals(5, $version_parts[1]); }