/** * Get Database Connection * * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection */ public function getConnection() { if (!$this->connection) { $dbConfig = array('driver' => 'pdo', 'dsn' => 'mysql:dbname=ipc2013.testing.test;host=localhost;charset=utf8', 'user' => 'ipc2013', 'pass' => 'ipc2013'); $this->adapter = new Adapter($dbConfig); $this->connection = $this->createDefaultDBConnection($this->adapter->getDriver()->getConnection()->getResource(), 'ipc2013.testing.test'); } return $this->connection; }
/** * Load config from db-adapter * * @param \Zend\Db\Adapter\Adapter $db * @return array */ protected function loadConfig() { if (empty($this->dbAdapter)) { return $this->config; } $platform = $this->dbAdapter->getPlatform(); $driver = $this->dbAdapter->getDriver(); $query = $this->dbAdapter->query(' SELECT ' . $platform->quoteIdentifier('value') . ' FROM ' . $platform->quoteIdentifier('settings') . ' WHERE ' . $platform->quoteIdentifier('key') . ' = ' . $platform->quoteValue('ini-cache') . ' AND ' . $platform->quoteIdentifier('type') . ' = ' . $platform->quoteValue('ini-cache') . ' LIMIT 1 '); $this->config = array(); $result = $query->execute(); if ($result->getAffectedRows() > 0) { foreach ($result as $cache) { $this->config = ArrayUtils::merge($this->config, (array) unserialize($cache['value'])); } } else { $query = $this->dbAdapter->query(' SELECT ' . $platform->quoteIdentifier('key') . ', ' . $platform->quoteIdentifier('value') . ' FROM ' . $platform->quoteIdentifier('settings') . ' WHERE ' . $platform->quoteIdentifier('type') . ' = ' . $platform->quoteValue('ini') . ' '); foreach ($query->execute() as $pair) { $key = (string) $pair['key']; $value = (string) $pair['value']; $entry = array(); $curr =& $entry; foreach (explode('.', $key) as $sub) { $curr[$sub] = null; $curr =& $curr[$sub]; } $curr = $value; $this->config = ArrayUtils::merge($this->config, $entry); } $query = $this->dbAdapter->query(' INSERT INTO ' . $platform->quoteIdentifier('settings') . ' ( ' . $platform->quoteIdentifier('key') . ', ' . $platform->quoteIdentifier('value') . ', ' . $platform->quoteIdentifier('type') . ' ) VALUES ( ' . $driver->formatParameterName('key') . ', ' . $driver->formatParameterName('value') . ', ' . $driver->formatParameterName('type') . ' ) '); $query->execute(array('key' => 'ini-cache', 'value' => serialize($this->config), 'type' => 'ini-cache')); } $this->dbAdapter = null; return $this->config; }
public function save(Queue $queue) { if ($queue->getId()) { $query = $this->dbAdapter->query('UPDATE `queues` SET `name` = :name WHERE `id = :id`'); $query->execute($queue->getArrayCopy()); } else { $query = $this->dbAdapter->query("INSERT INTO `queues` (`name`) VALUES (:name)"); $query->execute(['name' => $queue->getName()]); $queue->setId($this->dbAdapter->getDriver()->getLastGeneratedValue()); } return $queue; }
/** * @param array|\Zend\Db\Adapter\Driver\DriverInterface $config * @throws UnsupportedDriverException * @return \Zend\Db\Adapter\Adapter */ public static function factory($config) { $platform = new SphinxQL(); $adapter = new ZendDBAdapter($config, $platform); $driver = $adapter->getDriver(); // Check driver if ($driver instanceof ZendPdoDriver && $driver->getDatabasePlatformName(ZendPdoDriver::NAME_FORMAT_CAMELCASE) == 'Mysql') { $driver->registerStatementPrototype(new PdoStatement()); } elseif (!$driver instanceof ZendMysqliDriver) { $class = get_class($driver); throw new UnsupportedDriverException($class . ' not supported. Use Zend\\Db\\Adapter\\Driver\\Pdo\\Pdo or Zend\\Db\\Adapter\\Driver\\Mysqli\\Mysqli'); } $platform->setDriver($adapter->getDriver()); return $adapter; }
/** * Process the command * * @return integer */ public function processCommandTask() { // load autoload configuration from project $config = ConfigFactory::fromFiles(glob($this->params->projectConfigDir . '/autoload/{,*.}{global,development,local}.php', GLOB_BRACE)); // check for db config if (empty($config) || !isset($config['db'])) { $this->console->writeFailLine('task_crud_check_db_connection_no_config'); return 1; } // create db adapter instance try { $dbAdapter = new Adapter($config['db']); } catch (InvalidArgumentException $e) { $this->console->writeFailLine('task_crud_check_db_connection_config_inconsistent'); return 1; } // connect to database try { $connection = $dbAdapter->getDriver()->getConnection()->connect(); } catch (RuntimeException $e) { $this->console->writeFailLine('task_crud_check_db_connection_failed'); return 1; } $this->params->dbAdapter = $dbAdapter; return 0; }
/** * Simple query executor, expects results and returns them as an assoc array * @param $query * @param array $params * @return array * @throws \Exception */ public function executeRawQuery($query, array $params = array()) { $this->logQuery($this->fixTableName($query), $params); try { $this->result = $this->_adapter->query($this->fixTableName($query), $params); } catch (\Exception $e) { $this->result = new ResultSet(ResultSet::TYPE_ARRAY, []); $mysqli = $this->_adapter->getDriver()->getConnection()->getResource(); error_log("ERROR: ADB : executeRawQuery"); error_log("Engine message: " . isset($mysqli->error) ? $mysqli->error : "No message available"); error_log($e->getMessage()); error_log("query: " . $this->getFullQuery($query, $params)); error_log($e->getTraceAsString()); $throw = true; if (isset($this->_conf['suppress-exceptions'])) { if ($this->_conf['suppress-exceptions']) { $throw = false; } } if (!isset($this->_conf['throw-engine-message'])) { // throw engine message by default $this->_conf['throw-engine-message'] = true; } if ($throw) { if (isset($mysqli->error) && $this->_conf['throw-engine-message'] && !empty($mysqli->error)) { throw new \Exception($mysqli->error); } else { throw $e; } } } $this->safeDropCache($query); return $this->result; }
/** * Drops a stream table * * Use this function with caution. All your events will be lost! But it can be useful in migration scenarios. * * @param StreamName $streamName * @param bool $returnSql * @return string|null Whether $returnSql is true or not function will return generated sql or execute it directly */ public function dropSchemaFor(StreamName $streamName, $returnSql = false) { $dropTable = new DropTable($this->getTable($streamName)); if ($returnSql) { return $dropTable->getSqlString($this->dbAdapter->getPlatform()); } $this->dbAdapter->getDriver()->getConnection()->execute($dropTable->getSqlString($this->dbAdapter->getPlatform())); }
/** * @return bool $successfulCreate */ protected function create() : bool { $insert = $this->sql->insert($this->getTablename()); $id = $this->adapter->getDriver()->getConnection()->getLastGeneratedValue(); $this->load($id); $success = true; return $success; }
public function rollbackTransaction() { self::$transactionCounter--; if (!self::$transactionCounter) { $connection = $this->adapter->getDriver()->getConnection(); $connection->rollback(); } }
protected function dropSqliteSchema(array $streams) { foreach ($streams as $stream) { $streamSql = 'DROP TABLE IF EXISTS ' . $this->getTable($stream); $this->dbAdatper->getDriver()->getConnection()->execute($streamSql); } $snapshotSql = 'DROP TABLE IF EXISTS snapshot'; $this->dbAdatper->getDriver()->getConnection()->execute($snapshotSql); }
/** * Insert * * @param array $set * @return int */ public function insert($set) { $insert = $this->sql->insert(); $insert->values($set); $statement = $this->sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); $this->lastInsertValue = $this->adapter->getDriver()->getConnection()->getLastGeneratedValue(); return $result->getAffectedRows(); }
protected function processExpression(ExpressionInterface $expression, PlatformInterface $platform, Adapter $adapter = null, $namedParameterPrefix = null) { // static counter for the number of times this method was invoked across the PHP runtime static $runtimeExpressionPrefix = 0; if ($adapter && (!is_string($namedParameterPrefix) || $namedParameterPrefix == '')) { $namedParameterPrefix = sprintf('expr%04dParam', ++$runtimeExpressionPrefix); } $sql = ''; $statementContainer = new StatementContainer(); $parameterContainer = $statementContainer->getParameterContainer(); // initialize variables $parts = $expression->getExpressionData(); $expressionParamIndex = 1; foreach ($parts as $part) { // if it is a string, simply tack it onto the return sql "specification" string if (is_string($part)) { $sql .= $part; continue; } if (!is_array($part)) { throw new Exception\RuntimeException('Elements returned from getExpressionData() array must be a string or array.'); } // process values and types (the middle and last position of the expression data) $values = $part[1]; $types = isset($part[2]) ? $part[2] : array(); foreach ($values as $vIndex => $value) { if (isset($types[$vIndex]) && $types[$vIndex] == ExpressionInterface::TYPE_IDENTIFIER) { $values[$vIndex] = $platform->quoteIdentifierInFragment($value); } elseif (isset($types[$vIndex]) && $types[$vIndex] == ExpressionInterface::TYPE_VALUE) { // if prepareType is set, it means that this particular value must be // passed back to the statement in a way it can be used as a placeholder value if ($adapter) { $name = $namedParameterPrefix . $expressionParamIndex++; $parameterContainer->offsetSet($name, $value); $values[$vIndex] = $adapter->getDriver()->formatParameterName($name); continue; } // if not a preparable statement, simply quote the value and move on $values[$vIndex] = $platform->quoteValue($value); } elseif (isset($types[$vIndex]) && $types[$vIndex] == ExpressionInterface::TYPE_LITERAL) { $values[$vIndex] = $value; } elseif (isset($types[$vIndex]) && $types[$vIndex] == ExpressionInterface::TYPE_SELECT) { // process sub-select if ($adapter) { $values[$vIndex] = '(' . $this->processSubSelect($value, $platform, $adapter, $statementContainer->getParameterContainer()) . ')'; } else { $values[$vIndex] = '(' . $this->processSubSelect($value, $platform) . ')'; } } } // after looping the values, interpolate them into the sql string (they might be placeholder names, or values) $sql .= vsprintf($part[0], $values); } $statementContainer->setSql($sql); return $statementContainer; }
/** * @param \Zend\Db\Adapter\Adapter $adapter */ public function __construct($adapter) { $dbConfig = $adapter->getDriver()->getConnection()->getConnectionParameters(); if (isset($dbConfig['dsn'])) { $data = EhrlichAndreas_Util_Dsn::parseDsn($dbConfig['dsn']); foreach ($data as $key => $value) { $dbConfig[$key] = $value; } $data = EhrlichAndreas_Util_Dsn::parseUri($dbConfig['dsn']); if (isset($data[0])) { $dbConfig['adapter'] = ucfirst($data[0]); } if (isset($dbConfig['adapter']) && $dbConfig['driver']) { $dbConfig['adapter'] = $dbConfig['driver'] . '_' . $dbConfig['adapter']; } } $this->adapter = EhrlichAndreas_Db_Db::factory($dbConfig); $this->adapter->setConnection($adapter->getDriver()->getConnection()->getResource()); }
public function selectCategoryOptions() { $adapter = new Adapter(array('driver' => 'mysqli', 'host' => 'localhost', 'port' => '3306', 'dbname' => 'zndemo', 'username' => 'root', 'password' => '')); $result = $adapter->getDriver()->getConnection()->execute('select id,name from categories where status=1'); $selectData = array(0 => '--Select Category--'); foreach ($result as $res) { $selectData[$res['id']] = $res['name']; } return $selectData; }
public function create(array $data) { $sql = new Sql($this->adapter); $this->adapter->getDriver()->getConnection()->beginTransaction(); $insert = $sql->insert('places'); $insert->values(['name' => $data['name'], 'latitude' => $data['latitude'], 'longitude' => $data['longitude']]); $query = $sql->getSqlStringForSqlObject($insert); /** @var Result $results */ $results = $this->adapter->query($query, Adapter::QUERY_MODE_EXECUTE); $placeId = $results->getGeneratedValue(); foreach ($data['types'] as $typeId) { $insert = $sql->insert('places_place_types'); $insert->values(['place_id' => $placeId, 'place_type_id' => $typeId]); $q = $sql->getSqlStringForSqlObject($insert); $this->adapter->query($q, Adapter::QUERY_MODE_EXECUTE); } $this->adapter->getDriver()->getConnection()->commit(); return $placeId; }
/** * Insert * * @param type $set * @return type */ public function insert($set) { $insert = clone $this->sqlInsert; $insert->into($this->tableName, $this->databaseSchema); $insert->values($set); $statement = $this->adapter->createStatement(); $insert->prepareStatement($this->adapter, $statement); $result = $statement->execute(); $this->lastInsertId = $this->adapter->getDriver()->getConnection()->getLastGeneratedId(); return $result->getAffectedRows(); }
/** * Sets the DB adapter. * * @param Adapter $dbAdapter */ public function setAdapter(Adapter $dbAdapter) { $this->dbAdapter = $dbAdapter; /* * temp fix */ $driver = $this->dbAdapter->getDriver(); $driver->getConnection()->connect(); $this->dbAdapter->getPlatform()->setDriver($driver); /* --- */ $this->setSqlFromAdapter($dbAdapter); }
/** * @throws TransactionException */ public function rollbackTransaction() { if ($this->isTransactionActive === false) { throw new TransactionException("Can't rollback transaction while no one is running"); } try { $this->adapter->getDriver()->getConnection()->rollBack(); $this->isTransactionActive = false; } catch (\Exception $e) { throw new TransactionException("Can`t rollback transaction", 0, $e); } }
protected function processOffset(PlatformInterface $platform, Adapter $adapter = null, ParameterContainer $parameterContainer = null) { if ($this->offset === null) { return null; } if ($adapter) { $parameterContainer->offsetSet('offset', $this->offset, ParameterContainer::TYPE_INTEGER); return array($adapter->getDriver()->formatParameterName('offset')); } else { return array($this->offset); } }
/** * @throws Exception\UnsupportedFeatureException * @return AbstractMetadataReader */ protected function getDefaultMetadataReader() { $conn = $this->adapter->getDriver()->getConnection()->getResource(); $class = strtolower(get_class($conn)); switch ($class) { case 'pdo': return new MetadataReader\PDOMysqlMetadataReader($conn); case 'mysqli': return new MetadataReader\MysqliMetadataReader($conn); default: throw new Exception\UnsupportedFeatureException(__METHOD__ . " Does not support default metadata reader for driver '{$class}'"); } }
/** * @todo add $columns support * * @param Insert $insert * @return mixed * @throws Exception\RuntimeException */ protected function executeInsert(Insert $insert) { $insertState = $insert->getRawState(); if ($insertState['table'] != $this->table) { throw new Exception\RuntimeException('The table name of the provided Insert object must match that of the table'); } // apply preInsert features $this->featureSet->apply('preInsert', array($insert)); $statement = $this->sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); $this->lastInsertValue = $this->adapter->getDriver()->getConnection()->getLastGeneratedValue(); // apply postInsert features $this->featureSet->apply('postInsert', array($statement, $result)); return $result->getAffectedRows(); }
/** * Execute the query and return a Zend\Db\Resultset\ResultSet object * * @throws Exception\InvalidUsageException * @return \Zend\Db\ResultSet\ResultSet */ public function execute() { if ($this->adapter === null) { $msg = __METHOD__ . ": Error, prior to use execute method you must provide a valid database adapter. See Select::setDbAdapter() method."; throw new Exception\InvalidUsageException($msg); } $sql = new Sql($this->adapter); $sql_string = $sql->getSqlStringForSqlObject($this); //return $this->adapter->createStatement($sql_string)->execute(); //return $this->adapter->query($sql_string, Adapter::QUERY_MODE_EXECUTE); $result = $this->adapter->getDriver()->getConnection()->execute($sql_string); $resultset = new ResultSet(); $resultset->initialize($result); return $resultset; }
/** * Setup services which depends on the db * * @param \Zend\Db\Adapter\Adapter $db * @return \Zend\Db\Adapter\Adapter */ public function configure(DbAdapter $db) { $sm = $this->getServiceLocator(); $platform = $db->getPlatform(); $driver = $db->getDriver(); $domain = strtolower($this->getDomain()); $query = $db->query(' SELECT * FROM ' . $platform->quoteIdentifier('_central') . '.' . $platform->quoteIdentifier('fulldomain') . ' WHERE LOWER( ' . $platform->quoteIdentifier('fulldomain') . ' ) = LOWER( ' . $driver->formatParameterName('fulldomain') . ' ) '); $result = $query->execute(array('fulldomain' => $domain)); if ($result->getAffectedRows() > 0) { foreach ($result as $data) { $info = new SiteInfo(array_merge($data, array('scheme' => $this->getScheme(), 'port' => $this->getPort()))); $sm->setService('SiteInfo', $info); $driver->getConnection()->setCurrentSchema($info->getSchema()); return $db; } } else { $parts = explode('.', $domain); $subParts = array(); $mainDomain = false; while (count($parts) > 2) { $subParts[] = array_shift($parts); $mainDomain = implode('.', $parts); $result = $query->execute(array('fulldomain' => $mainDomain)); if ($result->getAffectedRows() > 0) { break; } $mainDomain = false; } if ($mainDomain) { $sm->setService('RedirectToDomain', new RedirectionService($this->getScheme(), $mainDomain, $this->getPort(), sprintf('sub-domain "%s" not found', implode('.', $subParts)), true)); } else { $config = $driver->getConnection()->getConnectionParameters(); if (empty($config['defaultDomain'])) { throw new Exception\InvalidArgumentException('Domain not found, and default domain not set'); } else { $sm->setService('RedirectToDomain', new RedirectionService($this->getScheme(), $config['defaultDomain'], $this->getPort(), 'domain not found', false)); } } } return $db; }
/** * Apply down on the migration * And remove migration name from base * * @param string $migrationName * @param array $migrationArray * @throws \Exception */ public function downgrade($migrationName, array $migrationArray) { $connection = $this->adapter->getDriver()->getConnection(); try { $connection->beginTransaction(); $query = $migrationArray['down']; $this->adapter->query($query, Adapter::QUERY_MODE_EXECUTE); $sql = new Sql($this->adapter); $delete = $sql->delete(self::TABLE); $delete->where(array('migration' => $migrationName)); $queryString = $sql->getSqlStringForSqlObject($delete); $this->adapter->query($queryString, Adapter::QUERY_MODE_EXECUTE); $connection->commit(); } catch (\Exception $exception) { $connection->rollback(); throw new \Exception($exception->getMessage()); } }
/** * Get input filters * * @return array */ protected function getInputFilters() { $inputFilter = new InputFilter(); $inputFactory = new InputFactory(); $inputFilter->add($inputFactory->createInput(['name' => 'db_host', 'required' => true, 'filters' => [['name' => 'Zend\\Filter\\StringTrim']], 'validators' => [['name' => 'callback', 'options' => ['callback' => function ($value, $data) { try { $adapter = new DbAdapter(['driver' => 'Pdo_Mysql', 'database' => $data['db_name'], 'username' => $data['db_user'], 'password' => $data['db_password'], 'port' => $data['db_port'], 'host' => $value]); $adapter->getDriver()->getConnection()->connect(); return true; } catch (Exception $e) { } return false; }, 'message' => 'Can\'t connect to the Database']]]])); $inputFilter->add($inputFactory->createInput(['name' => 'db_port', 'required' => true, 'filters' => [['name' => 'Zend\\Filter\\StringTrim']], 'validators' => [['name' => 'Zend\\Validator\\Digits']]])); $inputFilter->add($inputFactory->createInput(['name' => 'db_name', 'required' => true, 'filters' => [['name' => 'Zend\\Filter\\StringTrim']], 'validators' => []])); $inputFilter->add($inputFactory->createInput(['name' => 'db_user', 'required' => true, 'filters' => [['name' => 'Zend\\Filter\\StringTrim']], 'validators' => []])); $inputFilter->add($inputFactory->createInput(['name' => 'db_password', 'required' => false, 'filters' => [['name' => 'Zend\\Filter\\StringTrim']], 'validators' => []])); $inputFilter->add($inputFactory->createInput(['name' => 'admin_username', 'required' => true, 'filters' => [['name' => 'Zend\\Filter\\StringTrim']], 'validators' => [['name' => 'StringLength', 'options' => ['max' => self::ADMIN_NICKNAME_MAX_LENGTH]]]])); $inputFilter->add($inputFactory->createInput(['name' => 'admin_password', 'required' => true, 'filters' => [['name' => 'Zend\\Filter\\StringTrim']], 'validators' => [['name' => 'StringLength', 'options' => ['max' => self::ADMIN_PASSWORD_MAX_LENGTH]]]])); $inputFilter->add($inputFactory->createInput(['name' => 'admin_email', 'required' => true, 'filters' => [['name' => 'Zend\\Filter\\StringTrim']], 'validators' => [['name' => 'StringLength', 'options' => ['max' => self::ADMIN_EMAIL_MAX_LENGTH]], ['name' => 'emailAddress']]])); $inputFilter->add($inputFactory->createInput(['name' => 'site_email', 'required' => true, 'filters' => [['name' => 'Zend\\Filter\\StringTrim']], 'validators' => [['name' => 'StringLength', 'options' => ['max' => self::SITE_EMAIL_MAX_LENGTH]], ['name' => 'emailAddress']]])); $inputFilter->add($inputFactory->createInput(['name' => 'dynamic_cache', 'required' => false, 'filters' => [], 'validators' => [['name' => 'callback', 'options' => ['callback' => function ($value, $data) { switch ($value) { case 'xcache': return extension_loaded('xcache'); case 'wincache': return extension_loaded('wincache'); case 'apc': return version_compare('3.1.6', phpversion('apc')) > 0 || !ini_get('apc.enabled') ? false : true; default: $v = (string) phpversion('memcached'); $extMemcachedMajorVersion = $v !== '' ? (int) $v[0] : 0; return $extMemcachedMajorVersion < 1 ? false : true; } }, 'message' => 'Extension is not installed']]]])); $inputFilter->add($inputFactory->createInput(['name' => 'memcache_host', 'required' => false, 'filters' => [['name' => 'Zend\\Filter\\StringTrim']], 'validators' => []])); $inputFilter->add($inputFactory->createInput(['name' => 'memcache_port', 'required' => false, 'filters' => [['name' => 'Zend\\Filter\\StringTrim']], 'validators' => [['name' => 'Zend\\Validator\\Digits']]])); return $inputFilter; }
/** * @depends testConnection */ public function testTypeWithPreparedStatement() { if ($this->adapter->getDriver() instanceof Mysqli) { $this->markTestSkipped('Mysqli does not support prepared statement client side emulation'); } $this->adapter->query('DELETE FROM foo WHERE id = 1', Adapter::QUERY_MODE_EXECUTE); $indexer = new Indexer($this->adapter); $indexer->setQueryMode($indexer::QUERY_MODE_PREPARED); $search = clone $this->search; $search->setQueryMode($search::QUERY_MODE_PREPARED); $affectedRow = $indexer->insert('foo', ['id' => 1, 'c1' => 10, 'c2' => true, 'c3' => '5', 'f1' => '3.333'], true); //replace $this->assertEquals(1, $affectedRow); //test int in where $select = new Select('foo'); $select->where(['id' => 1]); $results = $search->searchWith($select); foreach ($results as $result) { $this->assertEquals(1, $result['id']); $this->assertEquals(10, $result['c1']); $this->assertEquals(1, $result['c2']); $this->assertEquals(5, $result['c3']); $this->assertEquals(3.333, $result['f1']); break; } //test float in where $select = new Select('foo'); $select->where(['f1' => 3.333]); $results = $search->searchWith($select); foreach ($results as $result) { $this->assertEquals(1, $result['id']); $this->assertEquals(10, $result['c1']); $this->assertEquals(1, $result['c2']); $this->assertEquals(5, $result['c3']); $this->assertEquals(3.333, $result['f1']); break; } }
/** * Prepare statement * * @param \Zend\Db\Adapter\Adapter $adapter * @param \Zend\Db\Adapter\Driver\StatementInterface $statement * @return void */ public function prepareStatement(Adapter $adapter, StatementInterface $statement) { $driver = $adapter->getDriver(); $platform = $adapter->getPlatform(); $parameterContainer = $statement->getParameterContainer(); $prepareType = $driver->getPrepareType(); $parts = parent::getWhereParts(); $wherePart = ''; $whereParamIndex = 1; foreach ($parts as $part) { if (is_string($part)) { $wherePart .= $part; } elseif (is_array($part)) { $values = $part[1]; $types = isset($part[2]) ? $part[2] : array(); foreach ($values as $vIndex => $value) { if (isset($types[$vIndex]) && $types[$vIndex] == self::TYPE_IDENTIFIER) { $values[$vIndex] = $platform->quoteIdentifierInFragment($value); } elseif (isset($types[$vIndex]) && $types[$vIndex] == self::TYPE_VALUE) { if ($prepareType == 'positional') { $parameterContainer->offsetSet(null, $value); $values[$vIndex] = $driver->formatParameterName(null); } elseif ($prepareType == 'named') { $name = 'where' . $whereParamIndex++; $values[$vIndex] = $driver->formatParameterName($name); $parameterContainer->offsetSet($name, $value); } } } $wherePart .= vsprintf($part[0], $values); } } $sql = $statement->getSql(); $sql .= sprintf($this->specification, $wherePart); $statement->setSql($sql); }
/** * Prepare statement * * @param Adapter $adapter * @param StatementContainerInterface $statementContainer * @return void */ public function prepareStatement(Adapter $adapter, StatementContainerInterface $statementContainer) { $driver = $adapter->getDriver(); $platform = $adapter->getPlatform(); $parameterContainer = $statementContainer->getParameterContainer(); if (!$parameterContainer instanceof ParameterContainer) { $parameterContainer = new ParameterContainer(); $statementContainer->setParameterContainer($parameterContainer); } $table = $platform->quoteIdentifier($this->table); $columns = array(); $values = array(); foreach ($this->columns as $cIndex => $column) { $columns[$cIndex] = $platform->quoteIdentifier($column); if ($this->values[$cIndex] instanceof Expression) { $exprData = $this->processExpression($this->values[$cIndex], $platform, $adapter); $values[$cIndex] = $exprData->getSql(); $parameterContainer->merge($exprData->getParameterContainer()); } else { $values[$cIndex] = $driver->formatParameterName($column); $parameterContainer->offsetSet($column, $this->values[$cIndex]); } } $sql = sprintf($this->specifications[self::SPECIFICATION_INSERT], $table, implode(', ', $columns), implode(', ', $values)); $statementContainer->setSql($sql); }
/** * @testdox unit test: Test getDriver() will return driver object * @covers Zend\Db\Adapter\Adapter::getDriver */ public function testGetDriver() { $this->assertSame($this->mockDriver, $this->adapter->getDriver()); }
/** * @return Adapter */ protected function getAdapter() { global $globalTestConfiguration; if (!isset($globalTestConfiguration) || !isset($globalTestConfiguration['zenddb']) || !isset($globalTestConfiguration['zenddb']['driver'])) { $this->markTestIncomplete('Invalid configuration found in test.config.php. Make sure "zenddb" is set and contains' . 'a valid config array for Zend\\Db\\Adapter\\Adapter'); } $this->adapter = $adapter = new Adapter($globalTestConfiguration['zenddb']); // attempt to connect $adapter->getDriver()->getConnection()->connect(); $this->assertTrue($adapter->getDriver()->getConnection()->isConnected(), 'DB connection established.'); $meta = new Metadata($adapter); $sql = new Sql($adapter); static::$schemaCleanup = true; // drop previous tables if needed if (in_array('model', $meta->getTableNames())) { $ddl = new Ddl\DropTable('model'); $adapter->query($sql->getSqlStringForSqlObject($ddl))->execute(); } if (in_array('minimalmodel', $meta->getTableNames())) { $ddl = new Ddl\DropTable('minimalmodel'); $adapter->query($sql->getSqlStringForSqlObject($ddl))->execute(); } // create test tables $ddl = new Ddl\CreateTable('model'); $ddl->addColumn(new Ddl\Column\Integer('id', true, null, ['auto_increment' => true])); $ddl->addColumn((new Ddl\Column\Varchar('magicProperty', 255))->setNullable(true)); $ddl->addColumn((new Ddl\Column\Varchar('protectedProperty', 255))->setNullable(true)); $ddl->addConstraint(new Ddl\Constraint\PrimaryKey('id')); $adapter->query($sql->getSqlStringForSqlObject($ddl), $adapter::QUERY_MODE_EXECUTE); $ddl = new Ddl\CreateTable('minimalmodel'); $ddl->addColumn(new Ddl\Column\Integer('id', true, null, ['auto_increment' => true])); $ddl->addColumn((new Ddl\Column\Varchar('name', 255))->setNullable(true)); $ddl->addColumn((new Ddl\Column\Varchar('value', 255))->setNullable(true)); $ddl->addConstraint(new Ddl\Constraint\PrimaryKey('id')); $adapter->query($sql->getSqlStringForSqlObject($ddl), $adapter::QUERY_MODE_EXECUTE); // return the adapter return $adapter; }