repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/ResultSet/Exception/RuntimeException.php | src/ResultSet/Exception/RuntimeException.php | <?php
namespace Laminas\Db\ResultSet\Exception;
use Laminas\Db\Exception;
class RuntimeException extends Exception\RuntimeException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/ResultSet/Exception/InvalidArgumentException.php | src/ResultSet/Exception/InvalidArgumentException.php | <?php
namespace Laminas\Db\ResultSet\Exception;
use Laminas\Db\Exception;
class InvalidArgumentException extends Exception\InvalidArgumentException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/AbstractTableGateway.php | src/TableGateway/AbstractTableGateway.php | <?php
namespace Laminas\Db\TableGateway;
use Closure;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\ResultSet\ResultSet;
use Laminas\Db\ResultSet\ResultSetInterface;
use Laminas\Db\Sql\Delete;
use Laminas\Db\Sql\Insert;
use Laminas\Db\Sql\Join;
use Laminas\Db\Sql\Select;
use Laminas\Db\Sql\Sql;
use Laminas\Db\Sql\TableIdentifier;
use Laminas\Db\Sql\Update;
use Laminas\Db\Sql\Where;
use Laminas\Db\TableGateway\Feature\EventFeatureEventsInterface;
use function array_shift;
use function array_values;
use function count;
use function end;
use function is_array;
use function is_object;
use function is_string;
use function reset;
use function sprintf;
use function strtolower;
/**
* @property AdapterInterface $adapter
* @property int $lastInsertValue
* @property string $table
*/
abstract class AbstractTableGateway implements TableGatewayInterface
{
/** @var bool */
protected $isInitialized = false;
/** @var AdapterInterface */
protected $adapter;
/** @var string|array|TableIdentifier */
protected $table;
/** @var array */
protected $columns = [];
/** @var Feature\FeatureSet */
protected $featureSet;
/** @var ResultSetInterface */
protected $resultSetPrototype;
/** @var Sql */
protected $sql;
/** @var int */
protected $lastInsertValue;
/**
* @return bool
*/
public function isInitialized()
{
return $this->isInitialized;
}
/**
* Initialize
*
* @throws Exception\RuntimeException
* @return null
*/
public function initialize()
{
if ($this->isInitialized) {
return;
}
if (! $this->featureSet instanceof Feature\FeatureSet) {
$this->featureSet = new Feature\FeatureSet();
}
$this->featureSet->setTableGateway($this);
$this->featureSet->apply(EventFeatureEventsInterface::EVENT_PRE_INITIALIZE, []);
if (! $this->adapter instanceof AdapterInterface) {
throw new Exception\RuntimeException('This table does not have an Adapter setup');
}
if (! is_string($this->table) && ! $this->table instanceof TableIdentifier && ! is_array($this->table)) {
throw new Exception\RuntimeException('This table object does not have a valid table set.');
}
if (! $this->resultSetPrototype instanceof ResultSetInterface) {
$this->resultSetPrototype = new ResultSet();
}
if (! $this->sql instanceof Sql) {
$this->sql = new Sql($this->adapter, $this->table);
}
$this->featureSet->apply(EventFeatureEventsInterface::EVENT_POST_INITIALIZE, []);
$this->isInitialized = true;
}
/**
* Get table name
*
* @return string
*/
public function getTable()
{
return $this->table;
}
/**
* Get adapter
*
* @return AdapterInterface
*/
public function getAdapter()
{
return $this->adapter;
}
/**
* @return array
*/
public function getColumns()
{
return $this->columns;
}
/**
* @return Feature\FeatureSet
*/
public function getFeatureSet()
{
return $this->featureSet;
}
/**
* Get select result prototype
*
* @return ResultSetInterface
*/
public function getResultSetPrototype()
{
return $this->resultSetPrototype;
}
/**
* @return Sql
*/
public function getSql()
{
return $this->sql;
}
/**
* Select
*
* @param Where|Closure|string|array $where
* @return ResultSetInterface
*/
public function select($where = null)
{
if (! $this->isInitialized) {
$this->initialize();
}
$select = $this->sql->select();
if ($where instanceof Closure) {
$where($select);
} elseif ($where !== null) {
$select->where($where);
}
return $this->selectWith($select);
}
/**
* @return ResultSetInterface
*/
public function selectWith(Select $select)
{
if (! $this->isInitialized) {
$this->initialize();
}
return $this->executeSelect($select);
}
/**
* @return ResultSetInterface
* @throws Exception\RuntimeException
*/
protected function executeSelect(Select $select)
{
$selectState = $select->getRawState();
if (
isset($selectState['table'])
&& $selectState['table'] !== $this->table
&& (is_array($selectState['table'])
&& end($selectState['table']) !== $this->table)
) {
throw new Exception\RuntimeException(
'The table name of the provided Select object must match that of the table'
);
}
if (
isset($selectState['columns'])
&& $selectState['columns'] === [Select::SQL_STAR]
&& $this->columns !== []
) {
$select->columns($this->columns);
}
// apply preSelect features
$this->featureSet->apply(EventFeatureEventsInterface::EVENT_PRE_SELECT, [$select]);
// prepare and execute
$statement = $this->sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
// build result set
$resultSet = clone $this->resultSetPrototype;
$resultSet->initialize($result);
// apply postSelect features
$this->featureSet->apply(EventFeatureEventsInterface::EVENT_POST_SELECT, [$statement, $result, $resultSet]);
return $resultSet;
}
/**
* Insert
*
* @param array $set
* @return int
*/
public function insert($set)
{
if (! $this->isInitialized) {
$this->initialize();
}
$insert = $this->sql->insert();
$insert->values($set);
return $this->executeInsert($insert);
}
/**
* @return int
*/
public function insertWith(Insert $insert)
{
if (! $this->isInitialized) {
$this->initialize();
}
return $this->executeInsert($insert);
}
/**
* @todo add $columns support
* @return int
* @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(EventFeatureEventsInterface::EVENT_PRE_INSERT, [$insert]);
// Most RDBMS solutions do not allow using table aliases in INSERTs
// See https://github.com/zendframework/zf2/issues/7311
$unaliasedTable = false;
if (is_array($insertState['table'])) {
$tableData = array_values($insertState['table']);
$unaliasedTable = array_shift($tableData);
$insert->into($unaliasedTable);
}
$statement = $this->sql->prepareStatementForSqlObject($insert);
$result = $statement->execute();
$this->lastInsertValue = $this->adapter->getDriver()->getConnection()->getLastGeneratedValue();
// apply postInsert features
$this->featureSet->apply(EventFeatureEventsInterface::EVENT_POST_INSERT, [$statement, $result]);
// Reset original table information in Insert instance, if necessary
if ($unaliasedTable) {
$insert->into($insertState['table']);
}
return $result->getAffectedRows();
}
/**
* Update
*
* @param array $set
* @param string|array|Closure $where
* @param null|array $joins
* @return int
*/
public function update($set, $where = null, ?array $joins = null)
{
if (! $this->isInitialized) {
$this->initialize();
}
$sql = $this->sql;
$update = $sql->update();
$update->set($set);
if ($where !== null) {
$update->where($where);
}
if ($joins) {
foreach ($joins as $join) {
$type = $join['type'] ?? Join::JOIN_INNER;
$update->join($join['name'], $join['on'], $type);
}
}
return $this->executeUpdate($update);
}
/**
* @return int
*/
public function updateWith(Update $update)
{
if (! $this->isInitialized) {
$this->initialize();
}
return $this->executeUpdate($update);
}
/**
* @todo add $columns support
* @return int
* @throws Exception\RuntimeException
*/
protected function executeUpdate(Update $update)
{
$updateState = $update->getRawState();
if ($updateState['table'] !== $this->table) {
throw new Exception\RuntimeException(
'The table name of the provided Update object must match that of the table'
);
}
// apply preUpdate features
$this->featureSet->apply(EventFeatureEventsInterface::EVENT_PRE_UPDATE, [$update]);
$unaliasedTable = false;
if (is_array($updateState['table'])) {
$tableData = array_values($updateState['table']);
$unaliasedTable = array_shift($tableData);
$update->table($unaliasedTable);
}
$statement = $this->sql->prepareStatementForSqlObject($update);
$result = $statement->execute();
// apply postUpdate features
$this->featureSet->apply(EventFeatureEventsInterface::EVENT_POST_UPDATE, [$statement, $result]);
// Reset original table information in Update instance, if necessary
if ($unaliasedTable) {
$update->table($updateState['table']);
}
return $result->getAffectedRows();
}
/**
* Delete
*
* @param Where|Closure|string|array $where
* @return int
*/
public function delete($where)
{
if (! $this->isInitialized) {
$this->initialize();
}
$delete = $this->sql->delete();
if ($where instanceof Closure) {
$where($delete);
} else {
$delete->where($where);
}
return $this->executeDelete($delete);
}
/**
* @return int
*/
public function deleteWith(Delete $delete)
{
$this->initialize();
return $this->executeDelete($delete);
}
/**
* @todo add $columns support
* @return int
* @throws Exception\RuntimeException
*/
protected function executeDelete(Delete $delete)
{
$deleteState = $delete->getRawState();
if ($deleteState['table'] !== $this->table) {
throw new Exception\RuntimeException(
'The table name of the provided Delete object must match that of the table'
);
}
// pre delete update
$this->featureSet->apply(EventFeatureEventsInterface::EVENT_PRE_DELETE, [$delete]);
$unaliasedTable = false;
if (is_array($deleteState['table'])) {
$tableData = array_values($deleteState['table']);
$unaliasedTable = array_shift($tableData);
$delete->from($unaliasedTable);
}
$statement = $this->sql->prepareStatementForSqlObject($delete);
$result = $statement->execute();
// apply postDelete features
$this->featureSet->apply(EventFeatureEventsInterface::EVENT_POST_DELETE, [$statement, $result]);
// Reset original table information in Delete instance, if necessary
if ($unaliasedTable) {
$delete->from($deleteState['table']);
}
return $result->getAffectedRows();
}
/**
* Get last insert value
*
* @return int
*/
public function getLastInsertValue()
{
return $this->lastInsertValue;
}
/**
* __get
*
* @param string $property
* @throws Exception\InvalidArgumentException
* @return mixed
*/
public function __get($property)
{
switch (strtolower($property)) {
case 'lastinsertvalue':
return $this->lastInsertValue;
case 'adapter':
return $this->adapter;
case 'table':
return $this->table;
}
if ($this->featureSet->canCallMagicGet($property)) {
return $this->featureSet->callMagicGet($property);
}
throw new Exception\InvalidArgumentException('Invalid magic property access in ' . self::class . '::__get()');
}
/**
* @param string $property
* @param mixed $value
* @return mixed
* @throws Exception\InvalidArgumentException
*/
public function __set($property, $value)
{
if ($this->featureSet->canCallMagicSet($property)) {
return $this->featureSet->callMagicSet($property, $value);
}
throw new Exception\InvalidArgumentException('Invalid magic property access in ' . self::class . '::__set()');
}
/**
* @param string $method
* @param array $arguments
* @return mixed
* @throws Exception\InvalidArgumentException
*/
public function __call($method, $arguments)
{
if ($this->featureSet->canCallMagicCall($method)) {
return $this->featureSet->callMagicCall($method, $arguments);
}
throw new Exception\InvalidArgumentException(sprintf(
'Invalid method (%s) called, caught by %s::__call()',
$method,
self::class
));
}
/**
* __clone
*/
public function __clone()
{
$this->resultSetPrototype = isset($this->resultSetPrototype) ? clone $this->resultSetPrototype : null;
$this->sql = clone $this->sql;
if (is_object($this->table)) {
$this->table = clone $this->table;
} elseif (
is_array($this->table)
&& count($this->table) === 1
&& is_object(reset($this->table))
) {
foreach ($this->table as $alias => &$tableObject) {
$tableObject = clone $tableObject;
}
}
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/TableGateway.php | src/TableGateway/TableGateway.php | <?php
namespace Laminas\Db\TableGateway;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\ResultSet\ResultSet;
use Laminas\Db\ResultSet\ResultSetInterface;
use Laminas\Db\Sql\Sql;
use Laminas\Db\Sql\TableIdentifier;
use function is_array;
use function is_string;
class TableGateway extends AbstractTableGateway
{
/**
* Constructor
*
* @param string|TableIdentifier|array $table
* @param Feature\AbstractFeature|Feature\FeatureSet|Feature\AbstractFeature[]|null $features
* @throws Exception\InvalidArgumentException
*/
public function __construct(
$table,
AdapterInterface $adapter,
$features = null,
?ResultSetInterface $resultSetPrototype = null,
?Sql $sql = null
) {
// table
if (! (is_string($table) || $table instanceof TableIdentifier || is_array($table))) {
throw new Exception\InvalidArgumentException(
'Table name must be a string or an instance of Laminas\Db\Sql\TableIdentifier'
);
}
$this->table = $table;
// adapter
$this->adapter = $adapter;
// process features
if ($features !== null) {
if ($features instanceof Feature\AbstractFeature) {
$features = [$features];
}
if (is_array($features)) {
$this->featureSet = new Feature\FeatureSet($features);
} elseif ($features instanceof Feature\FeatureSet) {
$this->featureSet = $features;
} else {
throw new Exception\InvalidArgumentException(
'TableGateway expects $feature to be an instance of an AbstractFeature or a FeatureSet, or an '
. 'array of AbstractFeatures'
);
}
} else {
$this->featureSet = new Feature\FeatureSet();
}
// result prototype
$this->resultSetPrototype = $resultSetPrototype ?: new ResultSet();
// Sql object (factory for select, insert, update, delete)
$this->sql = $sql ?: new Sql($this->adapter, $this->table);
// check sql object bound to same table
if ($this->sql->getTable() !== $this->table) {
throw new Exception\InvalidArgumentException(
'The table inside the provided Sql object must match the table of this TableGateway'
);
}
$this->initialize();
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/TableGatewayInterface.php | src/TableGateway/TableGatewayInterface.php | <?php
namespace Laminas\Db\TableGateway;
use Closure;
use Laminas\Db\ResultSet\ResultSetInterface;
use Laminas\Db\Sql\Where;
interface TableGatewayInterface
{
/** @return string */
public function getTable();
/**
* @param Where|Closure|string|array $where
* @return ResultSetInterface
*/
public function select($where = null);
/**
* @param array<string, mixed> $set
* @return int
*/
public function insert($set);
/**
* @param array<string, mixed> $set
* @param Where|Closure|string|array $where
* @return int
*/
public function update($set, $where = null);
/**
* @param Where|Closure|string|array $where
* @return int
*/
public function delete($where);
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Feature/EventFeatureEventsInterface.php | src/TableGateway/Feature/EventFeatureEventsInterface.php | <?php
namespace Laminas\Db\TableGateway\Feature;
/**
* EventFeature event constants.
*
* This moves the constants introduced in {@link https://github.com/zendframework/zf2/pull/7066}
* into a separate interface that EventFeature implements; the change keeps
* backwards compatibility, while simultaneously removing the need to add
* another hard dependency to the component.
*/
interface EventFeatureEventsInterface
{
public const EVENT_PRE_INITIALIZE = 'preInitialize';
public const EVENT_POST_INITIALIZE = 'postInitialize';
public const EVENT_PRE_SELECT = 'preSelect';
public const EVENT_POST_SELECT = 'postSelect';
public const EVENT_PRE_INSERT = 'preInsert';
public const EVENT_POST_INSERT = 'postInsert';
public const EVENT_PRE_DELETE = 'preDelete';
public const EVENT_POST_DELETE = 'postDelete';
public const EVENT_PRE_UPDATE = 'preUpdate';
public const EVENT_POST_UPDATE = 'postUpdate';
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Feature/EventFeature.php | src/TableGateway/Feature/EventFeature.php | <?php
namespace Laminas\Db\TableGateway\Feature;
use Laminas\Db\Adapter\Driver\ResultInterface;
use Laminas\Db\Adapter\Driver\StatementInterface;
use Laminas\Db\ResultSet\ResultSetInterface;
use Laminas\Db\Sql\Delete;
use Laminas\Db\Sql\Insert;
use Laminas\Db\Sql\Select;
use Laminas\Db\Sql\Update;
use Laminas\Db\TableGateway\TableGateway;
use Laminas\EventManager\EventManager;
use Laminas\EventManager\EventManagerInterface;
use Laminas\EventManager\EventsCapableInterface;
use function get_class;
class EventFeature extends AbstractFeature implements
EventFeatureEventsInterface,
EventsCapableInterface
{
/** @var EventManagerInterface */
protected $eventManager;
/** @var ?EventFeature\TableGatewayEvent */
protected $event;
public function __construct(
?EventManagerInterface $eventManager = null,
?EventFeature\TableGatewayEvent $tableGatewayEvent = null
) {
$this->eventManager = $eventManager instanceof EventManagerInterface
? $eventManager
: new EventManager();
$this->eventManager->addIdentifiers([
TableGateway::class,
]);
$this->event = $tableGatewayEvent ?: new EventFeature\TableGatewayEvent();
}
/**
* Retrieve composed event manager instance
*
* @return EventManagerInterface
*/
public function getEventManager()
{
return $this->eventManager;
}
/**
* Retrieve composed event instance
*
* @return EventFeature\TableGatewayEvent
*/
public function getEvent()
{
return $this->event;
}
/**
* Initialize feature and trigger "preInitialize" event
*
* Ensures that the composed TableGateway has identifiers based on the
* class name, and that the event target is set to the TableGateway
* instance. It then triggers the "preInitialize" event.
*
* @return void
*/
public function preInitialize()
{
if (get_class($this->tableGateway) !== TableGateway::class) {
$this->eventManager->addIdentifiers([get_class($this->tableGateway)]);
}
$this->event->setTarget($this->tableGateway);
$this->event->setName(static::EVENT_PRE_INITIALIZE);
$this->eventManager->triggerEvent($this->event);
}
/**
* Trigger the "postInitialize" event
*
* @return void
*/
public function postInitialize()
{
$this->event->setName(static::EVENT_POST_INITIALIZE);
$this->eventManager->triggerEvent($this->event);
}
/**
* Trigger the "preSelect" event
*
* Triggers the "preSelect" event mapping the following parameters:
* - $select as "select"
*
* @return void
*/
public function preSelect(Select $select)
{
$this->event->setName(static::EVENT_PRE_SELECT);
$this->event->setParams(['select' => $select]);
$this->eventManager->triggerEvent($this->event);
}
/**
* Trigger the "postSelect" event
*
* Triggers the "postSelect" event mapping the following parameters:
* - $statement as "statement"
* - $result as "result"
* - $resultSet as "result_set"
*
* @return void
*/
public function postSelect(StatementInterface $statement, ResultInterface $result, ResultSetInterface $resultSet)
{
$this->event->setName(static::EVENT_POST_SELECT);
$this->event->setParams([
'statement' => $statement,
'result' => $result,
'result_set' => $resultSet,
]);
$this->eventManager->triggerEvent($this->event);
}
/**
* Trigger the "preInsert" event
*
* Triggers the "preInsert" event mapping the following parameters:
* - $insert as "insert"
*
* @return void
*/
public function preInsert(Insert $insert)
{
$this->event->setName(static::EVENT_PRE_INSERT);
$this->event->setParams(['insert' => $insert]);
$this->eventManager->triggerEvent($this->event);
}
/**
* Trigger the "postInsert" event
*
* Triggers the "postInsert" event mapping the following parameters:
* - $statement as "statement"
* - $result as "result"
*
* @return void
*/
public function postInsert(StatementInterface $statement, ResultInterface $result)
{
$this->event->setName(static::EVENT_POST_INSERT);
$this->event->setParams([
'statement' => $statement,
'result' => $result,
]);
$this->eventManager->triggerEvent($this->event);
}
/**
* Trigger the "preUpdate" event
*
* Triggers the "preUpdate" event mapping the following parameters:
* - $update as "update"
*
* @return void
*/
public function preUpdate(Update $update)
{
$this->event->setName(static::EVENT_PRE_UPDATE);
$this->event->setParams(['update' => $update]);
$this->eventManager->triggerEvent($this->event);
}
/**
* Trigger the "postUpdate" event
*
* Triggers the "postUpdate" event mapping the following parameters:
* - $statement as "statement"
* - $result as "result"
*
* @return void
*/
public function postUpdate(StatementInterface $statement, ResultInterface $result)
{
$this->event->setName(static::EVENT_POST_UPDATE);
$this->event->setParams([
'statement' => $statement,
'result' => $result,
]);
$this->eventManager->triggerEvent($this->event);
}
/**
* Trigger the "preDelete" event
*
* Triggers the "preDelete" event mapping the following parameters:
* - $delete as "delete"
*
* @return void
*/
public function preDelete(Delete $delete)
{
$this->event->setName(static::EVENT_PRE_DELETE);
$this->event->setParams(['delete' => $delete]);
$this->eventManager->triggerEvent($this->event);
}
/**
* Trigger the "postDelete" event
*
* Triggers the "postDelete" event mapping the following parameters:
* - $statement as "statement"
* - $result as "result"
*
* @return void
*/
public function postDelete(StatementInterface $statement, ResultInterface $result)
{
$this->event->setName(static::EVENT_POST_DELETE);
$this->event->setParams([
'statement' => $statement,
'result' => $result,
]);
$this->eventManager->triggerEvent($this->event);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Feature/GlobalAdapterFeature.php | src/TableGateway/Feature/GlobalAdapterFeature.php | <?php
namespace Laminas\Db\TableGateway\Feature;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\TableGateway\Exception;
class GlobalAdapterFeature extends AbstractFeature
{
/** @var Adapter[] */
protected static $staticAdapters = [];
/**
* Set static adapter
*/
public static function setStaticAdapter(Adapter $adapter)
{
$class = static::class;
static::$staticAdapters[$class] = $adapter;
if ($class === self::class) {
static::$staticAdapters[self::class] = $adapter;
}
}
/**
* Get static adapter
*
* @throws Exception\RuntimeException
* @return Adapter
*/
public static function getStaticAdapter()
{
$class = static::class;
// class specific adapter
if (isset(static::$staticAdapters[$class])) {
return static::$staticAdapters[$class];
}
// default adapter
if (isset(static::$staticAdapters[self::class])) {
return static::$staticAdapters[self::class];
}
throw new Exception\RuntimeException('No database adapter was found in the static registry.');
}
/**
* after initialization, retrieve the original adapter as "master"
*/
public function preInitialize()
{
$this->tableGateway->adapter = self::getStaticAdapter();
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Feature/AbstractFeature.php | src/TableGateway/Feature/AbstractFeature.php | <?php
namespace Laminas\Db\TableGateway\Feature;
use Laminas\Db\TableGateway\AbstractTableGateway;
use Laminas\Db\TableGateway\Exception;
abstract class AbstractFeature extends AbstractTableGateway
{
/** @var AbstractTableGateway */
protected $tableGateway;
/** @var array */
protected $sharedData = [];
/** @return string */
public function getName()
{
return static::class;
}
public function setTableGateway(AbstractTableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function initialize()
{
throw new Exception\RuntimeException('This method is not intended to be called on this object.');
}
/** @return string[] */
public function getMagicMethodSpecifications()
{
return [];
}
/*
public function preInitialize();
public function postInitialize();
public function preSelect(Select $select);
public function postSelect(StatementInterface $statement, ResultInterface $result, ResultSetInterface $resultSet);
public function preInsert(Insert $insert);
public function postInsert(StatementInterface $statement, ResultInterface $result);
public function preUpdate(Update $update);
public function postUpdate(StatementInterface $statement, ResultInterface $result);
public function preDelete(Delete $delete);
public function postDelete(StatementInterface $statement, ResultInterface $result);
*/
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Feature/RowGatewayFeature.php | src/TableGateway/Feature/RowGatewayFeature.php | <?php
namespace Laminas\Db\TableGateway\Feature;
use Laminas\Db\ResultSet\ResultSet;
use Laminas\Db\RowGateway\RowGateway;
use Laminas\Db\RowGateway\RowGatewayInterface;
use Laminas\Db\TableGateway\Exception;
use Laminas\Db\TableGateway\Feature\MetadataFeature;
use function func_get_args;
use function is_string;
class RowGatewayFeature extends AbstractFeature
{
/** @var array */
protected $constructorArguments = [];
public function __construct()
{
$this->constructorArguments = func_get_args();
}
public function postInitialize()
{
$args = $this->constructorArguments;
/** @var ResultSet $resultSetPrototype */
$resultSetPrototype = $this->tableGateway->resultSetPrototype;
if (! $this->tableGateway->resultSetPrototype instanceof ResultSet) {
throw new Exception\RuntimeException(
'This feature ' . self::class . ' expects the ResultSet to be an instance of ' . ResultSet::class
);
}
if (isset($args[0])) {
if (is_string($args[0])) {
$primaryKey = $args[0];
$rowGatewayPrototype = new RowGateway(
$primaryKey,
$this->tableGateway->table,
$this->tableGateway->adapter
);
$resultSetPrototype->setArrayObjectPrototype($rowGatewayPrototype);
} elseif ($args[0] instanceof RowGatewayInterface) {
$rowGatewayPrototype = $args[0];
$resultSetPrototype->setArrayObjectPrototype($rowGatewayPrototype);
}
} else {
// get from metadata feature
$metadata = $this->tableGateway->featureSet->getFeatureByClassName(
MetadataFeature::class
);
if ($metadata === false || ! isset($metadata->sharedData['metadata'])) {
throw new Exception\RuntimeException(
'No information was provided to the RowGatewayFeature and/or no MetadataFeature could be consulted '
. 'to find the primary key necessary for RowGateway object creation.'
);
}
$primaryKey = $metadata->sharedData['metadata']['primaryKey'];
$rowGatewayPrototype = new RowGateway(
$primaryKey,
$this->tableGateway->table,
$this->tableGateway->adapter
);
$resultSetPrototype->setArrayObjectPrototype($rowGatewayPrototype);
}
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Feature/SequenceFeature.php | src/TableGateway/Feature/SequenceFeature.php | <?php
namespace Laminas\Db\TableGateway\Feature;
use Laminas\Db\Adapter\Driver\ResultInterface;
use Laminas\Db\Adapter\Driver\StatementInterface;
use Laminas\Db\Sql\Insert;
use function array_search;
class SequenceFeature extends AbstractFeature
{
/** @var string */
protected $primaryKeyField;
/** @var string */
protected $sequenceName;
/** @var int */
protected $sequenceValue;
/**
* @param string $primaryKeyField
* @param string $sequenceName
*/
public function __construct($primaryKeyField, $sequenceName)
{
$this->primaryKeyField = $primaryKeyField;
$this->sequenceName = $sequenceName;
}
/**
* @return Insert
*/
public function preInsert(Insert $insert)
{
$columns = $insert->getRawState('columns');
$values = $insert->getRawState('values');
$key = array_search($this->primaryKeyField, $columns);
if ($key !== false) {
$this->sequenceValue = $values[$key] ?? null;
return $insert;
}
$this->sequenceValue = $this->nextSequenceId();
if ($this->sequenceValue === null) {
return $insert;
}
$insert->values([$this->primaryKeyField => $this->sequenceValue], Insert::VALUES_MERGE);
return $insert;
}
public function postInsert(StatementInterface $statement, ResultInterface $result)
{
if ($this->sequenceValue !== null) {
$this->tableGateway->lastInsertValue = $this->sequenceValue;
}
}
/**
* Generate a new value from the specified sequence in the database, and return it.
*
* @return int
*/
public function nextSequenceId()
{
$platform = $this->tableGateway->adapter->getPlatform();
$platformName = $platform->getName();
switch ($platformName) {
case 'Oracle':
$sql = 'SELECT ' . $platform->quoteIdentifier($this->sequenceName) . '.NEXTVAL as "nextval" FROM dual';
break;
case 'PostgreSQL':
$sql = 'SELECT NEXTVAL(\'"' . $this->sequenceName . '"\')';
break;
default:
return;
}
$statement = $this->tableGateway->adapter->createStatement();
$statement->prepare($sql);
$result = $statement->execute();
$sequence = $result->current();
unset($statement, $result);
return $sequence['nextval'];
}
/**
* Return the most recent value from the specified sequence in the database.
*
* @return int
*/
public function lastSequenceId()
{
$platform = $this->tableGateway->adapter->getPlatform();
$platformName = $platform->getName();
switch ($platformName) {
case 'Oracle':
$sql = 'SELECT ' . $platform->quoteIdentifier($this->sequenceName) . '.CURRVAL as "currval" FROM dual';
break;
case 'PostgreSQL':
$sql = 'SELECT CURRVAL(\'' . $this->sequenceName . '\')';
break;
default:
return;
}
$statement = $this->tableGateway->adapter->createStatement();
$statement->prepare($sql);
$result = $statement->execute();
$sequence = $result->current();
unset($statement, $result);
return $sequence['currval'];
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Feature/FeatureSet.php | src/TableGateway/Feature/FeatureSet.php | <?php
namespace Laminas\Db\TableGateway\Feature;
use Laminas\Db\TableGateway\AbstractTableGateway;
use Laminas\Db\TableGateway\TableGatewayInterface;
use function call_user_func_array;
use function method_exists;
class FeatureSet
{
public const APPLY_HALT = 'halt';
/** @var null|AbstractTableGateway */
protected $tableGateway;
/** @var AbstractFeature[] */
protected $features = [];
/** @var array */
protected $magicSpecifications = [];
public function __construct(array $features = [])
{
if ($features) {
$this->addFeatures($features);
}
}
/**
* @return $this Provides a fluent interface
*/
public function setTableGateway(AbstractTableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
foreach ($this->features as $feature) {
$feature->setTableGateway($this->tableGateway);
}
return $this;
}
/**
* @param string $featureClassName
* @return null|AbstractFeature
*/
public function getFeatureByClassName($featureClassName)
{
$feature = null;
foreach ($this->features as $potentialFeature) {
if ($potentialFeature instanceof $featureClassName) {
$feature = $potentialFeature;
break;
}
}
return $feature;
}
/**
* @param array $features
* @return $this Provides a fluent interface
*/
public function addFeatures(array $features)
{
foreach ($features as $feature) {
$this->addFeature($feature);
}
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function addFeature(AbstractFeature $feature)
{
if ($this->tableGateway instanceof TableGatewayInterface) {
$feature->setTableGateway($this->tableGateway);
}
$this->features[] = $feature;
return $this;
}
/**
* @param string $method
* @param array $args
* @return void
*/
public function apply($method, $args)
{
foreach ($this->features as $feature) {
if (method_exists($feature, $method)) {
$return = call_user_func_array([$feature, $method], $args);
if ($return === self::APPLY_HALT) {
break;
}
}
}
}
/**
* @param string $property
* @return bool
*/
public function canCallMagicGet($property)
{
return false;
}
/**
* @param string $property
* @return mixed
*/
public function callMagicGet($property)
{
return null;
}
/**
* @param string $property
* @return bool
*/
public function canCallMagicSet($property)
{
return false;
}
/**
* @param string $property
* @param mixed $value
* @return mixed
*/
public function callMagicSet($property, $value)
{
return null;
}
/**
* Is the method requested available in one of the added features
*
* @param string $method
* @return bool
*/
public function canCallMagicCall($method)
{
if (! empty($this->features)) {
foreach ($this->features as $feature) {
if (method_exists($feature, $method)) {
return true;
}
}
}
return false;
}
/**
* Call method of on added feature as though it were a local method
*
* @param string $method
* @param array $arguments
* @return mixed
*/
public function callMagicCall($method, $arguments)
{
foreach ($this->features as $feature) {
if (method_exists($feature, $method)) {
return $feature->$method($arguments);
}
}
return null;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Feature/MasterSlaveFeature.php | src/TableGateway/Feature/MasterSlaveFeature.php | <?php
namespace Laminas\Db\TableGateway\Feature;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\Sql\Sql;
class MasterSlaveFeature extends AbstractFeature
{
/** @var AdapterInterface */
protected $slaveAdapter;
/** @var Sql */
protected $masterSql;
/** @var Sql */
protected $slaveSql;
/**
* Constructor
*/
public function __construct(AdapterInterface $slaveAdapter, ?Sql $slaveSql = null)
{
$this->slaveAdapter = $slaveAdapter;
if ($slaveSql) {
$this->slaveSql = $slaveSql;
}
}
/** @return AdapterInterface */
public function getSlaveAdapter()
{
return $this->slaveAdapter;
}
/**
* @return Sql
*/
public function getSlaveSql()
{
return $this->slaveSql;
}
/**
* after initialization, retrieve the original adapter as "master"
*/
public function postInitialize()
{
$this->masterSql = $this->tableGateway->sql;
if ($this->slaveSql === null) {
$this->slaveSql = new Sql(
$this->slaveAdapter,
$this->tableGateway->sql->getTable(),
$this->tableGateway->sql->getSqlPlatform()
);
}
}
/**
* preSelect()
* Replace adapter with slave temporarily
*/
public function preSelect()
{
$this->tableGateway->sql = $this->slaveSql;
}
/**
* postSelect()
* Ensure to return to the master adapter
*/
public function postSelect()
{
$this->tableGateway->sql = $this->masterSql;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Feature/MetadataFeature.php | src/TableGateway/Feature/MetadataFeature.php | <?php
namespace Laminas\Db\TableGateway\Feature;
use Laminas\Db\Metadata\MetadataInterface;
use Laminas\Db\Metadata\Object\ConstraintObject;
use Laminas\Db\Metadata\Object\TableObject;
use Laminas\Db\Metadata\Source\Factory as SourceFactory;
use Laminas\Db\Sql\TableIdentifier;
use Laminas\Db\TableGateway\Exception;
use function count;
use function current;
use function is_array;
class MetadataFeature extends AbstractFeature
{
/** @var MetadataInterface */
protected $metadata;
/**
* Constructor
*/
public function __construct(?MetadataInterface $metadata = null)
{
if ($metadata) {
$this->metadata = $metadata;
}
$this->sharedData['metadata'] = [
'primaryKey' => null,
'columns' => [],
];
}
public function postInitialize()
{
if ($this->metadata === null) {
$this->metadata = SourceFactory::createSourceFromAdapter($this->tableGateway->adapter);
}
// localize variable for brevity
$t = $this->tableGateway;
$m = $this->metadata;
$tableGatewayTable = is_array($t->table) ? current($t->table) : $t->table;
if ($tableGatewayTable instanceof TableIdentifier) {
$table = $tableGatewayTable->getTable();
$schema = $tableGatewayTable->getSchema();
} else {
$table = $tableGatewayTable;
$schema = null;
}
// get column named
$columns = $m->getColumnNames($table, $schema);
$t->columns = $columns;
// set locally
$this->sharedData['metadata']['columns'] = $columns;
// process primary key only if table is a table; there are no PK constraints on views
if (! $m->getTable($table, $schema) instanceof TableObject) {
return;
}
$pkc = null;
foreach ($m->getConstraints($table, $schema) as $constraint) {
/** @var ConstraintObject $constraint */
if ($constraint->getType() === 'PRIMARY KEY') {
$pkc = $constraint;
break;
}
}
if ($pkc === null) {
throw new Exception\RuntimeException('A primary key for this column could not be found in the metadata.');
}
$pkcColumns = $pkc->getColumns();
if (count($pkcColumns) === 1) {
$primaryKey = $pkcColumns[0];
} else {
$primaryKey = $pkcColumns;
}
$this->sharedData['metadata']['primaryKey'] = $primaryKey;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Feature/EventFeature/TableGatewayEvent.php | src/TableGateway/Feature/EventFeature/TableGatewayEvent.php | <?php
namespace Laminas\Db\TableGateway\Feature\EventFeature;
use ArrayAccess;
use Laminas\Db\TableGateway\AbstractTableGateway;
use Laminas\EventManager\EventInterface;
class TableGatewayEvent implements EventInterface
{
/** @var AbstractTableGateway */
protected $target;
/** @var null */
protected $name;
/** @var array|ArrayAccess */
protected $params = [];
/**
* Get event name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get target/context from which event was triggered
*
* @return null|string|object
*/
public function getTarget()
{
return $this->target;
}
/**
* Get parameters passed to the event
*
* @return array|ArrayAccess
*/
public function getParams()
{
return $this->params;
}
/**
* Get a single parameter by name
*
* @param string $name
* @param mixed $default Default value to return if parameter does not exist
* @return mixed
*/
public function getParam($name, $default = null)
{
return $this->params[$name] ?? $default;
}
/**
* Set the event name
*
* @param string $name
* @return void
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Set the event target/context
*
* @param null|string|object $target
* @return void
*/
public function setTarget($target)
{
$this->target = $target;
}
/**
* Set event parameters
*
* @param string $params
* @return void
*/
public function setParams($params)
{
$this->params = $params;
}
/**
* Set a single parameter by key
*
* @param string $name
* @param mixed $value
* @return void
*/
public function setParam($name, $value)
{
$this->params[$name] = $value;
}
/**
* Indicate whether or not the parent EventManagerInterface should stop propagating events
*
* @param bool $flag
* @return void
*/
public function stopPropagation($flag = true)
{
}
/**
* Has this event indicated event propagation should stop?
*
* @return bool
*/
public function propagationIsStopped()
{
return false;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Exception/ExceptionInterface.php | src/TableGateway/Exception/ExceptionInterface.php | <?php
namespace Laminas\Db\TableGateway\Exception;
use Laminas\Db\Exception;
interface ExceptionInterface extends Exception\ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Exception/RuntimeException.php | src/TableGateway/Exception/RuntimeException.php | <?php
namespace Laminas\Db\TableGateway\Exception;
use Laminas\Db\Exception;
class RuntimeException extends Exception\InvalidArgumentException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/TableGateway/Exception/InvalidArgumentException.php | src/TableGateway/Exception/InvalidArgumentException.php | <?php
namespace Laminas\Db\TableGateway\Exception;
use Laminas\Db\Exception;
class InvalidArgumentException extends Exception\InvalidArgumentException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/RowGateway/RowGatewayInterface.php | src/RowGateway/RowGatewayInterface.php | <?php
namespace Laminas\Db\RowGateway;
interface RowGatewayInterface
{
public function save();
public function delete();
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/RowGateway/AbstractRowGateway.php | src/RowGateway/AbstractRowGateway.php | <?php
namespace Laminas\Db\RowGateway;
use ArrayAccess;
use Countable;
use Laminas\Db\Sql\Sql;
use Laminas\Db\Sql\TableIdentifier;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use ReturnTypeWillChange;
use function array_key_exists;
use function count;
use function is_string;
abstract class AbstractRowGateway implements ArrayAccess, Countable, RowGatewayInterface
{
/** @var bool */
protected $isInitialized = false;
/** @var string|TableIdentifier */
protected $table;
/** @var array */
protected $primaryKeyColumn;
/** @var array */
protected $primaryKeyData;
/** @var array */
protected $data = [];
/** @var Sql */
protected $sql;
/** @var Feature\FeatureSet */
protected $featureSet;
/**
* initialize()
*/
public function initialize()
{
if ($this->isInitialized) {
return;
}
if (! $this->featureSet instanceof Feature\FeatureSet) {
$this->featureSet = new Feature\FeatureSet();
}
$this->featureSet->setRowGateway($this);
$this->featureSet->apply('preInitialize', []);
if (! is_string($this->table) && ! $this->table instanceof TableIdentifier) {
throw new Exception\RuntimeException('This row object does not have a valid table set.');
}
if ($this->primaryKeyColumn === null) {
throw new Exception\RuntimeException('This row object does not have a primary key column set.');
} elseif (is_string($this->primaryKeyColumn)) {
$this->primaryKeyColumn = (array) $this->primaryKeyColumn;
}
if (! $this->sql instanceof Sql) {
throw new Exception\RuntimeException('This row object does not have a Sql object set.');
}
$this->featureSet->apply('postInitialize', []);
$this->isInitialized = true;
}
/**
* Populate Data
*
* @param array $rowData
* @param bool $rowExistsInDatabase
* @return $this Provides a fluent interface
*/
public function populate(array $rowData, $rowExistsInDatabase = false)
{
$this->initialize();
$this->data = $rowData;
if ($rowExistsInDatabase === true) {
$this->processPrimaryKeyData();
return $this;
}
$this->primaryKeyData = null;
return $this;
}
/**
* @param mixed $array
* @return AbstractRowGateway
*/
public function exchangeArray($array)
{
return $this->populate($array, true);
}
/**
* Save
*
* @return int
*/
public function save()
{
$this->initialize();
if ($this->rowExistsInDatabase()) {
// UPDATE
$data = $this->data;
$where = [];
$isPkModified = false;
// primary key is always an array even if its a single column
foreach ($this->primaryKeyColumn as $pkColumn) {
$where[$pkColumn] = $this->primaryKeyData[$pkColumn];
// phpcs:ignore SlevomatCodingStandard.Operators.DisallowEqualOperators.DisallowedEqualOperator
if ($data[$pkColumn] == $this->primaryKeyData[$pkColumn]) {
unset($data[$pkColumn]);
} else {
$isPkModified = true;
}
}
$statement = $this->sql->prepareStatementForSqlObject($this->sql->update()->set($data)->where($where));
$result = $statement->execute();
$rowsAffected = $result->getAffectedRows();
unset($statement, $result); // cleanup
// If one or more primary keys are modified, we update the where clause
if ($isPkModified) {
foreach ($this->primaryKeyColumn as $pkColumn) {
// phpcs:ignore SlevomatCodingStandard.Operators.DisallowEqualOperators.DisallowedEqualOperator
if ($data[$pkColumn] !== $this->primaryKeyData[$pkColumn]) {
$where[$pkColumn] = $data[$pkColumn];
}
}
}
} else {
// INSERT
$insert = $this->sql->insert();
$insert->values($this->data);
$statement = $this->sql->prepareStatementForSqlObject($insert);
$result = $statement->execute();
if (($primaryKeyValue = $result->getGeneratedValue()) && count($this->primaryKeyColumn) === 1) {
$this->primaryKeyData = [$this->primaryKeyColumn[0] => $primaryKeyValue];
} else {
// make primary key data available so that $where can be complete
$this->processPrimaryKeyData();
}
$rowsAffected = $result->getAffectedRows();
unset($statement, $result); // cleanup
$where = [];
// primary key is always an array even if its a single column
foreach ($this->primaryKeyColumn as $pkColumn) {
$where[$pkColumn] = $this->primaryKeyData[$pkColumn];
}
}
// refresh data
$statement = $this->sql->prepareStatementForSqlObject($this->sql->select()->where($where));
$result = $statement->execute();
$rowData = $result->current();
unset($statement, $result); // cleanup
// make sure data and original data are in sync after save
$this->populate($rowData, true);
// return rows affected
return $rowsAffected;
}
/**
* Delete
*
* @return int
*/
public function delete()
{
$this->initialize();
$where = [];
// primary key is always an array even if its a single column
foreach ($this->primaryKeyColumn as $pkColumn) {
$where[$pkColumn] = $this->primaryKeyData[$pkColumn] ?? null;
}
// @todo determine if we need to do a select to ensure 1 row will be affected
$statement = $this->sql->prepareStatementForSqlObject($this->sql->delete()->where($where));
$result = $statement->execute();
$affectedRows = $result->getAffectedRows();
if ($affectedRows === 1) {
// detach from database
$this->primaryKeyData = null;
}
return $affectedRows;
}
/**
* Offset Exists
*
* @param string $offset
* @return bool
*/
#[ReturnTypeWillChange]
public function offsetExists($offset)
{
return array_key_exists($offset, $this->data);
}
/**
* Offset get
*
* @param string $offset
* @return mixed
*/
#[ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->data[$offset];
}
/**
* Offset set
*
* @param string $offset
* @param mixed $value
* @return $this Provides a fluent interface
*/
#[ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
$this->data[$offset] = $value;
return $this;
}
/**
* Offset unset
*
* @param string $offset
* @return $this Provides a fluent interface
*/
#[ReturnTypeWillChange]
public function offsetUnset($offset)
{
$this->data[$offset] = null;
return $this;
}
/**
* @return int
*/
#[ReturnTypeWillChange]
public function count()
{
return count($this->data);
}
/**
* To array
*
* @return array
*/
public function toArray()
{
return $this->data;
}
/**
* __get
*
* @param string $name
* @throws Exception\InvalidArgumentException
* @return mixed
*/
public function __get($name)
{
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
} else {
throw new Exception\InvalidArgumentException('Not a valid column in this row: ' . $name);
}
}
/**
* __set
*
* @param string $name
* @param mixed $value
* @return void
*/
public function __set($name, $value)
{
$this->offsetSet($name, $value);
}
/**
* __isset
*
* @param string $name
* @return bool
*/
public function __isset($name)
{
return $this->offsetExists($name);
}
/**
* __unset
*
* @param string $name
* @return void
*/
public function __unset($name)
{
$this->offsetUnset($name);
}
/**
* @return bool
*/
public function rowExistsInDatabase()
{
return $this->primaryKeyData !== null;
}
/**
* @throws Exception\RuntimeException
*/
protected function processPrimaryKeyData()
{
$this->primaryKeyData = [];
foreach ($this->primaryKeyColumn as $column) {
if (! isset($this->data[$column])) {
throw new Exception\RuntimeException(
'While processing primary key data, a known key ' . $column . ' was not found in the data array'
);
}
$this->primaryKeyData[$column] = $this->data[$column];
}
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/RowGateway/RowGateway.php | src/RowGateway/RowGateway.php | <?php
namespace Laminas\Db\RowGateway;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\Sql\Sql;
use Laminas\Db\Sql\TableIdentifier;
class RowGateway extends AbstractRowGateway
{
/**
* Constructor
*
* @param string $primaryKeyColumn
* @param string|TableIdentifier $table
* @param AdapterInterface|Sql $adapterOrSql
* @throws Exception\InvalidArgumentException
*/
public function __construct($primaryKeyColumn, $table, $adapterOrSql = null)
{
// setup primary key
$this->primaryKeyColumn = empty($primaryKeyColumn) ? null : (array) $primaryKeyColumn;
// set table
$this->table = $table;
// set Sql object
if ($adapterOrSql instanceof Sql) {
$this->sql = $adapterOrSql;
} elseif ($adapterOrSql instanceof AdapterInterface) {
$this->sql = new Sql($adapterOrSql, $this->table);
} else {
throw new Exception\InvalidArgumentException('A valid Sql object was not provided.');
}
if ($this->sql->getTable() !== $this->table) {
throw new Exception\InvalidArgumentException(
'The Sql object provided does not have a table that matches this row object'
);
}
$this->initialize();
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/RowGateway/Feature/AbstractFeature.php | src/RowGateway/Feature/AbstractFeature.php | <?php
namespace Laminas\Db\RowGateway\Feature;
use Laminas\Db\RowGateway\AbstractRowGateway;
use Laminas\Db\RowGateway\Exception;
use Laminas\Db\RowGateway\Exception\RuntimeException;
abstract class AbstractFeature extends AbstractRowGateway
{
/** @var AbstractRowGateway */
protected $rowGateway;
/** @var array */
protected $sharedData = [];
/**
* @return string
*/
public function getName()
{
return static::class;
}
public function setRowGateway(AbstractRowGateway $rowGateway)
{
$this->rowGateway = $rowGateway;
}
/**
* @throws RuntimeException
*/
public function initialize()
{
throw new Exception\RuntimeException('This method is not intended to be called on this object.');
}
/**
* @return array
*/
public function getMagicMethodSpecifications()
{
return [];
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/RowGateway/Feature/FeatureSet.php | src/RowGateway/Feature/FeatureSet.php | <?php
namespace Laminas\Db\RowGateway\Feature;
use Laminas\Db\RowGateway\AbstractRowGateway;
use function call_user_func_array;
use function method_exists;
class FeatureSet
{
public const APPLY_HALT = 'halt';
/** @var AbstractRowGateway */
protected $rowGateway;
/** @var AbstractFeature[] */
protected $features = [];
/** @var array */
protected $magicSpecifications = [];
/**
* @param array $features
*/
public function __construct(array $features = [])
{
if ($features) {
$this->addFeatures($features);
}
}
/**
* @return $this Provides a fluent interface
*/
public function setRowGateway(AbstractRowGateway $rowGateway)
{
$this->rowGateway = $rowGateway;
foreach ($this->features as $feature) {
$feature->setRowGateway($this->rowGateway);
}
return $this;
}
/**
* @param string $featureClassName
* @return AbstractFeature
*/
public function getFeatureByClassName($featureClassName)
{
$feature = false;
foreach ($this->features as $potentialFeature) {
if ($potentialFeature instanceof $featureClassName) {
$feature = $potentialFeature;
break;
}
}
return $feature;
}
/**
* @param array $features
* @return $this Provides a fluent interface
*/
public function addFeatures(array $features)
{
foreach ($features as $feature) {
$this->addFeature($feature);
}
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function addFeature(AbstractFeature $feature)
{
$this->features[] = $feature;
$feature->setRowGateway($feature);
return $this;
}
/**
* @param string $method
* @param array $args
* @return void
*/
public function apply($method, $args)
{
foreach ($this->features as $feature) {
if (method_exists($feature, $method)) {
$return = call_user_func_array([$feature, $method], $args);
if ($return === self::APPLY_HALT) {
break;
}
}
}
}
/**
* @param string $property
* @return bool
*/
public function canCallMagicGet($property)
{
return false;
}
/**
* @param string $property
* @return mixed
*/
public function callMagicGet($property)
{
return null;
}
/**
* @param string $property
* @return bool
*/
public function canCallMagicSet($property)
{
return false;
}
/**
* @param string $property
* @param mixed $value
* @return mixed
*/
public function callMagicSet($property, $value)
{
return null;
}
/**
* @param string $method
* @return bool
*/
public function canCallMagicCall($method)
{
return false;
}
/**
* @param string $method
* @param array $arguments
* @return mixed
*/
public function callMagicCall($method, $arguments)
{
return null;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/RowGateway/Exception/ExceptionInterface.php | src/RowGateway/Exception/ExceptionInterface.php | <?php
namespace Laminas\Db\RowGateway\Exception;
use Laminas\Db\Exception;
interface ExceptionInterface extends Exception\ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/RowGateway/Exception/RuntimeException.php | src/RowGateway/Exception/RuntimeException.php | <?php
namespace Laminas\Db\RowGateway\Exception;
use Laminas\Db\Exception;
class RuntimeException extends Exception\RuntimeException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/RowGateway/Exception/InvalidArgumentException.php | src/RowGateway/Exception/InvalidArgumentException.php | <?php
namespace Laminas\Db\RowGateway\Exception;
use Laminas\Db\Exception;
class InvalidArgumentException extends Exception\InvalidArgumentException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Exception/ExceptionInterface.php | src/Exception/ExceptionInterface.php | <?php
namespace Laminas\Db\Exception;
interface ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Exception/RuntimeException.php | src/Exception/RuntimeException.php | <?php
namespace Laminas\Db\Exception;
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Exception/UnexpectedValueException.php | src/Exception/UnexpectedValueException.php | <?php
namespace Laminas\Db\Exception;
class UnexpectedValueException extends \UnexpectedValueException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Exception/InvalidArgumentException.php | src/Exception/InvalidArgumentException.php | <?php
namespace Laminas\Db\Exception;
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Exception/ErrorException.php | src/Exception/ErrorException.php | <?php
namespace Laminas\Db\Exception;
use Exception;
class ErrorException extends Exception implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/StatementContainerInterface.php | src/Adapter/StatementContainerInterface.php | <?php
namespace Laminas\Db\Adapter;
interface StatementContainerInterface
{
/**
* Set sql
*
* @param null|string $sql
* @return static
*/
public function setSql($sql);
/**
* Get sql
*
* @return null|string
*/
public function getSql();
/**
* Set parameter container
*
* @return static
*/
public function setParameterContainer(ParameterContainer $parameterContainer);
/**
* Get parameter container
*
* @return null|ParameterContainer
*/
public function getParameterContainer();
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Adapter.php | src/Adapter/Adapter.php | <?php
namespace Laminas\Db\Adapter;
use InvalidArgumentException;
use Laminas\Db\ResultSet;
use function func_get_args;
use function in_array;
use function is_array;
use function is_bool;
use function is_string;
use function strpos;
use function strtolower;
/**
* @property Driver\DriverInterface $driver
* @property Platform\PlatformInterface $platform
*/
class Adapter implements AdapterInterface, Profiler\ProfilerAwareInterface
{
/**
* Query Mode Constants
*/
public const QUERY_MODE_EXECUTE = 'execute';
public const QUERY_MODE_PREPARE = 'prepare';
/**
* Prepare Type Constants
*/
public const PREPARE_TYPE_POSITIONAL = 'positional';
public const PREPARE_TYPE_NAMED = 'named';
public const FUNCTION_FORMAT_PARAMETER_NAME = 'formatParameterName';
public const FUNCTION_QUOTE_IDENTIFIER = 'quoteIdentifier';
public const FUNCTION_QUOTE_VALUE = 'quoteValue';
public const VALUE_QUOTE_SEPARATOR = 'quoteSeparator';
/** @var Driver\DriverInterface */
protected $driver;
/** @var Platform\PlatformInterface */
protected $platform;
/** @var Profiler\ProfilerInterface */
protected $profiler;
/** @var ResultSet\ResultSetInterface */
protected $queryResultSetPrototype;
/**
* @deprecated
*
* @var Driver\StatementInterface
*/
protected $lastPreparedStatement;
/**
* @param Driver\DriverInterface|array $driver
* @throws Exception\InvalidArgumentException
*/
public function __construct(
$driver,
?Platform\PlatformInterface $platform = null,
?ResultSet\ResultSetInterface $queryResultPrototype = null,
?Profiler\ProfilerInterface $profiler = null
) {
// first argument can be an array of parameters
$parameters = [];
if (is_array($driver)) {
$parameters = $driver;
if ($profiler === null && isset($parameters['profiler'])) {
$profiler = $this->createProfiler($parameters);
}
$driver = $this->createDriver($parameters);
} elseif (! $driver instanceof Driver\DriverInterface) {
throw new Exception\InvalidArgumentException(
'The supplied or instantiated driver object does not implement ' . Driver\DriverInterface::class
);
}
$driver->checkEnvironment();
$this->driver = $driver;
if ($platform === null) {
$platform = $this->createPlatform($parameters);
}
$this->platform = $platform;
$this->queryResultSetPrototype = $queryResultPrototype ?: new ResultSet\ResultSet();
if ($profiler) {
$this->setProfiler($profiler);
}
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
if ($this->driver instanceof Profiler\ProfilerAwareInterface) {
$this->driver->setProfiler($profiler);
}
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* getDriver()
*
* @throws Exception\RuntimeException
* @return Driver\DriverInterface
*/
public function getDriver()
{
if ($this->driver === null) {
throw new Exception\RuntimeException('Driver has not been set or configured for this adapter.');
}
return $this->driver;
}
/**
* @return Platform\PlatformInterface
*/
public function getPlatform()
{
return $this->platform;
}
/**
* @return ResultSet\ResultSetInterface
*/
public function getQueryResultSetPrototype()
{
return $this->queryResultSetPrototype;
}
/** @return string */
public function getCurrentSchema()
{
return $this->driver->getConnection()->getCurrentSchema();
}
/**
* query() is a convenience function
*
* @param string $sql
* @param string|array|ParameterContainer $parametersOrQueryMode
* @throws Exception\InvalidArgumentException
* @return Driver\StatementInterface|ResultSet\ResultSet
*/
public function query(
$sql,
$parametersOrQueryMode = self::QUERY_MODE_PREPARE,
?ResultSet\ResultSetInterface $resultPrototype = null
) {
if (
is_string($parametersOrQueryMode)
&& in_array($parametersOrQueryMode, [self::QUERY_MODE_PREPARE, self::QUERY_MODE_EXECUTE])
) {
$mode = $parametersOrQueryMode;
$parameters = null;
} elseif (is_array($parametersOrQueryMode) || $parametersOrQueryMode instanceof ParameterContainer) {
$mode = self::QUERY_MODE_PREPARE;
$parameters = $parametersOrQueryMode;
} else {
throw new Exception\InvalidArgumentException(
'Parameter 2 to this method must be a flag, an array, or ParameterContainer'
);
}
if ($mode === self::QUERY_MODE_PREPARE) {
$lastPreparedStatement = $this->driver->createStatement($sql);
$lastPreparedStatement->prepare();
if (is_array($parameters) || $parameters instanceof ParameterContainer) {
if (is_array($parameters)) {
$lastPreparedStatement->setParameterContainer(new ParameterContainer($parameters));
} else {
$lastPreparedStatement->setParameterContainer($parameters);
}
$result = $lastPreparedStatement->execute();
} else {
return $lastPreparedStatement;
}
} else {
$result = $this->driver->getConnection()->execute($sql);
}
if ($result instanceof Driver\ResultInterface && $result->isQueryResult()) {
$resultSet = $resultPrototype ?? $this->queryResultSetPrototype;
$resultSetCopy = clone $resultSet;
$resultSetCopy->initialize($result);
return $resultSetCopy;
}
return $result;
}
/**
* Create statement
*
* @param string $initialSql
* @param null|ParameterContainer|array $initialParameters
* @return Driver\StatementInterface
*/
public function createStatement($initialSql = null, $initialParameters = null)
{
$statement = $this->driver->createStatement($initialSql);
if (
$initialParameters === null
|| ! $initialParameters instanceof ParameterContainer
&& is_array($initialParameters)
) {
$initialParameters = new ParameterContainer(is_array($initialParameters) ? $initialParameters : []);
}
$statement->setParameterContainer($initialParameters);
return $statement;
}
public function getHelpers()
{
$functions = [];
$platform = $this->platform;
foreach (func_get_args() as $arg) {
switch ($arg) {
case self::FUNCTION_QUOTE_IDENTIFIER:
$functions[] = function ($value) use ($platform) {
return $platform->quoteIdentifier($value);
};
break;
case self::FUNCTION_QUOTE_VALUE:
$functions[] = function ($value) use ($platform) {
return $platform->quoteValue($value);
};
break;
}
}
}
/**
* @param string $name
* @throws Exception\InvalidArgumentException
* @return Driver\DriverInterface|Platform\PlatformInterface
*/
public function __get($name)
{
switch (strtolower($name)) {
case 'driver':
return $this->driver;
case 'platform':
return $this->platform;
default:
throw new Exception\InvalidArgumentException('Invalid magic property on adapter');
}
}
/**
* @param array $parameters
* @return Driver\DriverInterface
* @throws InvalidArgumentException
* @throws Exception\InvalidArgumentException
*/
protected function createDriver($parameters)
{
if (! isset($parameters['driver'])) {
throw new Exception\InvalidArgumentException(
__FUNCTION__ . ' expects a "driver" key to be present inside the parameters'
);
}
if ($parameters['driver'] instanceof Driver\DriverInterface) {
return $parameters['driver'];
}
if (! is_string($parameters['driver'])) {
throw new Exception\InvalidArgumentException(
__FUNCTION__ . ' expects a "driver" to be a string or instance of DriverInterface'
);
}
$options = [];
if (isset($parameters['options'])) {
$options = (array) $parameters['options'];
unset($parameters['options']);
}
$driverName = strtolower($parameters['driver']);
switch ($driverName) {
case 'mysqli':
$driver = new Driver\Mysqli\Mysqli($parameters, null, null, $options);
break;
case 'sqlsrv':
$driver = new Driver\Sqlsrv\Sqlsrv($parameters);
break;
case 'oci8':
$driver = new Driver\Oci8\Oci8($parameters);
break;
case 'pgsql':
$driver = new Driver\Pgsql\Pgsql($parameters);
break;
case 'ibmdb2':
$driver = new Driver\IbmDb2\IbmDb2($parameters);
break;
case 'pdo':
default:
if ($driverName === 'pdo' || strpos($driverName, 'pdo') === 0) {
$driver = new Driver\Pdo\Pdo($parameters);
}
}
if (! isset($driver) || ! $driver instanceof Driver\DriverInterface) {
throw new Exception\InvalidArgumentException('DriverInterface expected');
}
return $driver;
}
/**
* @param array $parameters
* @return Platform\PlatformInterface
*/
protected function createPlatform(array $parameters)
{
if (isset($parameters['platform'])) {
$platformName = $parameters['platform'];
} elseif ($this->driver instanceof Driver\DriverInterface) {
$platformName = $this->driver->getDatabasePlatformName(Driver\DriverInterface::NAME_FORMAT_CAMELCASE);
} else {
throw new Exception\InvalidArgumentException(
'A platform could not be determined from the provided configuration'
);
}
// currently only supported by the IbmDb2 & Oracle concrete implementations
$options = $parameters['platform_options'] ?? [];
switch ($platformName) {
case 'Mysql':
// mysqli or pdo_mysql driver
if ($this->driver instanceof Driver\Mysqli\Mysqli || $this->driver instanceof Driver\Pdo\Pdo) {
$driver = $this->driver;
} else {
$driver = null;
}
return new Platform\Mysql($driver);
case 'SqlServer':
// PDO is only supported driver for quoting values in this platform
return new Platform\SqlServer($this->driver instanceof Driver\Pdo\Pdo ? $this->driver : null);
case 'Oracle':
if ($this->driver instanceof Driver\Oci8\Oci8 || $this->driver instanceof Driver\Pdo\Pdo) {
$driver = $this->driver;
} else {
$driver = null;
}
return new Platform\Oracle($options, $driver);
case 'Sqlite':
// PDO is only supported driver for quoting values in this platform
if ($this->driver instanceof Driver\Pdo\Pdo) {
return new Platform\Sqlite($this->driver);
}
return new Platform\Sqlite(null);
case 'Postgresql':
// pgsql or pdo postgres driver
if ($this->driver instanceof Driver\Pgsql\Pgsql || $this->driver instanceof Driver\Pdo\Pdo) {
$driver = $this->driver;
} else {
$driver = null;
}
return new Platform\Postgresql($driver);
case 'IbmDb2':
// ibm_db2 driver escaping does not need an action connection
return new Platform\IbmDb2($options);
default:
return new Platform\Sql92();
}
}
/**
* @param array $parameters
* @return Profiler\ProfilerInterface
* @throws Exception\InvalidArgumentException
*/
protected function createProfiler($parameters)
{
if ($parameters['profiler'] instanceof Profiler\ProfilerInterface) {
return $parameters['profiler'];
}
if (is_bool($parameters['profiler'])) {
return $parameters['profiler'] === true ? new Profiler\Profiler() : null;
}
throw new Exception\InvalidArgumentException(
'"profiler" parameter must be an instance of ProfilerInterface or a boolean'
);
}
/**
* @deprecated
*
* @param array $parameters
* @return Driver\DriverInterface
* @throws InvalidArgumentException
* @throws Exception\InvalidArgumentException
*/
protected function createDriverFromParameters(array $parameters)
{
return $this->createDriver($parameters);
}
/**
* @deprecated
*
* @return Platform\PlatformInterface
*/
protected function createPlatformFromDriver(Driver\DriverInterface $driver)
{
return $this->createPlatform($driver);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/AdapterAwareInterface.php | src/Adapter/AdapterAwareInterface.php | <?php
namespace Laminas\Db\Adapter;
interface AdapterAwareInterface
{
/**
* Set db adapter
*
* @return AdapterAwareInterface
*/
public function setDbAdapter(Adapter $adapter);
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/StatementContainer.php | src/Adapter/StatementContainer.php | <?php
namespace Laminas\Db\Adapter;
class StatementContainer implements StatementContainerInterface
{
/** @var string */
protected $sql = '';
/** @var ParameterContainer */
protected $parameterContainer;
/**
* @param string|null $sql
*/
public function __construct($sql = null, ?ParameterContainer $parameterContainer = null)
{
if ($sql) {
$this->setSql($sql);
}
$this->parameterContainer = $parameterContainer ?: new ParameterContainer();
}
/**
* @param string $sql
* @return $this Provides a fluent interface
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* @return $this Provides a fluent interface
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* @return null|ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/AdapterInterface.php | src/Adapter/AdapterInterface.php | <?php
namespace Laminas\Db\Adapter;
/**
* @property Driver\DriverInterface $driver
* @property Platform\PlatformInterface $platform
*/
interface AdapterInterface
{
/**
* @return Driver\DriverInterface
*/
public function getDriver();
/**
* @return Platform\PlatformInterface
*/
public function getPlatform();
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/ParameterContainer.php | src/Adapter/ParameterContainer.php | <?php
namespace Laminas\Db\Adapter;
use ArrayAccess;
use ArrayIterator;
use Countable;
use Iterator;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use ReturnTypeWillChange;
use function array_key_exists;
use function array_values;
use function count;
use function current;
use function is_array;
use function is_int;
use function is_string;
use function key;
use function ltrim;
use function next;
use function reset;
use function strpos;
class ParameterContainer implements Iterator, ArrayAccess, Countable
{
public const TYPE_AUTO = 'auto';
public const TYPE_NULL = 'null';
public const TYPE_DOUBLE = 'double';
public const TYPE_INTEGER = 'integer';
public const TYPE_BINARY = 'binary';
public const TYPE_STRING = 'string';
public const TYPE_LOB = 'lob';
/**
* Data
*
* @var array
*/
protected $data = [];
/** @var array */
protected $positions = [];
/**
* Errata
*
* @var array
*/
protected $errata = [];
/**
* Max length
*
* @var array
*/
protected $maxLength = [];
/** @var array */
protected $nameMapping = [];
/**
* Constructor
*
* @param array $data
*/
public function __construct(array $data = [])
{
if ($data) {
$this->setFromArray($data);
}
}
/**
* Offset exists
*
* @param string $name
* @return bool
*/
#[ReturnTypeWillChange]
public function offsetExists($name)
{
return isset($this->data[$name]);
}
/**
* Offset get
*
* @param string $name
* @return mixed
*/
#[ReturnTypeWillChange]
public function offsetGet($name)
{
if (isset($this->data[$name])) {
return $this->data[$name];
}
$normalizedName = ltrim($name, ':');
if (
isset($this->nameMapping[$normalizedName])
&& isset($this->data[$this->nameMapping[$normalizedName]])
) {
return $this->data[$this->nameMapping[$normalizedName]];
}
return null;
}
/**
* @param string|int $name
* @param string|int $from
* @return void
*/
public function offsetSetReference($name, $from)
{
$this->data[$name] = &$this->data[$from];
}
/**
* Offset set
*
* @param string|int $name
* @param mixed $value
* @param mixed $errata
* @param mixed $maxLength
* @throws Exception\InvalidArgumentException
*/
#[ReturnTypeWillChange]
public function offsetSet($name, $value, $errata = null, $maxLength = null)
{
$position = false;
// if integer, get name for this position
if (is_int($name)) {
if (isset($this->positions[$name])) {
$position = $name;
$name = $this->positions[$name];
} else {
$name = (string) $name;
}
} elseif (is_string($name)) {
// is a string:
$normalizedName = ltrim($name, ':');
if (isset($this->nameMapping[$normalizedName])) {
// We have a mapping; get real name from it
$name = $this->nameMapping[$normalizedName];
}
$position = array_key_exists($name, $this->data);
// @todo: this assumes that any data begining with a ":" will be considered a parameter
if (is_string($value) && strpos($value, ':') === 0) {
// We have a named parameter; handle name mapping (container creation)
$this->nameMapping[ltrim($value, ':')] = $name;
}
} elseif ($name === null) {
$name = (string) count($this->data);
} else {
throw new Exception\InvalidArgumentException('Keys must be string, integer or null');
}
if ($position === false) {
$this->positions[] = $name;
}
$this->data[$name] = $value;
if ($errata) {
$this->offsetSetErrata($name, $errata);
}
if ($maxLength) {
$this->offsetSetMaxLength($name, $maxLength);
}
}
/**
* Offset unset
*
* @param string $name
* @return $this Provides a fluent interface
*/
#[ReturnTypeWillChange]
public function offsetUnset($name)
{
if (is_int($name) && isset($this->positions[$name])) {
$name = $this->positions[$name];
}
unset($this->data[$name]);
return $this;
}
/**
* Set from array
*
* @param array $data
* @return $this Provides a fluent interface
*/
public function setFromArray(array $data)
{
foreach ($data as $n => $v) {
$this->offsetSet($n, $v);
}
return $this;
}
/**
* Offset set max length
*
* @param string|int $name
* @param mixed $maxLength
*/
public function offsetSetMaxLength($name, $maxLength)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
$this->maxLength[$name] = $maxLength;
}
/**
* Offset get max length
*
* @param string|int $name
* @throws Exception\InvalidArgumentException
* @return mixed
*/
public function offsetGetMaxLength($name)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
if (! array_key_exists($name, $this->data)) {
throw new Exception\InvalidArgumentException('Data does not exist for this name/position');
}
return $this->maxLength[$name];
}
/**
* Offset has max length
*
* @param string|int $name
* @return bool
*/
public function offsetHasMaxLength($name)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
return isset($this->maxLength[$name]);
}
/**
* Offset unset max length
*
* @param string|int $name
* @throws Exception\InvalidArgumentException
*/
public function offsetUnsetMaxLength($name)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
if (! array_key_exists($name, $this->maxLength)) {
throw new Exception\InvalidArgumentException('Data does not exist for this name/position');
}
$this->maxLength[$name] = null;
}
/**
* Get max length iterator
*
* @return ArrayIterator
*/
public function getMaxLengthIterator()
{
return new ArrayIterator($this->maxLength);
}
/**
* Offset set errata
*
* @param string|int $name
* @param mixed $errata
*/
public function offsetSetErrata($name, $errata)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
$this->errata[$name] = $errata;
}
/**
* Offset get errata
*
* @param string|int $name
* @throws Exception\InvalidArgumentException
* @return mixed
*/
public function offsetGetErrata($name)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
if (! array_key_exists($name, $this->data)) {
throw new Exception\InvalidArgumentException('Data does not exist for this name/position');
}
return $this->errata[$name];
}
/**
* Offset has errata
*
* @param string|int $name
* @return bool
*/
public function offsetHasErrata($name)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
return isset($this->errata[$name]);
}
/**
* Offset unset errata
*
* @param string|int $name
* @throws Exception\InvalidArgumentException
*/
public function offsetUnsetErrata($name)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
if (! array_key_exists($name, $this->errata)) {
throw new Exception\InvalidArgumentException('Data does not exist for this name/position');
}
$this->errata[$name] = null;
}
/**
* Get errata iterator
*
* @return ArrayIterator
*/
public function getErrataIterator()
{
return new ArrayIterator($this->errata);
}
/**
* getNamedArray
*
* @return array
*/
public function getNamedArray()
{
return $this->data;
}
/**
* getNamedArray
*
* @return array
*/
public function getPositionalArray()
{
return array_values($this->data);
}
/**
* count
*
* @return int
*/
#[ReturnTypeWillChange]
public function count()
{
return count($this->data);
}
/**
* Current
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function current()
{
return current($this->data);
}
/**
* Next
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function next()
{
return next($this->data);
}
/**
* Key
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function key()
{
return key($this->data);
}
/**
* Valid
*
* @return bool
*/
#[ReturnTypeWillChange]
public function valid()
{
return current($this->data) !== false;
}
/**
* Rewind
*/
#[ReturnTypeWillChange]
public function rewind()
{
reset($this->data);
}
/**
* @param array|ParameterContainer $parameters
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function merge($parameters)
{
if (! is_array($parameters) && ! $parameters instanceof ParameterContainer) {
throw new Exception\InvalidArgumentException(
'$parameters must be an array or an instance of ParameterContainer'
);
}
if (count($parameters) === 0) {
return $this;
}
if ($parameters instanceof ParameterContainer) {
$parameters = $parameters->getNamedArray();
}
foreach ($parameters as $key => $value) {
if (is_int($key)) {
$key = null;
}
$this->offsetSet($key, $value);
}
return $this;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/AdapterAwareTrait.php | src/Adapter/AdapterAwareTrait.php | <?php
namespace Laminas\Db\Adapter;
trait AdapterAwareTrait
{
/** @var Adapter */
protected $adapter;
/**
* Set db adapter
*
* @return $this Provides a fluent interface
*/
public function setDbAdapter(Adapter $adapter)
{
$this->adapter = $adapter;
return $this;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/AdapterServiceDelegator.php | src/Adapter/AdapterServiceDelegator.php | <?php
namespace Laminas\Db\Adapter;
use Psr\Container\ContainerInterface;
class AdapterServiceDelegator
{
/** @var string */
private $adapterName;
public function __construct(string $adapterName = AdapterInterface::class)
{
$this->adapterName = $adapterName;
}
public static function __set_state(array $state): self
{
return new self($state['adapterName'] ?? AdapterInterface::class);
}
/** @return AdapterInterface */
public function __invoke(
ContainerInterface $container,
string $name,
callable $callback,
?array $options = null
) {
$instance = $callback();
if (! $instance instanceof AdapterAwareInterface) {
return $instance;
}
if (! $container->has($this->adapterName)) {
return $instance;
}
$databaseAdapter = $container->get($this->adapterName);
if (! $databaseAdapter instanceof Adapter) {
return $instance;
}
$instance->setDbAdapter($databaseAdapter);
return $instance;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/AdapterServiceFactory.php | src/Adapter/AdapterServiceFactory.php | <?php
namespace Laminas\Db\Adapter;
use Interop\Container\ContainerInterface;
use Laminas\ServiceManager\FactoryInterface;
use Laminas\ServiceManager\ServiceLocatorInterface;
class AdapterServiceFactory implements FactoryInterface
{
/**
* Create db adapter service
*
* @param string $requestedName
* @param array $options
* @return Adapter
*/
public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null)
{
$config = $container->get('config');
return new Adapter($config['db']);
}
/**
* Create db adapter service (v2)
*
* @return Adapter
*/
public function createService(ServiceLocatorInterface $container)
{
return $this($container, Adapter::class);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/AdapterAbstractServiceFactory.php | src/Adapter/AdapterAbstractServiceFactory.php | <?php
namespace Laminas\Db\Adapter;
use Interop\Container\ContainerInterface;
use Laminas\ServiceManager\AbstractFactoryInterface;
use Laminas\ServiceManager\ServiceLocatorInterface;
use function is_array;
/**
* Database adapter abstract service factory.
*
* Allows configuring several database instances (such as writer and reader).
*/
class AdapterAbstractServiceFactory implements AbstractFactoryInterface
{
/** @var array */
protected $config;
/**
* Can we create an adapter by the requested name?
*
* @param string $requestedName
* @return bool
*/
public function canCreate(ContainerInterface $container, $requestedName)
{
$config = $this->getConfig($container);
if (empty($config)) {
return false;
}
return isset($config[$requestedName])
&& is_array($config[$requestedName])
&& ! empty($config[$requestedName]);
}
/**
* Determine if we can create a service with name (SM v2 compatibility)
*
* @param string $name
* @param string $requestedName
* @return bool
*/
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
return $this->canCreate($serviceLocator, $requestedName);
}
/**
* Create a DB adapter
*
* @param string $requestedName
* @param array $options
* @return Adapter
*/
public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null)
{
$config = $this->getConfig($container);
return new Adapter($config[$requestedName]);
}
/**
* Create service with name
*
* @param string $name
* @param string $requestedName
* @return Adapter
*/
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
return $this($serviceLocator, $requestedName);
}
/**
* Get db configuration, if any
*
* @return array
*/
protected function getConfig(ContainerInterface $container)
{
if ($this->config !== null) {
return $this->config;
}
if (! $container->has('config')) {
$this->config = [];
return $this->config;
}
$config = $container->get('config');
if (
! isset($config['db'])
|| ! is_array($config['db'])
) {
$this->config = [];
return $this->config;
}
$config = $config['db'];
if (
! isset($config['adapters'])
|| ! is_array($config['adapters'])
) {
$this->config = [];
return $this->config;
}
$this->config = $config['adapters'];
return $this->config;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/ConnectionInterface.php | src/Adapter/Driver/ConnectionInterface.php | <?php
namespace Laminas\Db\Adapter\Driver;
interface ConnectionInterface
{
/**
* Get current schema
*
* @return string
*/
public function getCurrentSchema();
/**
* Get resource
*
* @return mixed
*/
public function getResource();
/**
* Connect
*
* @return ConnectionInterface
*/
public function connect();
/**
* Is connected
*
* @return bool
*/
public function isConnected();
/**
* Disconnect
*
* @return ConnectionInterface
*/
public function disconnect();
/**
* Begin transaction
*
* @return ConnectionInterface
*/
public function beginTransaction();
/**
* Commit
*
* @return ConnectionInterface
*/
public function commit();
/**
* Rollback
*
* @return ConnectionInterface
*/
public function rollback();
/**
* Execute
*
* @param string $sql
* @return ResultInterface
*/
public function execute($sql);
/**
* Get last generated id
*
* @param null $name Ignored
* @return int
*/
public function getLastGeneratedValue($name = null);
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/ResultInterface.php | src/Adapter/Driver/ResultInterface.php | <?php
namespace Laminas\Db\Adapter\Driver;
use Countable;
use Iterator;
interface ResultInterface extends
Countable,
Iterator
{
/**
* Force buffering
*
* @return void
*/
public function buffer();
/**
* Check if is buffered
*
* @return bool|null
*/
public function isBuffered();
/**
* Is query result?
*
* @return bool
*/
public function isQueryResult();
/**
* Get affected rows
*
* @return int
*/
public function getAffectedRows();
/**
* Get generated value
*
* @return mixed|null
*/
public function getGeneratedValue();
/**
* Get the resource
*
* @return mixed
*/
public function getResource();
/**
* Get field count
*
* @return int
*/
public function getFieldCount();
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/DriverInterface.php | src/Adapter/Driver/DriverInterface.php | <?php
namespace Laminas\Db\Adapter\Driver;
interface DriverInterface
{
public const PARAMETERIZATION_POSITIONAL = 'positional';
public const PARAMETERIZATION_NAMED = 'named';
public const NAME_FORMAT_CAMELCASE = 'camelCase';
public const NAME_FORMAT_NATURAL = 'natural';
/**
* Get database platform name
*
* @param string $nameFormat
* @return string
*/
public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE);
/**
* Check environment
*
* @return bool
*/
public function checkEnvironment();
/**
* Get connection
*
* @return ConnectionInterface
*/
public function getConnection();
/**
* Create statement
*
* @param string|resource $sqlOrResource
* @return StatementInterface
*/
public function createStatement($sqlOrResource = null);
/**
* Create result
*
* @param resource $resource
* @return ResultInterface
*/
public function createResult($resource);
/**
* Get prepare type
*
* @return string
*/
public function getPrepareType();
/**
* Format parameter name
*
* @param string $name
* @param mixed $type
* @return string
*/
public function formatParameterName($name, $type = null);
/**
* Get last generated value
*
* @return mixed
*/
public function getLastGeneratedValue();
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/AbstractConnection.php | src/Adapter/Driver/AbstractConnection.php | <?php
namespace Laminas\Db\Adapter\Driver;
use Laminas\Db\Adapter\Profiler\ProfilerAwareInterface;
use Laminas\Db\Adapter\Profiler\ProfilerInterface;
abstract class AbstractConnection implements ConnectionInterface, ProfilerAwareInterface
{
/** @var array */
protected $connectionParameters = [];
/** @var string|null */
protected $driverName;
/** @var boolean */
protected $inTransaction = false;
/**
* Nested transactions count.
*
* @var integer
*/
protected $nestedTransactionsCount = 0;
/** @var ProfilerInterface|null */
protected $profiler;
/** @var resource|null */
protected $resource;
/**
* {@inheritDoc}
*/
public function disconnect()
{
if ($this->isConnected()) {
$this->resource = null;
}
return $this;
}
/**
* Get connection parameters
*
* @return array
*/
public function getConnectionParameters()
{
return $this->connectionParameters;
}
/**
* Get driver name
*
* @return null|string
*/
public function getDriverName()
{
return $this->driverName;
}
/**
* @return null|ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* {@inheritDoc}
*
* @return resource
*/
public function getResource()
{
if (! $this->isConnected()) {
$this->connect();
}
return $this->resource;
}
/**
* Checks whether the connection is in transaction state.
*
* @return boolean
*/
public function inTransaction()
{
return $this->inTransaction;
}
/**
* @param array $connectionParameters
* @return $this Provides a fluent interface
*/
public function setConnectionParameters(array $connectionParameters)
{
$this->connectionParameters = $connectionParameters;
return $this;
}
/**
* {@inheritDoc}
*
* @return $this Provides a fluent interface
*/
public function setProfiler(ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/StatementInterface.php | src/Adapter/Driver/StatementInterface.php | <?php
namespace Laminas\Db\Adapter\Driver;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\StatementContainerInterface;
interface StatementInterface extends StatementContainerInterface
{
/**
* Get resource
*
* @return resource
*/
public function getResource();
/**
* Prepare sql
*
* @param string $sql
*/
public function prepare($sql = null);
/**
* Check if is prepared
*
* @return bool
*/
public function isPrepared();
/**
* Execute
*
* @param null|array|ParameterContainer $parameters
* @return ResultInterface
*/
public function execute($parameters = null);
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Sqlsrv/Connection.php | src/Adapter/Driver/Sqlsrv/Connection.php | <?php
namespace Laminas\Db\Adapter\Driver\Sqlsrv;
use Laminas\Db\Adapter\Driver\AbstractConnection;
use Laminas\Db\Adapter\Driver\Sqlsrv\Exception\ErrorException;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Exception\InvalidArgumentException;
use function array_merge;
use function get_resource_type;
use function is_array;
use function is_resource;
use function sqlsrv_begin_transaction;
use function sqlsrv_close;
use function sqlsrv_commit;
use function sqlsrv_connect;
use function sqlsrv_errors;
use function sqlsrv_fetch_array;
use function sqlsrv_query;
use function sqlsrv_rollback;
use function strtolower;
class Connection extends AbstractConnection
{
/** @var Sqlsrv */
protected $driver;
/**
* Constructor
*
* @param array|resource $connectionInfo
* @throws InvalidArgumentException
*/
public function __construct($connectionInfo)
{
if (is_array($connectionInfo)) {
$this->setConnectionParameters($connectionInfo);
} elseif (is_resource($connectionInfo)) {
$this->setResource($connectionInfo);
} else {
throw new Exception\InvalidArgumentException('$connection must be an array of parameters or a resource');
}
}
/**
* Set driver
*
* @return $this Provides a fluent interface
*/
public function setDriver(Sqlsrv $driver)
{
$this->driver = $driver;
return $this;
}
/**
* {@inheritDoc}
*/
public function getCurrentSchema()
{
if (! $this->isConnected()) {
$this->connect();
}
$result = sqlsrv_query($this->resource, 'SELECT SCHEMA_NAME()');
$r = sqlsrv_fetch_array($result);
return $r[0];
}
/**
* Set resource
*
* @param resource $resource
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setResource($resource)
{
if (get_resource_type($resource) !== 'SQL Server Connection') {
throw new Exception\InvalidArgumentException('Resource provided was not of type SQL Server Connection');
}
$this->resource = $resource;
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\RuntimeException
*/
public function connect()
{
if ($this->resource) {
return $this;
}
$serverName = '.';
$params = [
'ReturnDatesAsStrings' => true,
];
foreach ($this->connectionParameters as $key => $value) {
switch (strtolower($key)) {
case 'hostname':
case 'servername':
$serverName = (string) $value;
break;
case 'username':
case 'uid':
$params['UID'] = (string) $value;
break;
case 'password':
case 'pwd':
$params['PWD'] = (string) $value;
break;
case 'database':
case 'dbname':
$params['Database'] = (string) $value;
break;
case 'charset':
$params['CharacterSet'] = (string) $value;
break;
case 'driver_options':
case 'options':
$params = array_merge($params, (array) $value);
break;
}
}
$this->resource = sqlsrv_connect($serverName, $params);
if (! $this->resource) {
throw new Exception\RuntimeException(
'Connect Error',
0,
new ErrorException(sqlsrv_errors())
);
}
return $this;
}
/**
* {@inheritDoc}
*/
public function isConnected()
{
return is_resource($this->resource);
}
/**
* {@inheritDoc}
*/
public function disconnect()
{
sqlsrv_close($this->resource);
$this->resource = null;
}
/**
* {@inheritDoc}
*/
public function beginTransaction()
{
if (! $this->isConnected()) {
$this->connect();
}
if (sqlsrv_begin_transaction($this->resource) === false) {
throw new Exception\RuntimeException(
new ErrorException(sqlsrv_errors())
);
}
$this->inTransaction = true;
return $this;
}
/**
* {@inheritDoc}
*/
public function commit()
{
// http://msdn.microsoft.com/en-us/library/cc296194.aspx
if (! $this->isConnected()) {
$this->connect();
}
sqlsrv_commit($this->resource);
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*/
public function rollback()
{
// http://msdn.microsoft.com/en-us/library/cc296176.aspx
if (! $this->isConnected()) {
throw new Exception\RuntimeException('Must be connected before you can rollback.');
}
sqlsrv_rollback($this->resource);
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\RuntimeException
*/
public function execute($sql)
{
if (! $this->isConnected()) {
$this->connect();
}
if (! $this->driver instanceof Sqlsrv) {
throw new Exception\RuntimeException('Connection is missing an instance of Sqlsrv');
}
if ($this->profiler) {
$this->profiler->profilerStart($sql);
}
$returnValue = sqlsrv_query($this->resource, $sql);
if ($this->profiler) {
$this->profiler->profilerFinish($sql);
}
// if the returnValue is something other than a Sqlsrv_result, bypass wrapping it
if ($returnValue === false) {
$errors = sqlsrv_errors();
// ignore general warnings
if ($errors[0]['SQLSTATE'] !== '01000') {
throw new Exception\RuntimeException(
'An exception occurred while trying to execute the provided $sql',
null,
new ErrorException($errors)
);
}
}
return $this->driver->createResult($returnValue);
}
/**
* Prepare
*
* @param string $sql
* @return string
*/
public function prepare($sql)
{
if (! $this->isConnected()) {
$this->connect();
}
return $this->driver->createStatement($sql);
}
/**
* {@inheritDoc}
*
* @return mixed
*/
public function getLastGeneratedValue($name = null)
{
if (! $this->resource) {
$this->connect();
}
$sql = 'SELECT @@IDENTITY as Current_Identity';
$result = sqlsrv_query($this->resource, $sql);
$row = sqlsrv_fetch_array($result);
return $row['Current_Identity'];
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Sqlsrv/Result.php | src/Adapter/Driver/Sqlsrv/Result.php | <?php
namespace Laminas\Db\Adapter\Driver\Sqlsrv;
use Iterator;
use Laminas\Db\Adapter\Driver\ResultInterface;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use ReturnTypeWillChange;
use function is_bool;
use function sqlsrv_fetch_array;
use function sqlsrv_num_fields;
use function sqlsrv_num_rows;
use function sqlsrv_rows_affected;
use const SQLSRV_FETCH_ASSOC;
use const SQLSRV_SCROLL_FIRST;
use const SQLSRV_SCROLL_NEXT;
class Result implements Iterator, ResultInterface
{
/** @var resource */
protected $resource;
/** @var bool */
protected $currentData = false;
/** @var bool */
protected $currentComplete = false;
/** @var int */
protected $position = -1;
/** @var mixed */
protected $generatedValue;
/**
* Initialize
*
* @param resource $resource
* @param mixed $generatedValue
* @return $this Provides a fluent interface
*/
public function initialize($resource, $generatedValue = null)
{
$this->resource = $resource;
$this->generatedValue = $generatedValue;
return $this;
}
/**
* @return null
*/
public function buffer()
{
return null;
}
/**
* @return bool
*/
public function isBuffered()
{
return false;
}
/**
* Get resource
*
* @return resource
*/
public function getResource()
{
return $this->resource;
}
/**
* Current
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function current()
{
if ($this->currentComplete) {
return $this->currentData;
}
$this->load();
return $this->currentData;
}
/**
* Next
*
* @return bool
*/
#[ReturnTypeWillChange]
public function next()
{
$this->load();
return true;
}
/**
* Load
*
* @param int $row
* @return mixed
*/
protected function load($row = SQLSRV_SCROLL_NEXT)
{
$this->currentData = sqlsrv_fetch_array($this->resource, SQLSRV_FETCH_ASSOC, $row);
$this->currentComplete = true;
$this->position++;
return $this->currentData;
}
/**
* Key
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function key()
{
return $this->position;
}
/**
* Rewind
*
* @return bool
*/
#[ReturnTypeWillChange]
public function rewind()
{
$this->position = 0;
$this->load(SQLSRV_SCROLL_FIRST);
return true;
}
/**
* Valid
*
* @return bool
*/
#[ReturnTypeWillChange]
public function valid()
{
if ($this->currentComplete && $this->currentData) {
return true;
}
return $this->load();
}
/**
* Count
*
* @return int
*/
#[ReturnTypeWillChange]
public function count()
{
return sqlsrv_num_rows($this->resource);
}
/**
* @return bool|int
*/
public function getFieldCount()
{
return sqlsrv_num_fields($this->resource);
}
/**
* Is query result
*
* @return bool
*/
public function isQueryResult()
{
if (is_bool($this->resource)) {
return false;
}
return sqlsrv_num_fields($this->resource) > 0;
}
/**
* Get affected rows
*
* @return int
*/
public function getAffectedRows()
{
return sqlsrv_rows_affected($this->resource);
}
/**
* @return mixed|null
*/
public function getGeneratedValue()
{
return $this->generatedValue;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Sqlsrv/Sqlsrv.php | src/Adapter/Driver/Sqlsrv/Sqlsrv.php | <?php
namespace Laminas\Db\Adapter\Driver\Sqlsrv;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Profiler;
use function extension_loaded;
use function is_resource;
use function is_string;
class Sqlsrv implements DriverInterface, Profiler\ProfilerAwareInterface
{
/** @var Connection */
protected $connection;
/** @var Statement */
protected $statementPrototype;
/** @var Result */
protected $resultPrototype;
/** @var null|Profiler\ProfilerInterface */
protected $profiler;
/**
* @param array|Connection|resource $connection
*/
public function __construct($connection, ?Statement $statementPrototype = null, ?Result $resultPrototype = null)
{
if (! $connection instanceof Connection) {
$connection = new Connection($connection);
}
$this->registerConnection($connection);
$this->registerStatementPrototype($statementPrototype ?: new Statement());
$this->registerResultPrototype($resultPrototype ?: new Result());
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
if ($this->connection instanceof Profiler\ProfilerAwareInterface) {
$this->connection->setProfiler($profiler);
}
if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) {
$this->statementPrototype->setProfiler($profiler);
}
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Register connection
*
* @return $this Provides a fluent interface
*/
public function registerConnection(Connection $connection)
{
$this->connection = $connection;
$this->connection->setDriver($this);
return $this;
}
/**
* Register statement prototype
*
* @return $this Provides a fluent interface
*/
public function registerStatementPrototype(Statement $statementPrototype)
{
$this->statementPrototype = $statementPrototype;
$this->statementPrototype->setDriver($this);
return $this;
}
/**
* Register result prototype
*
* @return $this Provides a fluent interface
*/
public function registerResultPrototype(Result $resultPrototype)
{
$this->resultPrototype = $resultPrototype;
return $this;
}
/**
* Get database paltform name
*
* @param string $nameFormat
* @return string
*/
public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE)
{
if ($nameFormat === self::NAME_FORMAT_CAMELCASE) {
return 'SqlServer';
}
return 'SQLServer';
}
/**
* Check environment
*
* @throws Exception\RuntimeException
* @return void
*/
public function checkEnvironment()
{
if (! extension_loaded('sqlsrv')) {
throw new Exception\RuntimeException(
'The Sqlsrv extension is required for this adapter but the extension is not loaded'
);
}
}
/**
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* @param string|resource $sqlOrResource
* @return Statement
*/
public function createStatement($sqlOrResource = null)
{
$statement = clone $this->statementPrototype;
if (is_resource($sqlOrResource)) {
$statement->initialize($sqlOrResource);
} else {
if (! $this->connection->isConnected()) {
$this->connection->connect();
}
$statement->initialize($this->connection->getResource());
if (is_string($sqlOrResource)) {
$statement->setSql($sqlOrResource);
} elseif ($sqlOrResource !== null) {
throw new Exception\InvalidArgumentException(
'createStatement() only accepts an SQL string or a Sqlsrv resource'
);
}
}
return $statement;
}
/**
* @param resource $resource
* @return Result
*/
public function createResult($resource)
{
$result = clone $this->resultPrototype;
$result->initialize($resource, $this->connection->getLastGeneratedValue());
return $result;
}
/**
* @return Result
*/
public function getResultPrototype()
{
return $this->resultPrototype;
}
/**
* @return string
*/
public function getPrepareType()
{
return self::PARAMETERIZATION_POSITIONAL;
}
/**
* @param string $name
* @param mixed $type
* @return string
*/
public function formatParameterName($name, $type = null)
{
return '?';
}
/**
* @return mixed
*/
public function getLastGeneratedValue()
{
return $this->getConnection()->getLastGeneratedValue();
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Sqlsrv/Statement.php | src/Adapter/Driver/Sqlsrv/Statement.php | <?php
namespace Laminas\Db\Adapter\Driver\Sqlsrv;
use Laminas\Db\Adapter\Driver\StatementInterface;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Profiler;
use function get_resource_type;
use function is_array;
use function sqlsrv_errors;
use function sqlsrv_execute;
use function sqlsrv_prepare;
use function substr_count;
use const SQLSRV_PARAM_IN;
class Statement implements StatementInterface, Profiler\ProfilerAwareInterface
{
/** @var resource */
protected $sqlsrv;
/** @var Sqlsrv */
protected $driver;
/** @var Profiler\ProfilerInterface */
protected $profiler;
/** @var string */
protected $sql;
/** @var bool */
protected $isQuery;
/** @var array */
protected $parameterReferences = [];
/** @var ParameterContainer */
protected $parameterContainer;
/** @var resource */
protected $resource;
/** @var bool */
protected $isPrepared = false;
/** @var array */
protected $prepareParams = [];
/** @var array */
protected $prepareOptions = [];
/** @var array */
protected $parameterReferenceValues = [];
/**
* Set driver
*
* @return $this Provides a fluent interface
*/
public function setDriver(Sqlsrv $driver)
{
$this->driver = $driver;
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* One of two resource types will be provided here:
* a) "SQL Server Connection" when a prepared statement needs to still be produced
* b) "SQL Server Statement" when a prepared statement has been already produced
* (there will need to already be a bound param set if it applies to this query)
*
* @param resource $resource
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function initialize($resource)
{
$resourceType = get_resource_type($resource);
if ($resourceType === 'SQL Server Connection') {
$this->sqlsrv = $resource;
} elseif ($resourceType === 'SQL Server Statement') {
$this->resource = $resource;
$this->isPrepared = true;
} else {
throw new Exception\InvalidArgumentException('Invalid resource provided to ' . self::class);
}
return $this;
}
/**
* Set parameter container
*
* @return $this Provides a fluent interface
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* @return ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* @param resource $resource
* @return $this Provides a fluent interface
*/
public function setResource($resource)
{
$this->resource = $resource;
return $this;
}
/**
* Get resource
*
* @return resource
*/
public function getResource()
{
return $this->resource;
}
/**
* @param string $sql
* @return $this Provides a fluent interface
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Get sql
*
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* @param string $sql
* @param array $options
* @return $this Provides a fluent interface
* @throws Exception\RuntimeException
*/
public function prepare($sql = null, array $options = [])
{
if ($this->isPrepared) {
throw new Exception\RuntimeException('Already prepared');
}
$sql = $sql ?: $this->sql;
$options = $options ?: $this->prepareOptions;
$pRef = &$this->parameterReferences;
for ($position = 0, $count = substr_count($sql, '?'); $position < $count; $position++) {
if (! isset($this->prepareParams[$position])) {
$pRef[$position] = [&$this->parameterReferenceValues[$position], SQLSRV_PARAM_IN, null, null];
} else {
$pRef[$position] = &$this->prepareParams[$position];
}
}
$this->resource = sqlsrv_prepare($this->sqlsrv, $sql, $pRef, $options);
$this->isPrepared = true;
return $this;
}
/**
* @return bool
*/
public function isPrepared()
{
return $this->isPrepared;
}
/**
* Execute
*
* @param null|array|ParameterContainer $parameters
* @throws Exception\RuntimeException
* @return Result
*/
public function execute($parameters = null)
{
/** END Standard ParameterContainer Merging Block */
if (! $this->isPrepared) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (! $this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
if ($this->parameterContainer->count() > 0) {
$this->bindParametersFromContainer();
}
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
$resultValue = sqlsrv_execute($this->resource);
if ($this->profiler) {
$this->profiler->profilerFinish();
}
if ($resultValue === false) {
$errors = sqlsrv_errors();
// ignore general warnings
if ($errors[0]['SQLSTATE'] !== '01000') {
throw new Exception\RuntimeException($errors[0]['message']);
}
}
return $this->driver->createResult($this->resource);
}
/**
* Bind parameters from container
*/
protected function bindParametersFromContainer()
{
$values = $this->parameterContainer->getPositionalArray();
$position = 0;
foreach ($values as $value) {
$this->parameterReferences[$position++][0] = $value;
}
}
/**
* @param array $prepareParams
*/
public function setPrepareParams(array $prepareParams)
{
$this->prepareParams = $prepareParams;
}
/**
* @param array $prepareOptions
*/
public function setPrepareOptions(array $prepareOptions)
{
$this->prepareOptions = $prepareOptions;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Sqlsrv/Exception/ExceptionInterface.php | src/Adapter/Driver/Sqlsrv/Exception/ExceptionInterface.php | <?php
namespace Laminas\Db\Adapter\Driver\Sqlsrv\Exception;
use Laminas\Db\Adapter\Exception;
interface ExceptionInterface extends Exception\ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Sqlsrv/Exception/ErrorException.php | src/Adapter/Driver/Sqlsrv/Exception/ErrorException.php | <?php
namespace Laminas\Db\Adapter\Driver\Sqlsrv\Exception;
use Laminas\Db\Adapter\Exception;
use function sqlsrv_errors;
class ErrorException extends Exception\ErrorException implements ExceptionInterface
{
/**
* Errors
*
* @var array
*/
protected $errors = [];
/**
* Construct
*
* @param bool $errors
*/
public function __construct($errors = false)
{
$this->errors = $errors === false ? sqlsrv_errors() : $errors;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Feature/DriverFeatureInterface.php | src/Adapter/Driver/Feature/DriverFeatureInterface.php | <?php
namespace Laminas\Db\Adapter\Driver\Feature;
interface DriverFeatureInterface
{
/**
* Setup the default features for Pdo
*
* @return DriverFeatureInterface
*/
public function setupDefaultFeatures();
/**
* Add feature
*
* @param string $name
* @param mixed $feature
* @return DriverFeatureInterface
*/
public function addFeature($name, $feature);
/**
* Get feature
*
* @param string $name
* @return mixed|false
*/
public function getFeature($name);
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Feature/AbstractFeature.php | src/Adapter/Driver/Feature/AbstractFeature.php | <?php
namespace Laminas\Db\Adapter\Driver\Feature;
use Laminas\Db\Adapter\Driver\DriverInterface;
abstract class AbstractFeature
{
/** @var DriverInterface */
protected $driver;
/**
* Set driver
*
* @return void
*/
public function setDriver(DriverInterface $driver)
{
$this->driver = $driver;
}
/**
* Get name
*
* @return string
*/
abstract public function getName();
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Oci8/Connection.php | src/Adapter/Driver/Oci8/Connection.php | <?php
namespace Laminas\Db\Adapter\Driver\Oci8;
use Laminas\Db\Adapter\Driver\AbstractConnection;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Exception\InvalidArgumentException;
use function get_resource_type;
use function is_array;
use function is_resource;
class Connection extends AbstractConnection
{
/** @var Oci8 */
protected $driver;
/**
* Constructor
*
* @param array|resource|null $connectionInfo
* @throws InvalidArgumentException
*/
public function __construct($connectionInfo = null)
{
if (is_array($connectionInfo)) {
$this->setConnectionParameters($connectionInfo);
} elseif ($connectionInfo instanceof \oci8) {
$this->setResource($connectionInfo);
} elseif (null !== $connectionInfo) {
throw new Exception\InvalidArgumentException(
'$connection must be an array of parameters, an oci8 resource or null'
);
}
}
/**
* @return $this Provides a fluent interface
*/
public function setDriver(Oci8 $driver)
{
$this->driver = $driver;
return $this;
}
/**
* {@inheritDoc}
*/
public function getCurrentSchema()
{
if (! $this->isConnected()) {
$this->connect();
}
$query = "SELECT sys_context('USERENV', 'CURRENT_SCHEMA') as \"current_schema\" FROM DUAL";
$stmt = oci_parse($this->resource, $query);
oci_execute($stmt);
$dbNameArray = oci_fetch_array($stmt, OCI_ASSOC);
return $dbNameArray['current_schema'];
}
/**
* Set resource
*
* @param resource $resource
* @return $this Provides a fluent interface
*/
public function setResource($resource)
{
if (! is_resource($resource) || get_resource_type($resource) !== 'oci8 connection') {
throw new Exception\InvalidArgumentException('A resource of type "oci8 connection" was expected');
}
$this->resource = $resource;
return $this;
}
/**
* {@inheritDoc}
*/
public function connect()
{
if (is_resource($this->resource)) {
return $this;
}
// localize
$p = $this->connectionParameters;
// given a list of key names, test for existence in $p
$findParameterValue = function (array $names) use ($p) {
foreach ($names as $name) {
if (isset($p[$name])) {
return $p[$name];
}
}
return null;
};
// http://www.php.net/manual/en/function.oci-connect.php
$username = $findParameterValue(['username']);
$password = $findParameterValue(['password']);
$connectionString = $findParameterValue([
'connection_string',
'connectionstring',
'connection',
'hostname',
'instance',
]);
$characterSet = $findParameterValue(['character_set', 'charset', 'encoding']);
$sessionMode = $findParameterValue(['session_mode']);
// connection modifiers
$isUnique = $findParameterValue(['unique']);
$isPersistent = $findParameterValue(['persistent']);
if ($isUnique === true) {
$this->resource = oci_new_connect($username, $password, $connectionString, $characterSet, $sessionMode);
} elseif ($isPersistent === true) {
$this->resource = oci_pconnect($username, $password, $connectionString, $characterSet, $sessionMode);
} else {
$this->resource = oci_connect($username, $password, $connectionString, $characterSet, $sessionMode);
}
if (! $this->resource) {
$e = oci_error();
throw new Exception\RuntimeException(
'Connection error',
$e['code'],
new Exception\ErrorException($e['message'], $e['code'])
);
}
return $this;
}
/**
* {@inheritDoc}
*/
public function isConnected()
{
return is_resource($this->resource);
}
/**
* {@inheritDoc}
*/
public function disconnect()
{
if (is_resource($this->resource)) {
oci_close($this->resource);
}
}
/**
* {@inheritDoc}
*/
public function beginTransaction()
{
if (! $this->isConnected()) {
$this->connect();
}
// A transaction begins when the first SQL statement that changes data is executed with oci_execute() using
// the OCI_NO_AUTO_COMMIT flag.
$this->inTransaction = true;
return $this;
}
/**
* {@inheritDoc}
*/
public function commit()
{
if (! $this->isConnected()) {
$this->connect();
}
if ($this->inTransaction()) {
$valid = oci_commit($this->resource);
if ($valid === false) {
$e = oci_error($this->resource);
throw new Exception\InvalidQueryException($e['message'], $e['code']);
}
$this->inTransaction = false;
}
return $this;
}
/**
* {@inheritDoc}
*/
public function rollback()
{
if (! $this->isConnected()) {
throw new Exception\RuntimeException('Must be connected before you can rollback.');
}
if (! $this->inTransaction()) {
throw new Exception\RuntimeException('Must call commit() before you can rollback.');
}
$valid = oci_rollback($this->resource);
if ($valid === false) {
$e = oci_error($this->resource);
throw new Exception\InvalidQueryException($e['message'], $e['code']);
}
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*/
public function execute($sql)
{
if (! $this->isConnected()) {
$this->connect();
}
if ($this->profiler) {
$this->profiler->profilerStart($sql);
}
$ociStmt = oci_parse($this->resource, $sql);
if ($this->inTransaction) {
$valid = @oci_execute($ociStmt, OCI_NO_AUTO_COMMIT);
} else {
$valid = @oci_execute($ociStmt, OCI_COMMIT_ON_SUCCESS);
}
if ($this->profiler) {
$this->profiler->profilerFinish($sql);
}
if ($valid === false) {
$e = oci_error($ociStmt);
throw new Exception\InvalidQueryException($e['message'], $e['code']);
}
return $this->driver->createResult($ociStmt);
}
/**
* @todo Get Last Generated Value in Connection (this might not apply)
* {@inheritDoc}
*/
public function getLastGeneratedValue($name = null)
{
return null;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Oci8/Result.php | src/Adapter/Driver/Oci8/Result.php | <?php
namespace Laminas\Db\Adapter\Driver\Oci8;
use Iterator;
use Laminas\Db\Adapter\Driver\ResultInterface;
use Laminas\Db\Adapter\Exception;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use ReturnTypeWillChange;
use function call_user_func;
use function get_resource_type;
use function is_callable;
use function is_int;
use function is_resource;
class Result implements Iterator, ResultInterface
{
/** @var resource */
protected $resource;
/** @var null|int */
protected $rowCount;
/**
* Cursor position
*
* @var int
*/
protected $position = 0;
/**
* Number of known rows
*
* @var int
*/
protected $numberOfRows = -1;
/**
* Is the current() operation already complete for this pointer position?
*
* @var bool
*/
protected $currentComplete = false;
/** @var bool|array */
protected $currentData = false;
/** @var array */
protected $statementBindValues = ['keys' => null, 'values' => []];
/** @var mixed */
protected $generatedValue;
/**
* Initialize
*
* @param resource $resource
* @param null|int $generatedValue
* @param null|int $rowCount
* @return $this Provides a fluent interface
*/
public function initialize($resource, $generatedValue = null, $rowCount = null)
{
if (! is_resource($resource) && get_resource_type($resource) !== 'oci8 statement') {
throw new Exception\InvalidArgumentException('Invalid resource provided.');
}
$this->resource = $resource;
$this->generatedValue = $generatedValue;
$this->rowCount = $rowCount;
return $this;
}
/**
* Force buffering at driver level
*
* Oracle does not support this, to my knowledge (@ralphschindler)
*
* @return null
*/
public function buffer()
{
return null;
}
/**
* Is the result buffered?
*
* @return bool
*/
public function isBuffered()
{
return false;
}
/**
* Return the resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Is query result?
*
* @return bool
*/
public function isQueryResult()
{
return oci_num_fields($this->resource) > 0;
}
/**
* Get affected rows
*
* @return int
*/
public function getAffectedRows()
{
return oci_num_rows($this->resource);
}
/** @return mixed */
#[ReturnTypeWillChange]
public function current()
{
if ($this->currentComplete === false) {
if ($this->loadData() === false) {
return false;
}
}
return $this->currentData;
}
/**
* Load from oci8 result
*
* @return bool
*/
protected function loadData()
{
$this->currentComplete = true;
$this->currentData = oci_fetch_assoc($this->resource);
if ($this->currentData !== false) {
$this->position++;
return true;
}
return false;
}
/** @return void */
#[ReturnTypeWillChange]
public function next()
{
$this->loadData();
}
/** @return int|string */
#[ReturnTypeWillChange]
public function key()
{
return $this->position;
}
/** @return void */
#[ReturnTypeWillChange]
public function rewind()
{
if ($this->position > 0) {
throw new Exception\RuntimeException('Oci8 results cannot be rewound for multiple iterations');
}
}
/** @return bool */
#[ReturnTypeWillChange]
public function valid()
{
if ($this->currentComplete) {
return $this->currentData !== false;
}
return $this->loadData();
}
/** @return int */
#[ReturnTypeWillChange]
public function count()
{
if (is_int($this->rowCount)) {
return $this->rowCount;
}
if (is_callable($this->rowCount)) {
$this->rowCount = (int) call_user_func($this->rowCount);
return $this->rowCount;
}
return 0;
}
/**
* @return int
*/
public function getFieldCount()
{
return oci_num_fields($this->resource);
}
/**
* @todo OCI8 generated value in Driver Result
* @return null
*/
public function getGeneratedValue()
{
return null;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Oci8/Statement.php | src/Adapter/Driver/Oci8/Statement.php | <?php
namespace Laminas\Db\Adapter\Driver\Oci8;
use Laminas\Db\Adapter\Driver\StatementInterface;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Profiler;
use function is_array;
use function is_string;
use function oci_bind_by_name;
use function oci_error;
use function oci_execute;
use function oci_new_descriptor;
use function oci_parse;
use function oci_statement_type;
use function sprintf;
use const OCI_B_CLOB;
use const OCI_COMMIT_ON_SUCCESS;
use const OCI_DTYPE_LOB;
use const OCI_NO_AUTO_COMMIT;
use const OCI_TEMP_CLOB;
use const SQLT_BIN;
use const SQLT_CHR;
use const SQLT_INT;
class Statement implements StatementInterface, Profiler\ProfilerAwareInterface
{
/** @var resource */
protected $oci8;
/** @var Oci8 */
protected $driver;
/** @var Profiler\ProfilerInterface */
protected $profiler;
/** @var string */
protected $sql = '';
/**
* Parameter container
*
* @var ParameterContainer
*/
protected $parameterContainer;
/** @var resource */
protected $resource;
/**
* @internal
* @deprecated
*
* @var bool
*/
public $parametersBound;
/**
* Is prepared
*
* @var bool
*/
protected $isPrepared = false;
/** @var bool */
protected $bufferResults = false;
/**
* Set driver
*
* @param Oci8 $driver
* @return $this Provides a fluent interface
*/
public function setDriver($driver)
{
$this->driver = $driver;
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Initialize
*
* @param resource $oci8
* @return $this Provides a fluent interface
*/
public function initialize($oci8)
{
$this->oci8 = $oci8;
return $this;
}
/**
* Set sql
*
* @param string $sql
* @return $this Provides a fluent interface
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Set Parameter container
*
* @return $this Provides a fluent interface
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* Get resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Set resource
*
* @param resource $oci8Statement
* @return $this Provides a fluent interface
*/
public function setResource($oci8Statement)
{
$type = oci_statement_type($oci8Statement);
if (false === $type || 'UNKNOWN' === $type) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid statement provided to %s',
__METHOD__
));
}
$this->resource = $oci8Statement;
$this->isPrepared = true;
return $this;
}
/**
* Get sql
*
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* @return ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* @return bool
*/
public function isPrepared()
{
return $this->isPrepared;
}
/**
* @param string $sql
* @return $this Provides a fluent interface
*/
public function prepare($sql = null)
{
if ($this->isPrepared) {
throw new Exception\RuntimeException('This statement has already been prepared');
}
$sql = $sql ?: $this->sql;
// get oci8 statement resource
$this->resource = oci_parse($this->oci8, $sql);
if (! $this->resource) {
$e = oci_error($this->oci8);
throw new Exception\InvalidQueryException(
'Statement couldn\'t be produced with sql: ' . $sql,
$e['code'],
new Exception\ErrorException($e['message'], $e['code'])
);
}
$this->isPrepared = true;
return $this;
}
/**
* Execute
*
* @param null|array|ParameterContainer $parameters
* @return mixed
*/
public function execute($parameters = null)
{
if (! $this->isPrepared) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (! $this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
if ($this->parameterContainer->count() > 0) {
$this->bindParametersFromContainer();
}
/** END Standard ParameterContainer Merging Block */
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
if ($this->driver->getConnection()->inTransaction()) {
$ret = @oci_execute($this->resource, OCI_NO_AUTO_COMMIT);
} else {
$ret = @oci_execute($this->resource, OCI_COMMIT_ON_SUCCESS);
}
if ($this->profiler) {
$this->profiler->profilerFinish();
}
if ($ret === false) {
$e = oci_error($this->resource);
throw new Exception\RuntimeException($e['message'], $e['code']);
}
return $this->driver->createResult($this->resource, $this);
}
/**
* Bind parameters from container
*/
protected function bindParametersFromContainer()
{
$parameters = $this->parameterContainer->getNamedArray();
foreach ($parameters as $name => &$value) {
if ($this->parameterContainer->offsetHasErrata($name)) {
switch ($this->parameterContainer->offsetGetErrata($name)) {
case ParameterContainer::TYPE_NULL:
$type = null;
$value = null;
break;
case ParameterContainer::TYPE_DOUBLE:
case ParameterContainer::TYPE_INTEGER:
$type = SQLT_INT;
if (is_string($value)) {
$value = (int) $value;
}
break;
case ParameterContainer::TYPE_BINARY:
$type = SQLT_BIN;
break;
case ParameterContainer::TYPE_LOB:
$type = OCI_B_CLOB;
$clob = oci_new_descriptor($this->driver->getConnection()->getResource(), OCI_DTYPE_LOB);
$clob->writetemporary($value, OCI_TEMP_CLOB);
$value = $clob;
break;
case ParameterContainer::TYPE_STRING:
default:
$type = SQLT_CHR;
break;
}
} else {
$type = SQLT_CHR;
}
$maxLength = -1;
if ($this->parameterContainer->offsetHasMaxLength($name)) {
$maxLength = $this->parameterContainer->offsetGetMaxLength($name);
}
oci_bind_by_name($this->resource, $name, $value, $maxLength, $type);
}
}
/**
* Perform a deep clone
*/
public function __clone()
{
$this->isPrepared = false;
$this->parametersBound = false;
$this->resource = null;
if ($this->parameterContainer) {
$this->parameterContainer = clone $this->parameterContainer;
}
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Oci8/Oci8.php | src/Adapter/Driver/Oci8/Oci8.php | <?php
namespace Laminas\Db\Adapter\Driver\Oci8;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Driver\Feature\AbstractFeature;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Profiler;
use function array_intersect_key;
use function array_merge;
use function extension_loaded;
use function get_resource_type;
use function is_array;
use function is_resource;
use function is_string;
class Oci8 implements DriverInterface, Profiler\ProfilerAwareInterface
{
public const FEATURES_DEFAULT = 'default';
/** @var Connection */
protected $connection;
/** @var Statement */
protected $statementPrototype;
/** @var Result */
protected $resultPrototype;
/** @var Profiler\ProfilerInterface */
protected $profiler;
/** @var array */
protected $options = [];
/** @var array */
protected $features = [];
/**
* @param array|Connection|\oci8 $connection
* @param array $options
* @param string $features
*/
public function __construct(
$connection,
?Statement $statementPrototype = null,
?Result $resultPrototype = null,
array $options = [],
$features = self::FEATURES_DEFAULT
) {
if (! $connection instanceof Connection) {
$connection = new Connection($connection);
}
$options = array_intersect_key(array_merge($this->options, $options), $this->options);
$this->registerConnection($connection);
$this->registerStatementPrototype($statementPrototype ?: new Statement());
$this->registerResultPrototype($resultPrototype ?: new Result());
if (is_array($features)) {
foreach ($features as $name => $feature) {
$this->addFeature($name, $feature);
}
} elseif ($features instanceof AbstractFeature) {
$this->addFeature($features->getName(), $features);
} elseif ($features === self::FEATURES_DEFAULT) {
$this->setupDefaultFeatures();
}
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
if ($this->connection instanceof Profiler\ProfilerAwareInterface) {
$this->connection->setProfiler($profiler);
}
if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) {
$this->statementPrototype->setProfiler($profiler);
}
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Register connection
*
* @return $this Provides a fluent interface
*/
public function registerConnection(Connection $connection)
{
$this->connection = $connection;
$this->connection->setDriver($this); // needs access to driver to createStatement()
return $this;
}
/**
* Register statement prototype
*
* @return $this Provides a fluent interface
*/
public function registerStatementPrototype(Statement $statementPrototype)
{
$this->statementPrototype = $statementPrototype;
$this->statementPrototype->setDriver($this); // needs access to driver to createResult()
return $this;
}
/**
* @return null|Statement
*/
public function getStatementPrototype()
{
return $this->statementPrototype;
}
/**
* Register result prototype
*
* @return $this Provides a fluent interface
*/
public function registerResultPrototype(Result $resultPrototype)
{
$this->resultPrototype = $resultPrototype;
return $this;
}
/**
* @return null|Result
*/
public function getResultPrototype()
{
return $this->resultPrototype;
}
/**
* Add feature
*
* @param string $name
* @param AbstractFeature $feature
* @return $this Provides a fluent interface
*/
public function addFeature($name, $feature)
{
if ($feature instanceof AbstractFeature) {
$name = $feature->getName(); // overwrite the name, just in case
$feature->setDriver($this);
}
$this->features[$name] = $feature;
return $this;
}
/**
* Setup the default features for Pdo
*
* @return $this Provides a fluent interface
*/
public function setupDefaultFeatures()
{
$this->addFeature(null, new Feature\RowCounter());
return $this;
}
/**
* Get feature
*
* @param string $name
* @return AbstractFeature|false
*/
public function getFeature($name)
{
if (isset($this->features[$name])) {
return $this->features[$name];
}
return false;
}
/**
* Get database platform name
*
* @param string $nameFormat
* @return string
*/
public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE)
{
return 'Oracle';
}
/**
* Check environment
*/
public function checkEnvironment()
{
if (! extension_loaded('oci8')) {
throw new Exception\RuntimeException(
'The Oci8 extension is required for this adapter but the extension is not loaded'
);
}
}
/**
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* @param string $sqlOrResource
* @return Statement
*/
public function createStatement($sqlOrResource = null)
{
$statement = clone $this->statementPrototype;
if (is_resource($sqlOrResource) && get_resource_type($sqlOrResource) === 'oci8 statement') {
$statement->setResource($sqlOrResource);
} else {
if (is_string($sqlOrResource)) {
$statement->setSql($sqlOrResource);
} elseif ($sqlOrResource !== null) {
throw new Exception\InvalidArgumentException(
'Oci8 only accepts an SQL string or an oci8 resource in ' . __FUNCTION__
);
}
if (! $this->connection->isConnected()) {
$this->connection->connect();
}
$statement->initialize($this->connection->getResource());
}
return $statement;
}
/**
* @param resource $resource
* @param null $context
* @return Result
*/
public function createResult($resource, $context = null)
{
$result = clone $this->resultPrototype;
$rowCount = null;
// special feature, oracle Oci counter
if ($context && ($rowCounter = $this->getFeature('RowCounter')) && oci_num_fields($resource) > 0) {
$rowCount = $rowCounter->getRowCountClosure($context);
}
$result->initialize($resource, null, $rowCount);
return $result;
}
/**
* @return string
*/
public function getPrepareType()
{
return self::PARAMETERIZATION_NAMED;
}
/**
* @param string $name
* @param mixed $type
* @return string
*/
public function formatParameterName($name, $type = null)
{
return ':' . $name;
}
/**
* @return mixed
*/
public function getLastGeneratedValue()
{
return $this->getConnection()->getLastGeneratedValue();
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Oci8/Feature/RowCounter.php | src/Adapter/Driver/Oci8/Feature/RowCounter.php | <?php
namespace Laminas\Db\Adapter\Driver\Oci8\Feature;
use Laminas\Db\Adapter\Driver\Feature\AbstractFeature;
use Laminas\Db\Adapter\Driver\Oci8\Statement;
use function stripos;
use function strtolower;
/**
* Class for count of results of a select
*/
class RowCounter extends AbstractFeature
{
/**
* @return string
*/
public function getName()
{
return 'RowCounter';
}
/**
* @return null|int
*/
public function getCountForStatement(Statement $statement)
{
$countStmt = clone $statement;
$sql = $statement->getSql();
if ($sql === '' || stripos(strtolower($sql), 'select') === false) {
return;
}
$countSql = 'SELECT COUNT(*) as "count" FROM (' . $sql . ')';
$countStmt->prepare($countSql);
$result = $countStmt->execute();
$countRow = $result->current();
return $countRow['count'];
}
/**
* @param string $sql
* @return null|int
*/
public function getCountForSql($sql)
{
if (stripos(strtolower($sql), 'select') === false) {
return;
}
$countSql = 'SELECT COUNT(*) as "count" FROM (' . $sql . ')';
$result = $this->driver->getConnection()->execute($countSql);
$countRow = $result->current();
return $countRow['count'];
}
/**
* @param Statement|string $context
* @return callable
*/
public function getRowCountClosure($context)
{
/** @var RowCounter $rowCounter */
$rowCounter = $this;
return function () use ($rowCounter, $context) {
return $context instanceof Statement
? $rowCounter->getCountForStatement($context)
: $rowCounter->getCountForSql($context);
};
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Pdo/Connection.php | src/Adapter/Driver/Pdo/Connection.php | <?php
namespace Laminas\Db\Adapter\Driver\Pdo;
use Laminas\Db\Adapter\Driver\AbstractConnection;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Exception\RunTimeException;
use PDOException;
use PDOStatement;
use function array_diff_key;
use function implode;
use function is_array;
use function is_int;
use function str_replace;
use function strpos;
use function strtolower;
use function substr;
class Connection extends AbstractConnection
{
/** @var Pdo */
protected $driver;
/** @var \PDO */
protected $resource;
/** @var string */
protected $dsn;
/**
* Constructor
*
* @param array|\PDO|null $connectionParameters
* @throws Exception\InvalidArgumentException
*/
public function __construct($connectionParameters = null)
{
if (is_array($connectionParameters)) {
$this->setConnectionParameters($connectionParameters);
} elseif ($connectionParameters instanceof \PDO) {
$this->setResource($connectionParameters);
} elseif (null !== $connectionParameters) {
throw new Exception\InvalidArgumentException(
'$connection must be an array of parameters, a PDO object or null'
);
}
}
/**
* Set driver
*
* @return $this Provides a fluent interface
*/
public function setDriver(Pdo $driver)
{
$this->driver = $driver;
return $this;
}
/**
* {@inheritDoc}
*/
public function setConnectionParameters(array $connectionParameters)
{
$this->connectionParameters = $connectionParameters;
if (isset($connectionParameters['dsn'])) {
$this->driverName = substr(
$connectionParameters['dsn'],
0,
strpos($connectionParameters['dsn'], ':')
);
} elseif (isset($connectionParameters['pdodriver'])) {
$this->driverName = strtolower($connectionParameters['pdodriver']);
} elseif (isset($connectionParameters['driver'])) {
$this->driverName = strtolower(substr(
str_replace(['-', '_', ' '], '', $connectionParameters['driver']),
3
));
}
}
/**
* Get the dsn string for this connection
*
* @throws RunTimeException
* @return string
*/
public function getDsn()
{
if (! $this->dsn) {
throw new Exception\RuntimeException(
'The DSN has not been set or constructed from parameters in connect() for this Connection'
);
}
return $this->dsn;
}
/**
* {@inheritDoc}
*/
public function getCurrentSchema()
{
if (! $this->isConnected()) {
$this->connect();
}
switch ($this->driverName) {
case 'mysql':
$sql = 'SELECT DATABASE()';
break;
case 'sqlite':
return 'main';
case 'sqlsrv':
case 'dblib':
$sql = 'SELECT SCHEMA_NAME()';
break;
case 'pgsql':
default:
$sql = 'SELECT CURRENT_SCHEMA';
break;
}
/** @var PDOStatement $result */
$result = $this->resource->query($sql);
if ($result instanceof PDOStatement) {
return $result->fetchColumn();
}
return false;
}
/**
* Set resource
*
* @return $this Provides a fluent interface
*/
public function setResource(\PDO $resource)
{
$this->resource = $resource;
$this->driverName = strtolower($this->resource->getAttribute(\PDO::ATTR_DRIVER_NAME));
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\InvalidConnectionParametersException
* @throws Exception\RuntimeException
*/
public function connect()
{
if ($this->resource) {
return $this;
}
$dsn = $username = $password = $hostname = $database = null;
$options = [];
foreach ($this->connectionParameters as $key => $value) {
switch (strtolower($key)) {
case 'dsn':
$dsn = $value;
break;
case 'driver':
$value = strtolower((string) $value);
if (strpos($value, 'pdo') === 0) {
$pdoDriver = str_replace(['-', '_', ' '], '', $value);
$pdoDriver = substr($pdoDriver, 3) ?: '';
}
break;
case 'pdodriver':
$pdoDriver = (string) $value;
break;
case 'user':
case 'username':
$username = (string) $value;
break;
case 'pass':
case 'password':
$password = (string) $value;
break;
case 'host':
case 'hostname':
$hostname = (string) $value;
break;
case 'port':
$port = (int) $value;
break;
case 'database':
case 'dbname':
$database = (string) $value;
break;
case 'charset':
$charset = (string) $value;
break;
case 'unix_socket':
$unixSocket = (string) $value;
break;
case 'version':
$version = (string) $value;
break;
case 'driver_options':
case 'options':
$value = (array) $value;
$options = array_diff_key($options, $value) + $value;
break;
default:
$options[$key] = $value;
break;
}
}
if (isset($hostname) && isset($unixSocket)) {
throw new Exception\InvalidConnectionParametersException(
'Ambiguous connection parameters, both hostname and unix_socket parameters were set',
$this->connectionParameters
);
}
if (! isset($dsn) && isset($pdoDriver)) {
$dsn = [];
switch ($pdoDriver) {
case 'sqlite':
$dsn[] = $database;
break;
case 'sqlsrv':
if (isset($database)) {
$dsn[] = "database={$database}";
}
if (isset($hostname)) {
$dsn[] = "server={$hostname}";
}
break;
default:
if (isset($database)) {
$dsn[] = "dbname={$database}";
}
if (isset($hostname)) {
$dsn[] = "host={$hostname}";
}
if (isset($port)) {
$dsn[] = "port={$port}";
}
if (isset($charset) && $pdoDriver !== 'pgsql') {
$dsn[] = "charset={$charset}";
}
if (isset($unixSocket)) {
$dsn[] = "unix_socket={$unixSocket}";
}
if (isset($version)) {
$dsn[] = "version={$version}";
}
break;
}
$dsn = $pdoDriver . ':' . implode(';', $dsn);
} elseif (! isset($dsn)) {
throw new Exception\InvalidConnectionParametersException(
'A dsn was not provided or could not be constructed from your parameters',
$this->connectionParameters
);
}
$this->dsn = $dsn;
try {
$this->resource = new \PDO($dsn, $username, $password, $options);
$this->resource->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
if (isset($charset) && $pdoDriver === 'pgsql') {
$this->resource->exec('SET NAMES ' . $this->resource->quote($charset));
}
$this->driverName = strtolower($this->resource->getAttribute(\PDO::ATTR_DRIVER_NAME));
} catch (PDOException $e) {
$code = $e->getCode();
if (! is_int($code)) {
$code = 0;
}
throw new Exception\RuntimeException('Connect Error: ' . $e->getMessage(), $code, $e);
}
return $this;
}
/**
* {@inheritDoc}
*/
public function isConnected()
{
return $this->resource instanceof \PDO;
}
/**
* {@inheritDoc}
*/
public function beginTransaction()
{
if (! $this->isConnected()) {
$this->connect();
}
if (0 === $this->nestedTransactionsCount) {
$this->resource->beginTransaction();
$this->inTransaction = true;
}
$this->nestedTransactionsCount++;
return $this;
}
/**
* {@inheritDoc}
*/
public function commit()
{
if (! $this->isConnected()) {
$this->connect();
}
if ($this->inTransaction) {
$this->nestedTransactionsCount -= 1;
}
/*
* This shouldn't check for being in a transaction since
* after issuing a SET autocommit=0; we have to commit too.
*/
if (0 === $this->nestedTransactionsCount) {
$this->resource->commit();
$this->inTransaction = false;
}
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\RuntimeException
*/
public function rollback()
{
if (! $this->isConnected()) {
throw new Exception\RuntimeException('Must be connected before you can rollback');
}
if (! $this->inTransaction()) {
throw new Exception\RuntimeException('Must call beginTransaction() before you can rollback');
}
$this->resource->rollBack();
$this->inTransaction = false;
$this->nestedTransactionsCount = 0;
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\InvalidQueryException
*/
public function execute($sql)
{
if (! $this->isConnected()) {
$this->connect();
}
if ($this->profiler) {
$this->profiler->profilerStart($sql);
}
$resultResource = $this->resource->query($sql);
if ($this->profiler) {
$this->profiler->profilerFinish($sql);
}
if ($resultResource === false) {
$errorInfo = $this->resource->errorInfo();
throw new Exception\InvalidQueryException($errorInfo[2]);
}
return $this->driver->createResult($resultResource, $sql);
}
/**
* Prepare
*
* @param string $sql
* @return Statement
*/
public function prepare($sql)
{
if (! $this->isConnected()) {
$this->connect();
}
return $this->driver->createStatement($sql);
}
/**
* {@inheritDoc}
*
* @param string $name
* @return string|null|false
*/
public function getLastGeneratedValue($name = null)
{
if (
$name === null
&& ($this->driverName === 'pgsql' || $this->driverName === 'firebird')
) {
return;
}
try {
return $this->resource->lastInsertId($name);
} catch (\Exception $e) {
// do nothing
}
return false;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Pdo/Result.php | src/Adapter/Driver/Pdo/Result.php | <?php
namespace Laminas\Db\Adapter\Driver\Pdo;
use Closure;
use Iterator;
use Laminas\Db\Adapter\Driver\ResultInterface;
use Laminas\Db\Adapter\Exception;
use PDO;
use PDOStatement;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use ReturnTypeWillChange;
use function call_user_func;
use function in_array;
use function is_int;
class Result implements Iterator, ResultInterface
{
public const STATEMENT_MODE_SCROLLABLE = 'scrollable';
public const STATEMENT_MODE_FORWARD = 'forward';
/** @var string */
protected $statementMode = self::STATEMENT_MODE_FORWARD;
/** @var int */
protected $fetchMode = PDO::FETCH_ASSOC;
/**
* @internal
*
* @var array
*/
public const VALID_FETCH_MODES = [
PDO::FETCH_LAZY, // 1
PDO::FETCH_ASSOC, // 2
PDO::FETCH_NUM, // 3
PDO::FETCH_BOTH, // 4
PDO::FETCH_OBJ, // 5
PDO::FETCH_BOUND, // 6
// \PDO::FETCH_COLUMN, // 7 (not a valid fetch mode)
PDO::FETCH_CLASS, // 8
PDO::FETCH_INTO, // 9
PDO::FETCH_FUNC, // 10
PDO::FETCH_NAMED, // 11
PDO::FETCH_KEY_PAIR, // 12
PDO::FETCH_PROPS_LATE, // Extra option for \PDO::FETCH_CLASS
// \PDO::FETCH_SERIALIZE, // Seems to have been removed
// \PDO::FETCH_UNIQUE, // Option for fetchAll
PDO::FETCH_CLASSTYPE, // Extra option for \PDO::FETCH_CLASS
];
/** @var PDOStatement */
protected $resource;
/** @var array Result options */
protected $options;
/**
* Is the current complete?
*
* @var bool
*/
protected $currentComplete = false;
/**
* Track current item in recordset
*
* @var mixed
*/
protected $currentData;
/**
* Current position of scrollable statement
*
* @var int
*/
protected $position = -1;
/** @var mixed */
protected $generatedValue;
/** @var null */
protected $rowCount;
/**
* Initialize
*
* @param mixed $generatedValue
* @param int $rowCount
* @return $this Provides a fluent interface
*/
public function initialize(PDOStatement $resource, $generatedValue, $rowCount = null)
{
$this->resource = $resource;
$this->generatedValue = $generatedValue;
$this->rowCount = $rowCount;
return $this;
}
/**
* @return void
*/
public function buffer()
{
}
/**
* @return bool|null
*/
public function isBuffered()
{
return false;
}
/**
* @param int $fetchMode
* @throws Exception\InvalidArgumentException On invalid fetch mode.
*/
public function setFetchMode($fetchMode)
{
if (! in_array($fetchMode, self::VALID_FETCH_MODES, true)) {
throw new Exception\InvalidArgumentException(
'The fetch mode must be one of the PDO::FETCH_* constants.'
);
}
$this->fetchMode = (int) $fetchMode;
}
/**
* @return int
*/
public function getFetchMode()
{
return $this->fetchMode;
}
/**
* Get resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Get the data
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function current()
{
if ($this->currentComplete) {
return $this->currentData;
}
$this->currentData = $this->resource->fetch($this->fetchMode);
$this->currentComplete = true;
return $this->currentData;
}
/**
* Next
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function next()
{
$this->currentData = $this->resource->fetch($this->fetchMode);
$this->currentComplete = true;
$this->position++;
return $this->currentData;
}
/**
* Key
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function key()
{
return $this->position;
}
/**
* @throws Exception\RuntimeException
* @return void
*/
#[ReturnTypeWillChange]
public function rewind()
{
if ($this->statementMode === self::STATEMENT_MODE_FORWARD && $this->position > 0) {
throw new Exception\RuntimeException(
'This result is a forward only result set, calling rewind() after moving forward is not supported'
);
}
if (! $this->currentComplete) {
$this->currentData = $this->resource->fetch($this->fetchMode);
$this->currentComplete = true;
}
$this->position = 0;
}
/**
* Valid
*
* @return bool
*/
#[ReturnTypeWillChange]
public function valid()
{
return $this->currentData !== false;
}
/**
* Count
*
* @return int
*/
#[ReturnTypeWillChange]
public function count()
{
if (is_int($this->rowCount)) {
return $this->rowCount;
}
if ($this->rowCount instanceof Closure) {
$this->rowCount = (int) call_user_func($this->rowCount);
} else {
$this->rowCount = (int) $this->resource->rowCount();
}
return $this->rowCount;
}
/**
* @return int
*/
public function getFieldCount()
{
return $this->resource->columnCount();
}
/**
* Is query result
*
* @return bool
*/
public function isQueryResult()
{
return $this->resource->columnCount() > 0;
}
/**
* Get affected rows
*
* @return int
*/
public function getAffectedRows()
{
return $this->resource->rowCount();
}
/**
* @return mixed|null
*/
public function getGeneratedValue()
{
return $this->generatedValue;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Pdo/Pdo.php | src/Adapter/Driver/Pdo/Pdo.php | <?php
namespace Laminas\Db\Adapter\Driver\Pdo;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Driver\Feature\AbstractFeature;
use Laminas\Db\Adapter\Driver\Feature\DriverFeatureInterface;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Profiler;
use PDOStatement;
use function extension_loaded;
use function is_array;
use function is_numeric;
use function is_string;
use function ltrim;
use function preg_match;
use function sprintf;
use function ucfirst;
class Pdo implements DriverInterface, DriverFeatureInterface, Profiler\ProfilerAwareInterface
{
/**
* @const
*/
public const FEATURES_DEFAULT = 'default';
/** @var Connection */
protected $connection;
/** @var Statement */
protected $statementPrototype;
/** @var Result */
protected $resultPrototype;
/** @var array */
protected $features = [];
/**
* @internal
*
* @var Profiler\ProfilerInterface
*/
public $profiler;
/**
* @param array|Connection|\PDO $connection
* @param string $features
*/
public function __construct(
$connection,
?Statement $statementPrototype = null,
?Result $resultPrototype = null,
$features = self::FEATURES_DEFAULT
) {
if (! $connection instanceof Connection) {
$connection = new Connection($connection);
}
$this->registerConnection($connection);
$this->registerStatementPrototype($statementPrototype ?: new Statement());
$this->registerResultPrototype($resultPrototype ?: new Result());
if (is_array($features)) {
foreach ($features as $name => $feature) {
$this->addFeature($name, $feature);
}
} elseif ($features instanceof AbstractFeature) {
$this->addFeature($features->getName(), $features);
} elseif ($features === self::FEATURES_DEFAULT) {
$this->setupDefaultFeatures();
}
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
if ($this->connection instanceof Profiler\ProfilerAwareInterface) {
$this->connection->setProfiler($profiler);
}
if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) {
$this->statementPrototype->setProfiler($profiler);
}
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Register connection
*
* @return $this Provides a fluent interface
*/
public function registerConnection(Connection $connection)
{
$this->connection = $connection;
$this->connection->setDriver($this);
return $this;
}
/**
* Register statement prototype
*/
public function registerStatementPrototype(Statement $statementPrototype)
{
$this->statementPrototype = $statementPrototype;
$this->statementPrototype->setDriver($this);
}
/**
* Register result prototype
*/
public function registerResultPrototype(Result $resultPrototype)
{
$this->resultPrototype = $resultPrototype;
}
/**
* Add feature
*
* @param string $name
* @param AbstractFeature $feature
* @return $this Provides a fluent interface
*/
public function addFeature($name, $feature)
{
if ($feature instanceof AbstractFeature) {
$name = $feature->getName(); // overwrite the name, just in case
$feature->setDriver($this);
}
$this->features[$name] = $feature;
return $this;
}
/**
* Setup the default features for Pdo
*
* @return $this Provides a fluent interface
*/
public function setupDefaultFeatures()
{
$driverName = $this->connection->getDriverName();
if ($driverName === 'sqlite') {
$this->addFeature(null, new Feature\SqliteRowCounter());
return $this;
}
if ($driverName === 'oci') {
$this->addFeature(null, new Feature\OracleRowCounter());
return $this;
}
return $this;
}
/**
* Get feature
*
* @param string $name
* @return AbstractFeature|false
*/
public function getFeature($name)
{
if (isset($this->features[$name])) {
return $this->features[$name];
}
return false;
}
/**
* Get database platform name
*
* @param string $nameFormat
* @return string
*/
public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE)
{
$name = $this->getConnection()->getDriverName();
if ($nameFormat === self::NAME_FORMAT_CAMELCASE) {
switch ($name) {
case 'pgsql':
return 'Postgresql';
case 'oci':
return 'Oracle';
case 'dblib':
case 'sqlsrv':
return 'SqlServer';
default:
return ucfirst($name);
}
} else {
switch ($name) {
case 'sqlite':
return 'SQLite';
case 'mysql':
return 'MySQL';
case 'pgsql':
return 'PostgreSQL';
case 'oci':
return 'Oracle';
case 'dblib':
case 'sqlsrv':
return 'SQLServer';
default:
return ucfirst($name);
}
}
}
/**
* Check environment
*/
public function checkEnvironment()
{
if (! extension_loaded('PDO')) {
throw new Exception\RuntimeException(
'The PDO extension is required for this adapter but the extension is not loaded'
);
}
}
/**
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* @param string|PDOStatement $sqlOrResource
* @return Statement
*/
public function createStatement($sqlOrResource = null)
{
$statement = clone $this->statementPrototype;
if ($sqlOrResource instanceof PDOStatement) {
$statement->setResource($sqlOrResource);
} else {
if (is_string($sqlOrResource)) {
$statement->setSql($sqlOrResource);
}
if (! $this->connection->isConnected()) {
$this->connection->connect();
}
$statement->initialize($this->connection->getResource());
}
return $statement;
}
/**
* @param resource $resource
* @param mixed $context
* @return Result
*/
public function createResult($resource, $context = null)
{
$result = clone $this->resultPrototype;
$rowCount = null;
// special feature, sqlite PDO counter
if (
$this->connection->getDriverName() === 'sqlite'
&& ($sqliteRowCounter = $this->getFeature('SqliteRowCounter'))
&& $resource->columnCount() > 0
) {
$rowCount = $sqliteRowCounter->getRowCountClosure($context);
}
// special feature, oracle PDO counter
if (
$this->connection->getDriverName() === 'oci'
&& ($oracleRowCounter = $this->getFeature('OracleRowCounter'))
&& $resource->columnCount() > 0
) {
$rowCount = $oracleRowCounter->getRowCountClosure($context);
}
$result->initialize($resource, $this->connection->getLastGeneratedValue(), $rowCount);
return $result;
}
/**
* @return Result
*/
public function getResultPrototype()
{
return $this->resultPrototype;
}
/**
* @return string
*/
public function getPrepareType()
{
return self::PARAMETERIZATION_NAMED;
}
/**
* @param string $name
* @param string|null $type
* @return string
*/
public function formatParameterName($name, $type = null)
{
if ($type === null && ! is_numeric($name) || $type === self::PARAMETERIZATION_NAMED) {
$name = ltrim($name, ':');
// @see https://bugs.php.net/bug.php?id=43130
if (preg_match('/[^a-zA-Z0-9_]/', $name)) {
throw new Exception\RuntimeException(sprintf(
'The PDO param %s contains invalid characters.'
. ' Only alphabetic characters, digits, and underscores (_)'
. ' are allowed.',
$name
));
}
return ':' . $name;
}
return '?';
}
/**
* @param string|null $name
* @return string|null|false
*/
public function getLastGeneratedValue($name = null)
{
return $this->connection->getLastGeneratedValue($name);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Pdo/Statement.php | src/Adapter/Driver/Pdo/Statement.php | <?php
namespace Laminas\Db\Adapter\Driver\Pdo;
use Laminas\Db\Adapter\Driver\StatementInterface;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Profiler;
use PDOException;
use PDOStatement;
use function implode;
use function is_array;
use function is_bool;
use function is_int;
class Statement implements StatementInterface, Profiler\ProfilerAwareInterface
{
/** @var \PDO */
protected $pdo;
/** @var Profiler\ProfilerInterface */
protected $profiler;
/** @var Pdo */
protected $driver;
/** @var string */
protected $sql = '';
/** @var bool */
protected $isQuery;
/** @var ParameterContainer */
protected $parameterContainer;
/** @var bool */
protected $parametersBound = false;
/** @var PDOStatement */
protected $resource;
/** @var bool */
protected $isPrepared = false;
/**
* Set driver
*
* @return $this Provides a fluent interface
*/
public function setDriver(Pdo $driver)
{
$this->driver = $driver;
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Initialize
*
* @return $this Provides a fluent interface
*/
public function initialize(\PDO $connectionResource)
{
$this->pdo = $connectionResource;
return $this;
}
/**
* Set resource
*
* @return $this Provides a fluent interface
*/
public function setResource(PDOStatement $pdoStatement)
{
$this->resource = $pdoStatement;
return $this;
}
/**
* Get resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Set sql
*
* @param string $sql
* @return $this Provides a fluent interface
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Get sql
*
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* @return $this Provides a fluent interface
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* @return ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* @param string $sql
* @throws Exception\RuntimeException
*/
public function prepare($sql = null)
{
if ($this->isPrepared) {
throw new Exception\RuntimeException('This statement has been prepared already');
}
if ($sql === null) {
$sql = $this->sql;
}
$this->resource = $this->pdo->prepare($sql);
if ($this->resource === false) {
$error = $this->pdo->errorInfo();
throw new Exception\RuntimeException($error[2]);
}
$this->isPrepared = true;
}
/**
* @return bool
*/
public function isPrepared()
{
return $this->isPrepared;
}
/**
* @param null|array|ParameterContainer $parameters
* @throws Exception\InvalidQueryException
* @return Result
*/
public function execute($parameters = null)
{
if (! $this->isPrepared) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (! $this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
if ($this->parameterContainer->count() > 0) {
$this->bindParametersFromContainer();
}
/** END Standard ParameterContainer Merging Block */
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
try {
$this->resource->execute();
} catch (PDOException $e) {
if ($this->profiler) {
$this->profiler->profilerFinish();
}
$code = $e->getCode();
if (! is_int($code)) {
$code = 0;
}
throw new Exception\InvalidQueryException(
'Statement could not be executed (' . implode(' - ', $this->resource->errorInfo()) . ')',
$code,
$e
);
}
if ($this->profiler) {
$this->profiler->profilerFinish();
}
return $this->driver->createResult($this->resource, $this);
}
/**
* Bind parameters from container
*/
protected function bindParametersFromContainer()
{
if ($this->parametersBound) {
return;
}
$parameters = $this->parameterContainer->getNamedArray();
foreach ($parameters as $name => &$value) {
if (is_bool($value)) {
$type = \PDO::PARAM_BOOL;
} elseif (is_int($value)) {
$type = \PDO::PARAM_INT;
} else {
$type = \PDO::PARAM_STR;
}
if ($this->parameterContainer->offsetHasErrata($name)) {
switch ($this->parameterContainer->offsetGetErrata($name)) {
case ParameterContainer::TYPE_INTEGER:
$type = \PDO::PARAM_INT;
break;
case ParameterContainer::TYPE_NULL:
$type = \PDO::PARAM_NULL;
break;
case ParameterContainer::TYPE_LOB:
$type = \PDO::PARAM_LOB;
break;
}
}
// parameter is named or positional, value is reference
$parameter = is_int($name) ? $name + 1 : $this->driver->formatParameterName($name);
$this->resource->bindParam($parameter, $value, $type);
}
}
/**
* Perform a deep clone
*
* @return void
*/
public function __clone()
{
$this->isPrepared = false;
$this->parametersBound = false;
$this->resource = null;
if ($this->parameterContainer) {
$this->parameterContainer = clone $this->parameterContainer;
}
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Pdo/Feature/OracleRowCounter.php | src/Adapter/Driver/Pdo/Feature/OracleRowCounter.php | <?php
namespace Laminas\Db\Adapter\Driver\Pdo\Feature;
use Closure;
use Laminas\Db\Adapter\Driver\Feature\AbstractFeature;
use Laminas\Db\Adapter\Driver\Pdo;
use function stripos;
/**
* OracleRowCounter
*/
class OracleRowCounter extends AbstractFeature
{
/**
* @return string
*/
public function getName()
{
return 'OracleRowCounter';
}
/**
* @return int
*/
public function getCountForStatement(Pdo\Statement $statement)
{
$countStmt = clone $statement;
$sql = $statement->getSql();
if ($sql === '' || stripos($sql, 'select') === false) {
return;
}
$countSql = 'SELECT COUNT(*) as "count" FROM (' . $sql . ')';
$countStmt->prepare($countSql);
$result = $countStmt->execute();
$countRow = $result->getResource()->fetch(\PDO::FETCH_ASSOC);
unset($statement, $result);
return $countRow['count'];
}
/**
* @param string $sql
* @return null|int
*/
public function getCountForSql($sql)
{
if (stripos($sql, 'select') === false) {
return;
}
$countSql = 'SELECT COUNT(*) as count FROM (' . $sql . ')';
/** @var \PDO $pdo */
$pdo = $this->driver->getConnection()->getResource();
$result = $pdo->query($countSql);
$countRow = $result->fetch(\PDO::FETCH_ASSOC);
return $countRow['count'];
}
/**
* @param Pdo\Statement|string $context
* @return Closure
*/
public function getRowCountClosure($context)
{
return function () use ($context) {
return $context instanceof Pdo\Statement
? $this->getCountForStatement($context)
: $this->getCountForSql($context);
};
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Pdo/Feature/SqliteRowCounter.php | src/Adapter/Driver/Pdo/Feature/SqliteRowCounter.php | <?php
namespace Laminas\Db\Adapter\Driver\Pdo\Feature;
use Closure;
use Laminas\Db\Adapter\Driver\Feature\AbstractFeature;
use Laminas\Db\Adapter\Driver\Pdo;
use function stripos;
/**
* SqliteRowCounter
*/
class SqliteRowCounter extends AbstractFeature
{
/**
* @return string
*/
public function getName()
{
return 'SqliteRowCounter';
}
/**
* @return int
*/
public function getCountForStatement(Pdo\Statement $statement)
{
$countStmt = clone $statement;
$sql = $statement->getSql();
if ($sql === '' || stripos($sql, 'select') === false) {
return;
}
$countSql = 'SELECT COUNT(*) as "count" FROM (' . $sql . ')';
$countStmt->prepare($countSql);
$result = $countStmt->execute();
$countRow = $result->getResource()->fetch(\PDO::FETCH_ASSOC);
unset($statement, $result);
return $countRow['count'];
}
/**
* @param string $sql
* @return null|int
*/
public function getCountForSql($sql)
{
if (stripos($sql, 'select') === false) {
return;
}
$countSql = 'SELECT COUNT(*) as count FROM (' . $sql . ')';
/** @var \PDO $pdo */
$pdo = $this->driver->getConnection()->getResource();
$result = $pdo->query($countSql);
$countRow = $result->fetch(\PDO::FETCH_ASSOC);
return $countRow['count'];
}
/**
* @param Pdo\Statement|string $context
* @return Closure
*/
public function getRowCountClosure($context)
{
return function () use ($context) {
return $context instanceof Pdo\Statement
? $this->getCountForStatement($context)
: $this->getCountForSql($context);
};
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/IbmDb2/IbmDb2.php | src/Adapter/Driver/IbmDb2/IbmDb2.php | <?php
namespace Laminas\Db\Adapter\Driver\IbmDb2;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Profiler;
use function extension_loaded;
use function get_resource_type;
use function is_resource;
use function is_string;
class IbmDb2 implements DriverInterface, Profiler\ProfilerAwareInterface
{
/** @var Connection */
protected $connection;
/** @var Statement */
protected $statementPrototype;
/** @var Result */
protected $resultPrototype;
/** @var Profiler\ProfilerInterface */
protected $profiler;
/**
* @param array|Connection|resource $connection
*/
public function __construct($connection, ?Statement $statementPrototype = null, ?Result $resultPrototype = null)
{
if (! $connection instanceof Connection) {
$connection = new Connection($connection);
}
$this->registerConnection($connection);
$this->registerStatementPrototype($statementPrototype ?: new Statement());
$this->registerResultPrototype($resultPrototype ?: new Result());
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
if ($this->connection instanceof Profiler\ProfilerAwareInterface) {
$this->connection->setProfiler($profiler);
}
if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) {
$this->statementPrototype->setProfiler($profiler);
}
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* @return $this Provides a fluent interface
*/
public function registerConnection(Connection $connection)
{
$this->connection = $connection;
$this->connection->setDriver($this);
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function registerStatementPrototype(Statement $statementPrototype)
{
$this->statementPrototype = $statementPrototype;
$this->statementPrototype->setDriver($this);
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function registerResultPrototype(Result $resultPrototype)
{
$this->resultPrototype = $resultPrototype;
return $this;
}
/**
* Get database platform name
*
* @param string $nameFormat
* @return string
*/
public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE)
{
return $nameFormat === self::NAME_FORMAT_CAMELCASE
? 'IbmDb2'
: 'IBM DB2';
}
/**
* Check environment
*
* @return void
*/
public function checkEnvironment()
{
if (! extension_loaded('ibm_db2')) {
throw new Exception\RuntimeException('The ibm_db2 extension is required by this driver.');
}
}
/**
* Get connection
*
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* Create statement
*
* @param string|resource $sqlOrResource
* @return Statement
*/
public function createStatement($sqlOrResource = null)
{
$statement = clone $this->statementPrototype;
if (is_resource($sqlOrResource) && get_resource_type($sqlOrResource) === 'DB2 Statement') {
$statement->setResource($sqlOrResource);
} else {
if (is_string($sqlOrResource)) {
$statement->setSql($sqlOrResource);
} elseif ($sqlOrResource !== null) {
throw new Exception\InvalidArgumentException(
__FUNCTION__ . ' only accepts an SQL string or an ibm_db2 resource'
);
}
if (! $this->connection->isConnected()) {
$this->connection->connect();
}
$statement->initialize($this->connection->getResource());
}
return $statement;
}
/**
* Create result
*
* @param resource $resource
* @return Result
*/
public function createResult($resource)
{
$result = clone $this->resultPrototype;
$result->initialize($resource, $this->connection->getLastGeneratedValue());
return $result;
}
/**
* @return Result
*/
public function getResultPrototype()
{
return $this->resultPrototype;
}
/**
* Get prepare type
*
* @return string
*/
public function getPrepareType()
{
return self::PARAMETERIZATION_POSITIONAL;
}
/**
* Format parameter name
*
* @param string $name
* @param mixed $type
* @return string
*/
public function formatParameterName($name, $type = null)
{
return '?';
}
/**
* Get last generated value
*
* @return mixed
*/
public function getLastGeneratedValue()
{
return $this->connection->getLastGeneratedValue();
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/IbmDb2/Connection.php | src/Adapter/Driver/IbmDb2/Connection.php | <?php
namespace Laminas\Db\Adapter\Driver\IbmDb2;
use Laminas\Db\Adapter\Driver\AbstractConnection;
use Laminas\Db\Adapter\Exception;
use function get_resource_type;
use function ini_get;
use function is_array;
use function is_resource;
use function php_uname;
use function restore_error_handler;
use function set_error_handler;
use function sprintf;
use const E_WARNING;
class Connection extends AbstractConnection
{
/** @var IbmDb2 */
protected $driver;
/**
* i5 OS
*
* @var bool
*/
protected $i5;
/**
* Previous autocommit set
*
* @var mixed
*/
protected $prevAutocommit;
/**
* Constructor
*
* @param array|resource|null $connectionParameters (ibm_db2 connection resource)
* @throws Exception\InvalidArgumentException
*/
public function __construct($connectionParameters = null)
{
if (is_array($connectionParameters)) {
$this->setConnectionParameters($connectionParameters);
} elseif (is_resource($connectionParameters)) {
$this->setResource($connectionParameters);
} elseif (null !== $connectionParameters) {
throw new Exception\InvalidArgumentException(
'$connection must be an array of parameters, a db2 connection resource or null'
);
}
}
/**
* Set driver
*
* @return $this Provides a fluent interface
*/
public function setDriver(IbmDb2 $driver)
{
$this->driver = $driver;
return $this;
}
/**
* @param resource $resource DB2 resource
* @return $this Provides a fluent interface
*/
public function setResource($resource)
{
if (! is_resource($resource) || get_resource_type($resource) !== 'DB2 Connection') {
throw new Exception\InvalidArgumentException('The resource provided must be of type "DB2 Connection"');
}
$this->resource = $resource;
return $this;
}
/**
* {@inheritDoc}
*/
public function getCurrentSchema()
{
if (! $this->isConnected()) {
$this->connect();
}
$info = db2_server_info($this->resource);
return $info->DB_NAME ?? '';
}
/**
* {@inheritDoc}
*/
public function connect()
{
if (is_resource($this->resource)) {
return $this;
}
// localize
$p = $this->connectionParameters;
// given a list of key names, test for existence in $p
$findParameterValue = function (array $names) use ($p) {
foreach ($names as $name) {
if (isset($p[$name])) {
return $p[$name];
}
}
return null;
};
$database = $findParameterValue(['database', 'db']);
$username = $findParameterValue(['username', 'uid', 'UID']);
$password = $findParameterValue(['password', 'pwd', 'PWD']);
$isPersistent = $findParameterValue(['persistent', 'PERSISTENT', 'Persistent']);
$options = $p['driver_options'] ?? [];
$connect = (bool) $isPersistent ? 'db2_pconnect' : 'db2_connect';
$this->resource = $connect($database, $username, $password, $options);
if ($this->resource === false) {
throw new Exception\RuntimeException(sprintf(
'%s: Unable to connect to database',
__METHOD__
));
}
return $this;
}
/**
* {@inheritDoc}
*/
public function isConnected()
{
return $this->resource !== null;
}
/**
* {@inheritDoc}
*/
public function disconnect()
{
if ($this->resource) {
db2_close($this->resource);
$this->resource = null;
}
return $this;
}
/**
* {@inheritDoc}
*/
public function beginTransaction()
{
if ($this->isI5() && ! ini_get('ibm_db2.i5_allow_commit')) {
throw new Exception\RuntimeException(
'DB2 transactions are not enabled, you need to set the ibm_db2.i5_allow_commit=1 in your php.ini'
);
}
if (! $this->isConnected()) {
$this->connect();
}
$this->prevAutocommit = db2_autocommit($this->resource);
db2_autocommit($this->resource, DB2_AUTOCOMMIT_OFF);
$this->inTransaction = true;
return $this;
}
/**
* {@inheritDoc}
*/
public function commit()
{
if (! $this->isConnected()) {
$this->connect();
}
if (! db2_commit($this->resource)) {
throw new Exception\RuntimeException("The commit has not been successful");
}
if ($this->prevAutocommit) {
db2_autocommit($this->resource, $this->prevAutocommit);
}
$this->inTransaction = false;
return $this;
}
/**
* Rollback
*
* @return $this Provides a fluent interface
* @throws Exception\RuntimeException
*/
public function rollback()
{
if (! $this->isConnected()) {
throw new Exception\RuntimeException('Must be connected before you can rollback.');
}
if (! $this->inTransaction()) {
throw new Exception\RuntimeException('Must call beginTransaction() before you can rollback.');
}
if (! db2_rollback($this->resource)) {
throw new Exception\RuntimeException('The rollback has not been successful');
}
if ($this->prevAutocommit) {
db2_autocommit($this->resource, $this->prevAutocommit);
}
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*/
public function execute($sql)
{
if (! $this->isConnected()) {
$this->connect();
}
if ($this->profiler) {
$this->profiler->profilerStart($sql);
}
set_error_handler(function () {
}, E_WARNING); // suppress warnings
$resultResource = db2_exec($this->resource, $sql);
restore_error_handler();
if ($this->profiler) {
$this->profiler->profilerFinish($sql);
}
// if the returnValue is something other than a pg result resource, bypass wrapping it
if ($resultResource === false) {
throw new Exception\InvalidQueryException(db2_stmt_errormsg());
}
return $this->driver->createResult($resultResource === true ? $this->resource : $resultResource);
}
/**
* {@inheritDoc}
*/
public function getLastGeneratedValue($name = null)
{
return db2_last_insert_id($this->resource);
}
/**
* Determine if the OS is OS400 (AS400, IBM i)
*
* @return bool
*/
protected function isI5()
{
if (isset($this->i5)) {
return $this->i5;
}
$this->i5 = php_uname('s') === 'OS400';
return $this->i5;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/IbmDb2/Result.php | src/Adapter/Driver/IbmDb2/Result.php | <?php
namespace Laminas\Db\Adapter\Driver\IbmDb2;
use Laminas\Db\Adapter\Driver\ResultInterface;
use Laminas\Db\Adapter\Exception;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use ReturnTypeWillChange;
class Result implements ResultInterface
{
/** @var resource */
protected $resource;
/** @var int */
protected $position = 0;
/** @var bool */
protected $currentComplete = false;
/** @var mixed */
protected $currentData;
/** @var mixed */
protected $generatedValue;
/**
* @param resource $resource
* @param mixed $generatedValue
* @return $this Provides a fluent interface
*/
public function initialize($resource, $generatedValue = null)
{
$this->resource = $resource;
$this->generatedValue = $generatedValue;
return $this;
}
/**
* (PHP 5 >= 5.0.0)<br/>
* Return the current element
*
* @link http://php.net/manual/en/iterator.current.php
*
* @return mixed Can return any type.
*/
#[ReturnTypeWillChange]
public function current()
{
if ($this->currentComplete) {
return $this->currentData;
}
$this->currentData = db2_fetch_assoc($this->resource);
return $this->currentData;
}
/**
* @return mixed
*/
#[ReturnTypeWillChange]
public function next()
{
$this->currentData = db2_fetch_assoc($this->resource);
$this->currentComplete = true;
$this->position++;
return $this->currentData;
}
/**
* @return int|string
*/
#[ReturnTypeWillChange]
public function key()
{
return $this->position;
}
/**
* @return bool
*/
#[ReturnTypeWillChange]
public function valid()
{
return $this->currentData !== false;
}
/**
* (PHP 5 >= 5.0.0)<br/>
* Rewind the Iterator to the first element
*
* @link http://php.net/manual/en/iterator.rewind.php
*
* @return void Any returned value is ignored.
*/
#[ReturnTypeWillChange]
public function rewind()
{
if ($this->position > 0) {
throw new Exception\RuntimeException(
'This result is a forward only result set, calling rewind() after moving forward is not supported'
);
}
$this->currentData = db2_fetch_assoc($this->resource);
$this->currentComplete = true;
$this->position = 1;
}
/**
* Force buffering
*
* @return null
*/
public function buffer()
{
return null;
}
/**
* Check if is buffered
*
* @return bool|null
*/
public function isBuffered()
{
return false;
}
/**
* Is query result?
*
* @return bool
*/
public function isQueryResult()
{
return db2_num_fields($this->resource) > 0;
}
/**
* Get affected rows
*
* @return int
*/
public function getAffectedRows()
{
return db2_num_rows($this->resource);
}
/**
* Get generated value
*
* @return mixed|null
*/
public function getGeneratedValue()
{
return $this->generatedValue;
}
/**
* Get the resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Get field count
*
* @return int
*/
public function getFieldCount()
{
return db2_num_fields($this->resource);
}
/**
* @return int
*/
#[ReturnTypeWillChange]
public function count()
{
return 0;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/IbmDb2/Statement.php | src/Adapter/Driver/IbmDb2/Statement.php | <?php
namespace Laminas\Db\Adapter\Driver\IbmDb2;
use ErrorException;
use Laminas\Db\Adapter\Driver\StatementInterface;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Exception\InvalidArgumentException;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Profiler;
use function error_reporting;
use function get_resource_type;
use function is_array;
use function restore_error_handler;
use function set_error_handler;
use const E_WARNING;
class Statement implements StatementInterface, Profiler\ProfilerAwareInterface
{
/** @var resource */
protected $db2;
/** @var IbmDb2 */
protected $driver;
/** @var Profiler\ProfilerInterface */
protected $profiler;
/** @var string */
protected $sql = '';
/** @var ParameterContainer */
protected $parameterContainer;
/** @var bool */
protected $isPrepared = false;
/** @var resource */
protected $resource;
/**
* @param resource $resource
* @return $this Provides a fluent interface
*/
public function initialize($resource)
{
$this->db2 = $resource;
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function setDriver(IbmDb2 $driver)
{
$this->driver = $driver;
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Set sql
*
* @param null|string $sql
* @return $this Provides a fluent interface
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Get sql
*
* @return null|string
*/
public function getSql()
{
return $this->sql;
}
/**
* Set parameter container
*
* @return $this Provides a fluent interface
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* Get parameter container
*
* @return mixed
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* @param resource $resource
* @throws InvalidArgumentException
*/
public function setResource($resource)
{
if (get_resource_type($resource) !== 'DB2 Statement') {
throw new Exception\InvalidArgumentException('Resource must be of type DB2 Statement');
}
$this->resource = $resource;
}
/**
* Get resource
*
* @return resource
*/
public function getResource()
{
return $this->resource;
}
/**
* Prepare sql
*
* @param string|null $sql
* @return $this Provides a fluent interface
* @throws Exception\RuntimeException
*/
public function prepare($sql = null)
{
if ($this->isPrepared) {
throw new Exception\RuntimeException('This statement has been prepared already');
}
if ($sql === null) {
$sql = $this->sql;
}
try {
set_error_handler($this->createErrorHandler());
$this->resource = db2_prepare($this->db2, $sql);
} catch (ErrorException $e) {
throw new Exception\RuntimeException($e->getMessage() . '. ' . db2_stmt_errormsg(), db2_stmt_error(), $e);
} finally {
restore_error_handler();
}
if ($this->resource === false) {
throw new Exception\RuntimeException(db2_stmt_errormsg(), db2_stmt_error());
}
$this->isPrepared = true;
return $this;
}
/**
* Check if is prepared
*
* @return bool
*/
public function isPrepared()
{
return $this->isPrepared;
}
/**
* Execute
*
* @param null|array|ParameterContainer $parameters
* @return Result
*/
public function execute($parameters = null)
{
if (! $this->isPrepared) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (! $this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
/** END Standard ParameterContainer Merging Block */
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
set_error_handler(function () {
}, E_WARNING); // suppress warnings
$response = db2_execute($this->resource, $this->parameterContainer->getPositionalArray());
restore_error_handler();
if ($this->profiler) {
$this->profiler->profilerFinish();
}
if ($response === false) {
throw new Exception\RuntimeException(db2_stmt_errormsg($this->resource));
}
return $this->driver->createResult($this->resource);
}
/**
* Creates and returns a callable error handler that raises exceptions.
*
* Only raises exceptions for errors that are within the error_reporting mask.
*
* @return callable
*/
private function createErrorHandler()
{
/**
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @return void
* @throws ErrorException if error is not within the error_reporting mask.
*/
return function ($errno, $errstr, $errfile, $errline) {
if (! (error_reporting() & $errno)) {
// error_reporting does not include this error
return;
}
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
};
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Mysqli/Connection.php | src/Adapter/Driver/Mysqli/Connection.php | <?php
namespace Laminas\Db\Adapter\Driver\Mysqli;
use Exception as GenericException;
use Laminas\Db\Adapter\Driver\AbstractConnection;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Exception\InvalidArgumentException;
use function constant;
use function defined;
use function is_array;
use function is_string;
use function strtoupper;
use const MYSQLI_CLIENT_SSL;
use const MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
class Connection extends AbstractConnection
{
/** @var Mysqli */
protected $driver;
/** @var \mysqli */
protected $resource;
/**
* Constructor
*
* @param array|\mysqli|null $connectionInfo
* @throws InvalidArgumentException
*/
public function __construct($connectionInfo = null)
{
if (is_array($connectionInfo)) {
$this->setConnectionParameters($connectionInfo);
} elseif ($connectionInfo instanceof \mysqli) {
$this->setResource($connectionInfo);
} elseif (null !== $connectionInfo) {
throw new Exception\InvalidArgumentException(
'$connection must be an array of parameters, a mysqli object or null'
);
}
}
/**
* @return $this Provides a fluent interface
*/
public function setDriver(Mysqli $driver)
{
$this->driver = $driver;
return $this;
}
/**
* {@inheritDoc}
*/
public function getCurrentSchema()
{
if (! $this->isConnected()) {
$this->connect();
}
$result = $this->resource->query('SELECT DATABASE()');
$r = $result->fetch_row();
return $r[0];
}
/**
* Set resource
*
* @return $this Provides a fluent interface
*/
public function setResource(\mysqli $resource)
{
$this->resource = $resource;
return $this;
}
/**
* {@inheritDoc}
*/
public function connect()
{
if ($this->resource instanceof \mysqli) {
return $this;
}
// localize
$p = $this->connectionParameters;
// given a list of key names, test for existence in $p
$findParameterValue = function (array $names) use ($p) {
foreach ($names as $name) {
if (isset($p[$name])) {
return $p[$name];
}
}
return null;
};
$hostname = $findParameterValue(['hostname', 'host']);
$username = $findParameterValue(['username', 'user']);
$password = $findParameterValue(['password', 'passwd', 'pw']);
$database = $findParameterValue(['database', 'dbname', 'db', 'schema']);
$port = isset($p['port']) ? (int) $p['port'] : null;
$socket = $p['socket'] ?? null;
// phpcs:ignore WebimpressCodingStandard.NamingConventions.ValidVariableName.NotCamelCaps
$useSSL = $p['use_ssl'] ?? 0;
$clientKey = $p['client_key'] ?? '';
$clientCert = $p['client_cert'] ?? '';
$caCert = $p['ca_cert'] ?? '';
$caPath = $p['ca_path'] ?? '';
$cipher = $p['cipher'] ?? '';
$this->resource = $this->createResource();
if (! empty($p['driver_options'])) {
foreach ($p['driver_options'] as $option => $value) {
if (is_string($option)) {
$option = strtoupper($option);
if (! defined($option)) {
continue;
}
$option = constant($option);
}
$this->resource->options($option, $value);
}
}
$flags = null;
// phpcs:ignore WebimpressCodingStandard.NamingConventions.ValidVariableName.NotCamelCaps
if ($useSSL && ! $socket) {
// Even though mysqli docs are not quite clear on this, MYSQLI_CLIENT_SSL
// needs to be set to make sure SSL is used. ssl_set can also cause it to
// be implicitly set, but only when any of the parameters is non-empty.
$flags = MYSQLI_CLIENT_SSL;
$this->resource->ssl_set($clientKey, $clientCert, $caCert, $caPath, $cipher);
//MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT is not valid option, needs to be set as flag
if (
isset($p['driver_options'])
&& isset($p['driver_options'][MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT])
) {
$flags |= MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
}
}
try {
$flags === null
? $this->resource->real_connect($hostname, $username, $password, $database, $port, $socket)
: $this->resource->real_connect($hostname, $username, $password, $database, $port, $socket, $flags);
} catch (GenericException $e) {
throw new Exception\RuntimeException(
'Connection error',
$this->resource->connect_errno,
new Exception\ErrorException($this->resource->connect_error, $this->resource->connect_errno)
);
}
if ($this->resource->connect_error) {
throw new Exception\RuntimeException(
'Connection error',
$this->resource->connect_errno,
new Exception\ErrorException($this->resource->connect_error, $this->resource->connect_errno)
);
}
if (! empty($p['charset'])) {
$this->resource->set_charset($p['charset']);
}
return $this;
}
/**
* {@inheritDoc}
*/
public function isConnected()
{
return $this->resource instanceof \mysqli;
}
/**
* {@inheritDoc}
*/
public function disconnect()
{
if ($this->resource instanceof \mysqli) {
$this->resource->close();
}
$this->resource = null;
}
/**
* {@inheritDoc}
*/
public function beginTransaction()
{
if (! $this->isConnected()) {
$this->connect();
}
$this->resource->autocommit(false);
$this->inTransaction = true;
return $this;
}
/**
* {@inheritDoc}
*/
public function commit()
{
if (! $this->isConnected()) {
$this->connect();
}
$this->resource->commit();
$this->inTransaction = false;
$this->resource->autocommit(true);
return $this;
}
/**
* {@inheritDoc}
*/
public function rollback()
{
if (! $this->isConnected()) {
throw new Exception\RuntimeException('Must be connected before you can rollback.');
}
if (! $this->inTransaction) {
throw new Exception\RuntimeException('Must call beginTransaction() before you can rollback.');
}
$this->resource->rollback();
$this->resource->autocommit(true);
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\InvalidQueryException
*/
public function execute($sql)
{
if (! $this->isConnected()) {
$this->connect();
}
if ($this->profiler) {
$this->profiler->profilerStart($sql);
}
$resultResource = $this->resource->query($sql);
if ($this->profiler) {
$this->profiler->profilerFinish($sql);
}
// if the returnValue is something other than a mysqli_result, bypass wrapping it
if ($resultResource === false) {
throw new Exception\InvalidQueryException($this->resource->error);
}
return $this->driver->createResult($resultResource === true ? $this->resource : $resultResource);
}
/**
* {@inheritDoc}
*/
public function getLastGeneratedValue($name = null)
{
return $this->resource->insert_id;
}
/**
* Create a new mysqli resource
*
* @return \mysqli
*/
protected function createResource()
{
return new \mysqli();
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Mysqli/Result.php | src/Adapter/Driver/Mysqli/Result.php | <?php
namespace Laminas\Db\Adapter\Driver\Mysqli;
use Iterator;
use Laminas\Db\Adapter\Driver\ResultInterface;
use Laminas\Db\Adapter\Exception;
use mysqli;
use mysqli_result;
use mysqli_stmt;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use ReturnTypeWillChange;
use function array_fill;
use function call_user_func_array;
use function count;
class Result implements
Iterator,
ResultInterface
{
/** @var mysqli|mysqli_result|mysqli_stmt */
protected $resource;
/** @var bool */
protected $isBuffered;
/**
* Cursor position
*
* @var int
*/
protected $position = 0;
/**
* Number of known rows
*
* @var int
*/
protected $numberOfRows = -1;
/**
* Is the current() operation already complete for this pointer position?
*
* @var bool
*/
protected $currentComplete = false;
/** @var bool */
protected $nextComplete = false;
/** @var mixed */
protected $currentData;
/** @var array */
protected $statementBindValues = ['keys' => null, 'values' => []];
/** @var mixed */
protected $generatedValue;
/**
* Initialize
*
* @param mixed $resource
* @param mixed $generatedValue
* @param bool|null $isBuffered
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function initialize($resource, $generatedValue, $isBuffered = null)
{
if (
! $resource instanceof mysqli
&& ! $resource instanceof mysqli_result
&& ! $resource instanceof mysqli_stmt
) {
throw new Exception\InvalidArgumentException('Invalid resource provided.');
}
if ($isBuffered !== null) {
$this->isBuffered = $isBuffered;
} else {
if (
$resource instanceof mysqli || $resource instanceof mysqli_result
|| $resource instanceof mysqli_stmt && $resource->num_rows !== 0
) {
$this->isBuffered = true;
}
}
$this->resource = $resource;
$this->generatedValue = $generatedValue;
return $this;
}
/**
* Force buffering
*
* @throws Exception\RuntimeException
*/
public function buffer()
{
if ($this->resource instanceof mysqli_stmt && $this->isBuffered !== true) {
if ($this->position > 0) {
throw new Exception\RuntimeException('Cannot buffer a result set that has started iteration.');
}
$this->resource->store_result();
$this->isBuffered = true;
}
}
/**
* Check if is buffered
*
* @return bool|null
*/
public function isBuffered()
{
return $this->isBuffered;
}
/**
* Return the resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Is query result?
*
* @return bool
*/
public function isQueryResult()
{
return $this->resource->field_count > 0;
}
/**
* Get affected rows
*
* @return int
*/
public function getAffectedRows()
{
if ($this->resource instanceof mysqli || $this->resource instanceof mysqli_stmt) {
return $this->resource->affected_rows;
}
return $this->resource->num_rows;
}
/**
* Current
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function current()
{
if ($this->currentComplete) {
return $this->currentData;
}
if ($this->resource instanceof mysqli_stmt) {
$this->loadDataFromMysqliStatement();
return $this->currentData;
} else {
$this->loadFromMysqliResult();
return $this->currentData;
}
}
/**
* Mysqli's binding and returning of statement values
*
* Mysqli requires you to bind variables to the extension in order to
* get data out. These values have to be references:
*
* @see http://php.net/manual/en/mysqli-stmt.bind-result.php
*
* @throws Exception\RuntimeException
* @return bool
*/
protected function loadDataFromMysqliStatement()
{
// build the default reference based bind structure, if it does not already exist
if ($this->statementBindValues['keys'] === null) {
$this->statementBindValues['keys'] = [];
$resultResource = $this->resource->result_metadata();
foreach ($resultResource->fetch_fields() as $col) {
$this->statementBindValues['keys'][] = $col->name;
}
$this->statementBindValues['values'] = array_fill(0, count($this->statementBindValues['keys']), null);
$refs = [];
foreach ($this->statementBindValues['values'] as $i => &$f) {
$refs[$i] = &$f;
}
call_user_func_array([$this->resource, 'bind_result'], $this->statementBindValues['values']);
}
if (($r = $this->resource->fetch()) === null) {
if (! $this->isBuffered) {
$this->resource->close();
}
return false;
} elseif ($r === false) {
throw new Exception\RuntimeException($this->resource->error);
}
// dereference
for ($i = 0, $count = count($this->statementBindValues['keys']); $i < $count; $i++) {
$this->currentData[$this->statementBindValues['keys'][$i]] = $this->statementBindValues['values'][$i];
}
$this->currentComplete = true;
$this->nextComplete = true;
$this->position++;
return true;
}
/**
* Load from mysqli result
*
* @return bool
*/
protected function loadFromMysqliResult()
{
$this->currentData = null;
if (($data = $this->resource->fetch_assoc()) === null) {
return false;
}
$this->position++;
$this->currentData = $data;
$this->currentComplete = true;
$this->nextComplete = true;
$this->position++;
return true;
}
/**
* Next
*
* @return void
*/
#[ReturnTypeWillChange]
public function next()
{
$this->currentComplete = false;
if ($this->nextComplete === false) {
$this->position++;
}
$this->nextComplete = false;
}
/**
* Key
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function key()
{
return $this->position;
}
/**
* Rewind
*
* @throws Exception\RuntimeException
* @return void
*/
#[ReturnTypeWillChange]
public function rewind()
{
if (0 !== $this->position && false === $this->isBuffered) {
throw new Exception\RuntimeException('Unbuffered results cannot be rewound for multiple iterations');
}
$this->resource->data_seek(0); // works for both mysqli_result & mysqli_stmt
$this->currentComplete = false;
$this->position = 0;
}
/**
* Valid
*
* @return bool
*/
#[ReturnTypeWillChange]
public function valid()
{
if ($this->currentComplete) {
return true;
}
if ($this->resource instanceof mysqli_stmt) {
return $this->loadDataFromMysqliStatement();
}
return $this->loadFromMysqliResult();
}
/**
* Count
*
* @throws Exception\RuntimeException
* @return int
*/
#[ReturnTypeWillChange]
public function count()
{
if ($this->isBuffered === false) {
throw new Exception\RuntimeException('Row count is not available in unbuffered result sets.');
}
return $this->resource->num_rows;
}
/**
* Get field count
*
* @return int
*/
public function getFieldCount()
{
return $this->resource->field_count;
}
/**
* Get generated value
*
* @return mixed|null
*/
public function getGeneratedValue()
{
return $this->generatedValue;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Mysqli/Statement.php | src/Adapter/Driver/Mysqli/Statement.php | <?php
namespace Laminas\Db\Adapter\Driver\Mysqli;
use Laminas\Db\Adapter\Driver\StatementInterface;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Profiler;
use mysqli_stmt;
use function array_unshift;
use function call_user_func_array;
use function is_array;
class Statement implements StatementInterface, Profiler\ProfilerAwareInterface
{
/** @var \mysqli */
protected $mysqli;
/** @var Mysqli */
protected $driver;
/** @var Profiler\ProfilerInterface */
protected $profiler;
/** @var string */
protected $sql = '';
/**
* Parameter container
*
* @var ParameterContainer
*/
protected $parameterContainer;
/** @var mysqli_stmt */
protected $resource;
/**
* Is prepared
*
* @var bool
*/
protected $isPrepared = false;
/** @var bool */
protected $bufferResults = false;
/**
* @param bool $bufferResults
*/
public function __construct($bufferResults = false)
{
$this->bufferResults = (bool) $bufferResults;
}
/**
* Set driver
*
* @return $this Provides a fluent interface
*/
public function setDriver(Mysqli $driver)
{
$this->driver = $driver;
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Initialize
*
* @return $this Provides a fluent interface
*/
public function initialize(\mysqli $mysqli)
{
$this->mysqli = $mysqli;
return $this;
}
/**
* Set sql
*
* @param string $sql
* @return $this Provides a fluent interface
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Set Parameter container
*
* @return $this Provides a fluent interface
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* Get resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Set resource
*
* @return $this Provides a fluent interface
*/
public function setResource(mysqli_stmt $mysqliStatement)
{
$this->resource = $mysqliStatement;
$this->isPrepared = true;
return $this;
}
/**
* Get sql
*
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* Get parameter count
*
* @return ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* Is prepared
*
* @return bool
*/
public function isPrepared()
{
return $this->isPrepared;
}
/**
* Prepare
*
* @param string $sql
* @return $this Provides a fluent interface
* @throws Exception\InvalidQueryException
* @throws Exception\RuntimeException
*/
public function prepare($sql = null)
{
if ($this->isPrepared) {
throw new Exception\RuntimeException('This statement has already been prepared');
}
$sql = $sql ?: $this->sql;
$this->resource = $this->mysqli->prepare($sql);
if (! $this->resource instanceof mysqli_stmt) {
throw new Exception\InvalidQueryException(
'Statement couldn\'t be produced with sql: ' . $sql,
$this->mysqli->errno,
new Exception\ErrorException($this->mysqli->error, $this->mysqli->errno)
);
}
$this->isPrepared = true;
return $this;
}
/**
* Execute
*
* @param null|array|ParameterContainer $parameters
* @throws Exception\RuntimeException
* @return mixed
*/
public function execute($parameters = null)
{
if (! $this->isPrepared) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (! $this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
if ($this->parameterContainer->count() > 0) {
$this->bindParametersFromContainer();
}
/** END Standard ParameterContainer Merging Block */
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
$return = $this->resource->execute();
if ($this->profiler) {
$this->profiler->profilerFinish();
}
if ($return === false) {
throw new Exception\RuntimeException($this->resource->error);
}
if ($this->bufferResults === true) {
$this->resource->store_result();
$this->isPrepared = false;
$buffered = true;
} else {
$buffered = false;
}
return $this->driver->createResult($this->resource, $buffered);
}
/**
* Bind parameters from container
*
* @return void
*/
protected function bindParametersFromContainer()
{
$parameters = $this->parameterContainer->getNamedArray();
$type = '';
$args = [];
foreach ($parameters as $name => &$value) {
if ($this->parameterContainer->offsetHasErrata($name)) {
switch ($this->parameterContainer->offsetGetErrata($name)) {
case ParameterContainer::TYPE_DOUBLE:
$type .= 'd';
break;
case ParameterContainer::TYPE_NULL:
$value = null; // as per @see http://www.php.net/manual/en/mysqli-stmt.bind-param.php#96148
case ParameterContainer::TYPE_INTEGER:
$type .= 'i';
break;
case ParameterContainer::TYPE_STRING:
default:
$type .= 's';
break;
}
} else {
$type .= 's';
}
$args[] = &$value;
}
if ($args) {
array_unshift($args, $type);
call_user_func_array([$this->resource, 'bind_param'], $args);
}
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Mysqli/Mysqli.php | src/Adapter/Driver/Mysqli/Mysqli.php | <?php
namespace Laminas\Db\Adapter\Driver\Mysqli;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Profiler;
use mysqli_stmt;
use function array_intersect_key;
use function array_merge;
use function extension_loaded;
use function is_string;
class Mysqli implements DriverInterface, Profiler\ProfilerAwareInterface
{
/** @var Connection */
protected $connection;
/** @var Statement */
protected $statementPrototype;
/** @var Result */
protected $resultPrototype;
/** @var Profiler\ProfilerInterface */
protected $profiler;
/** @var array */
protected $options = [
'buffer_results' => false,
];
/**
* Constructor
*
* @param array|Connection|\mysqli $connection
* @param array $options
*/
public function __construct(
$connection,
?Statement $statementPrototype = null,
?Result $resultPrototype = null,
array $options = []
) {
if (! $connection instanceof Connection) {
$connection = new Connection($connection);
}
$options = array_intersect_key(array_merge($this->options, $options), $this->options);
$this->registerConnection($connection);
$this->registerStatementPrototype($statementPrototype ?: new Statement($options['buffer_results']));
$this->registerResultPrototype($resultPrototype ?: new Result());
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
if ($this->connection instanceof Profiler\ProfilerAwareInterface) {
$this->connection->setProfiler($profiler);
}
if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) {
$this->statementPrototype->setProfiler($profiler);
}
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Register connection
*
* @return $this Provides a fluent interface
*/
public function registerConnection(Connection $connection)
{
$this->connection = $connection;
$this->connection->setDriver($this); // needs access to driver to createStatement()
return $this;
}
/**
* Register statement prototype
*/
public function registerStatementPrototype(Statement $statementPrototype)
{
$this->statementPrototype = $statementPrototype;
$this->statementPrototype->setDriver($this); // needs access to driver to createResult()
}
/**
* Get statement prototype
*
* @return null|Statement
*/
public function getStatementPrototype()
{
return $this->statementPrototype;
}
/**
* Register result prototype
*/
public function registerResultPrototype(Result $resultPrototype)
{
$this->resultPrototype = $resultPrototype;
}
/**
* @return null|Result
*/
public function getResultPrototype()
{
return $this->resultPrototype;
}
/**
* Get database platform name
*
* @param string $nameFormat
* @return string
*/
public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE)
{
if ($nameFormat === self::NAME_FORMAT_CAMELCASE) {
return 'Mysql';
}
return 'MySQL';
}
/**
* Check environment
*
* @throws Exception\RuntimeException
* @return void
*/
public function checkEnvironment()
{
if (! extension_loaded('mysqli')) {
throw new Exception\RuntimeException(
'The Mysqli extension is required for this adapter but the extension is not loaded'
);
}
}
/**
* Get connection
*
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* Create statement
*
* @param string $sqlOrResource
* @return Statement
*/
public function createStatement($sqlOrResource = null)
{
/**
* @todo Resource tracking
if (is_resource($sqlOrResource) && !in_array($sqlOrResource, $this->resources, true)) {
$this->resources[] = $sqlOrResource;
}
*/
$statement = clone $this->statementPrototype;
if ($sqlOrResource instanceof mysqli_stmt) {
$statement->setResource($sqlOrResource);
} else {
if (is_string($sqlOrResource)) {
$statement->setSql($sqlOrResource);
}
if (! $this->connection->isConnected()) {
$this->connection->connect();
}
$statement->initialize($this->connection->getResource());
}
return $statement;
}
/**
* Create result
*
* @param resource $resource
* @param null|bool $isBuffered
* @return Result
*/
public function createResult($resource, $isBuffered = null)
{
$result = clone $this->resultPrototype;
$result->initialize($resource, $this->connection->getLastGeneratedValue(), $isBuffered);
return $result;
}
/**
* Get prepare type
*
* @return string
*/
public function getPrepareType()
{
return self::PARAMETERIZATION_POSITIONAL;
}
/**
* Format parameter name
*
* @param string $name
* @param mixed $type
* @return string
*/
public function formatParameterName($name, $type = null)
{
return '?';
}
/**
* Get last generated value
*
* @return mixed
*/
public function getLastGeneratedValue()
{
return $this->getConnection()->getLastGeneratedValue();
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Pgsql/Connection.php | src/Adapter/Driver/Pgsql/Connection.php | <?php
namespace Laminas\Db\Adapter\Driver\Pgsql;
use Laminas\Db\Adapter\Driver\AbstractConnection;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\ResultSet\ResultSetInterface;
use PgSql\Connection as PgSqlConnection;
use function array_filter;
use function defined;
use function http_build_query;
use function is_array;
use function is_resource;
use function pg_connect;
use function pg_fetch_result;
use function pg_last_error;
use function pg_query;
use function pg_set_client_encoding;
use function restore_error_handler;
use function set_error_handler;
use function sprintf;
use function str_replace;
use function urldecode;
use const PGSQL_CONNECT_ASYNC;
use const PGSQL_CONNECT_FORCE_NEW;
class Connection extends AbstractConnection
{
/** @var Pgsql */
protected $driver;
/** @var resource */
protected $resource;
/** @var null|int PostgreSQL connection type */
protected $type;
/**
* Constructor
*
* @param resource|array|null $connectionInfo
*/
public function __construct($connectionInfo = null)
{
if (is_array($connectionInfo)) {
$this->setConnectionParameters($connectionInfo);
} elseif ($connectionInfo instanceof PgSqlConnection || is_resource($connectionInfo)) {
$this->setResource($connectionInfo);
}
}
/**
* Set resource
*
* @param resource $resource
* @return $this Provides a fluent interface
*/
public function setResource($resource)
{
$this->resource = $resource;
return $this;
}
/**
* Set driver
*
* @return $this Provides a fluent interface
*/
public function setDriver(Pgsql $driver)
{
$this->driver = $driver;
return $this;
}
/**
* @param int|null $type
* @return $this Provides a fluent interface
*/
public function setType($type)
{
$invalidConectionType = $type !== PGSQL_CONNECT_FORCE_NEW;
// Compatibility with PHP < 5.6
if ($invalidConectionType && defined('PGSQL_CONNECT_ASYNC')) {
$invalidConectionType = $type !== PGSQL_CONNECT_ASYNC;
}
if ($invalidConectionType) {
throw new Exception\InvalidArgumentException(
'Connection type is not valid. (See: http://php.net/manual/en/function.pg-connect.php)'
);
}
$this->type = $type;
return $this;
}
/**
* {@inheritDoc}
*
* @return null|string
*/
public function getCurrentSchema()
{
if (! $this->isConnected()) {
$this->connect();
}
$result = pg_query($this->resource, 'SELECT CURRENT_SCHEMA AS "currentschema"');
if ($result === false) {
return null;
}
return pg_fetch_result($result, 0, 'currentschema');
}
/**
* {@inheritDoc}
*
* @throws Exception\RuntimeException On failure.
*/
public function connect()
{
if ($this->resource instanceof PgSqlConnection || is_resource($this->resource)) {
return $this;
}
$connection = $this->getConnectionString();
set_error_handler(function ($number, $string) {
throw new Exception\RuntimeException(
self::class . '::connect: Unable to connect to database',
$number ?? 0,
new Exception\ErrorException($string, $number ?? 0)
);
});
try {
$this->resource = pg_connect($connection);
} finally {
restore_error_handler();
}
if ($this->resource === false) {
throw new Exception\RuntimeException(sprintf(
'%s: Unable to connect to database',
__METHOD__
));
}
$p = $this->connectionParameters;
if (! empty($p['charset'])) {
if (-1 === pg_set_client_encoding($this->resource, $p['charset'])) {
throw new Exception\RuntimeException(sprintf(
"%s: Unable to set client encoding '%s'",
__METHOD__,
$p['charset']
));
}
}
return $this;
}
/**
* {@inheritDoc}
*/
public function isConnected()
{
return $this->resource instanceof PgSqlConnection || is_resource($this->resource);
}
/**
* {@inheritDoc}
*/
public function disconnect()
{
// phpcs:ignore SlevomatCodingStandard.Namespaces.ReferenceUsedNamesOnly.ReferenceViaFallbackGlobalName
pg_close($this->resource);
return $this;
}
/**
* {@inheritDoc}
*/
public function beginTransaction()
{
if ($this->inTransaction()) {
throw new Exception\RuntimeException('Nested transactions are not supported');
}
if (! $this->isConnected()) {
$this->connect();
}
pg_query($this->resource, 'BEGIN');
$this->inTransaction = true;
return $this;
}
/**
* {@inheritDoc}
*/
public function commit()
{
if (! $this->isConnected()) {
$this->connect();
}
if (! $this->inTransaction()) {
return; // We ignore attempts to commit non-existing transaction
}
pg_query($this->resource, 'COMMIT');
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*/
public function rollback()
{
if (! $this->isConnected()) {
throw new Exception\RuntimeException('Must be connected before you can rollback');
}
if (! $this->inTransaction()) {
throw new Exception\RuntimeException('Must call beginTransaction() before you can rollback');
}
pg_query($this->resource, 'ROLLBACK');
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\InvalidQueryException
* @return resource|ResultSetInterface
*/
public function execute($sql)
{
if (! $this->isConnected()) {
$this->connect();
}
if ($this->profiler) {
$this->profiler->profilerStart($sql);
}
$resultResource = pg_query($this->resource, $sql);
if ($this->profiler) {
$this->profiler->profilerFinish($sql);
}
// if the returnValue is something other than a pg result resource, bypass wrapping it
if ($resultResource === false) {
throw new Exception\InvalidQueryException(pg_last_error($this->resource));
}
return $this->driver->createResult($resultResource === true ? $this->resource : $resultResource);
}
/**
* {@inheritDoc}
*
* @return string
*/
public function getLastGeneratedValue($name = null)
{
if ($name === null) {
return;
}
$result = pg_query(
$this->resource,
'SELECT CURRVAL(\'' . str_replace('\'', '\\\'', $name) . '\') as "currval"'
);
return pg_fetch_result($result, 0, 'currval');
}
/**
* Get Connection String
*
* @return string
*/
private function getConnectionString()
{
// localize
$p = $this->connectionParameters;
// given a list of key names, test for existence in $p
$findParameterValue = function (array $names) use ($p) {
foreach ($names as $name) {
if (isset($p[$name])) {
return $p[$name];
}
}
return null;
};
$connectionParameters = [
'host' => $findParameterValue(['hostname', 'host']),
'user' => $findParameterValue(['username', 'user']),
'password' => $findParameterValue(['password', 'passwd', 'pw']),
'dbname' => $findParameterValue(['database', 'dbname', 'db', 'schema']),
'port' => isset($p['port']) ? (int) $p['port'] : null,
'socket' => $p['socket'] ?? null,
];
return urldecode(http_build_query(array_filter($connectionParameters), '', ' '));
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Pgsql/Result.php | src/Adapter/Driver/Pgsql/Result.php | <?php
namespace Laminas\Db\Adapter\Driver\Pgsql;
use Laminas\Db\Adapter\Driver\ResultInterface;
use Laminas\Db\Adapter\Exception;
use PgSql\Result as PgSqlResult;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use ReturnTypeWillChange;
use function get_resource_type;
use function is_resource;
use function pg_affected_rows;
use function pg_fetch_assoc;
use function pg_num_fields;
use function pg_num_rows;
class Result implements ResultInterface
{
/** @var resource */
protected $resource;
/** @var int */
protected $position = 0;
/** @var int */
protected $count = 0;
/** @var null|mixed */
protected $generatedValue;
/**
* Initialize
*
* @param resource $resource
* @param int|string $generatedValue
* @return void
* @throws Exception\InvalidArgumentException
*/
public function initialize($resource, $generatedValue)
{
if (
! $resource instanceof PgSqlResult
&& (
! is_resource($resource)
|| 'pgsql result' !== get_resource_type($resource)
)
) {
throw new Exception\InvalidArgumentException('Resource not of the correct type.');
}
$this->resource = $resource;
$this->count = pg_num_rows($this->resource);
$this->generatedValue = $generatedValue;
}
/**
* Current
*
* @return array|bool|mixed
*/
#[ReturnTypeWillChange]
public function current()
{
if ($this->count === 0) {
return false;
}
return pg_fetch_assoc($this->resource, $this->position);
}
/**
* Next
*
* @return void
*/
#[ReturnTypeWillChange]
public function next()
{
$this->position++;
}
/**
* Key
*
* @return int|mixed
*/
#[ReturnTypeWillChange]
public function key()
{
return $this->position;
}
/**
* Valid
*
* @return bool
*/
#[ReturnTypeWillChange]
public function valid()
{
return $this->position < $this->count;
}
/**
* Rewind
*
* @return void
*/
#[ReturnTypeWillChange]
public function rewind()
{
$this->position = 0;
}
/**
* Buffer
*
* @return null
*/
public function buffer()
{
return null;
}
/**
* Is buffered
*
* @return false
*/
public function isBuffered()
{
return false;
}
/**
* Is query result
*
* @return bool
*/
public function isQueryResult()
{
return pg_num_fields($this->resource) > 0;
}
/**
* Get affected rows
*
* @return int
*/
public function getAffectedRows()
{
return pg_affected_rows($this->resource);
}
/**
* Get generated value
*
* @return mixed|null
*/
public function getGeneratedValue()
{
return $this->generatedValue;
}
/**
* Get resource
*/
public function getResource()
{
// TODO: Implement getResource() method.
}
/**
* Count
*
* @return int The custom count as an integer.
*/
#[ReturnTypeWillChange]
public function count()
{
return $this->count;
}
/**
* Get field count
*
* @return int
*/
public function getFieldCount()
{
return pg_num_fields($this->resource);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Pgsql/Pgsql.php | src/Adapter/Driver/Pgsql/Pgsql.php | <?php
namespace Laminas\Db\Adapter\Driver\Pgsql;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Profiler;
use function extension_loaded;
use function is_string;
class Pgsql implements DriverInterface, Profiler\ProfilerAwareInterface
{
/** @var Connection */
protected $connection;
/** @var Statement */
protected $statementPrototype;
/** @var Result */
protected $resultPrototype;
/** @var null|Profiler\ProfilerInterface */
protected $profiler;
/** @var array */
protected $options = [
'buffer_results' => false,
];
/**
* Constructor
*
* @param array|Connection|resource $connection
* @param array $options
*/
public function __construct(
$connection,
?Statement $statementPrototype = null,
?Result $resultPrototype = null,
$options = null
) {
if (! $connection instanceof Connection) {
$connection = new Connection($connection);
}
$this->registerConnection($connection);
$this->registerStatementPrototype($statementPrototype ?: new Statement());
$this->registerResultPrototype($resultPrototype ?: new Result());
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
if ($this->connection instanceof Profiler\ProfilerAwareInterface) {
$this->connection->setProfiler($profiler);
}
if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) {
$this->statementPrototype->setProfiler($profiler);
}
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Register connection
*
* @return $this Provides a fluent interface
*/
public function registerConnection(Connection $connection)
{
$this->connection = $connection;
$this->connection->setDriver($this);
return $this;
}
/**
* Register statement prototype
*
* @return $this Provides a fluent interface
*/
public function registerStatementPrototype(Statement $statement)
{
$this->statementPrototype = $statement;
$this->statementPrototype->setDriver($this); // needs access to driver to createResult()
return $this;
}
/**
* Register result prototype
*
* @return $this Provides a fluent interface
*/
public function registerResultPrototype(Result $result)
{
$this->resultPrototype = $result;
return $this;
}
/**
* Get database platform name
*
* @param string $nameFormat
* @return string
*/
public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE)
{
if ($nameFormat === self::NAME_FORMAT_CAMELCASE) {
return 'Postgresql';
}
return 'PostgreSQL';
}
/**
* Check environment
*
* @throws Exception\RuntimeException
* @return void
*/
public function checkEnvironment()
{
if (! extension_loaded('pgsql')) {
throw new Exception\RuntimeException(
'The PostgreSQL (pgsql) extension is required for this adapter but the extension is not loaded'
);
}
}
/**
* Get connection
*
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* Create statement
*
* @param string|null $sqlOrResource
* @return Statement
*/
public function createStatement($sqlOrResource = null)
{
$statement = clone $this->statementPrototype;
if (is_string($sqlOrResource)) {
$statement->setSql($sqlOrResource);
}
if (! $this->connection->isConnected()) {
$this->connection->connect();
}
$statement->initialize($this->connection->getResource());
return $statement;
}
/**
* Create result
*
* @param resource $resource
* @return Result
*/
public function createResult($resource)
{
$result = clone $this->resultPrototype;
$result->initialize($resource, $this->connection->getLastGeneratedValue());
return $result;
}
/**
* @return Result
*/
public function getResultPrototype()
{
return $this->resultPrototype;
}
/**
* Get prepare Type
*
* @return string
*/
public function getPrepareType()
{
return self::PARAMETERIZATION_POSITIONAL;
}
/**
* Format parameter name
*
* @param string $name
* @param mixed $type
* @return string
*/
public function formatParameterName($name, $type = null)
{
return '$#';
}
/**
* Get last generated value
*
* @param string $name
* @return mixed
*/
public function getLastGeneratedValue($name = null)
{
return $this->connection->getLastGeneratedValue($name);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Driver/Pgsql/Statement.php | src/Adapter/Driver/Pgsql/Statement.php | <?php
namespace Laminas\Db\Adapter\Driver\Pgsql;
use Laminas\Db\Adapter\Driver\StatementInterface;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Profiler;
use PgSql\Connection as PgSqlConnection;
use function get_resource_type;
use function is_array;
use function is_resource;
use function pg_execute;
use function pg_last_error;
use function pg_prepare;
use function preg_replace_callback;
use function sprintf;
class Statement implements StatementInterface, Profiler\ProfilerAwareInterface
{
/** @var int */
protected static $statementIndex = 0;
/** @var string */
protected $statementName = '';
/** @var Pgsql */
protected $driver;
/** @var Profiler\ProfilerInterface */
protected $profiler;
/** @var resource */
protected $pgsql;
/** @var resource */
protected $resource;
/** @var string */
protected $sql;
/** @var ParameterContainer */
protected $parameterContainer;
/**
* @return $this Provides a fluent interface
*/
public function setDriver(Pgsql $driver)
{
$this->driver = $driver;
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Initialize
*
* @param resource $pgsql
* @return void
* @throws Exception\RuntimeException For invalid or missing postgresql connection.
*/
public function initialize($pgsql)
{
if (
! $pgsql instanceof PgSqlConnection
&& (
! is_resource($pgsql)
|| 'pgsql link' !== get_resource_type($pgsql)
)
) {
throw new Exception\RuntimeException(sprintf(
'%s: Invalid or missing postgresql connection; received "%s"',
__METHOD__,
get_resource_type($pgsql)
));
}
$this->pgsql = $pgsql;
}
/**
* Get resource
*
* @todo Implement this method
* phpcs:ignore Squiz.Commenting.FunctionComment.InvalidNoReturn
* @return resource
*/
public function getResource()
{
}
/**
* Set sql
*
* @param string $sql
* @return $this Provides a fluent interface
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Get sql
*
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* Set parameter container
*
* @return $this Provides a fluent interface
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* Get parameter container
*
* @return ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* Prepare
*
* @param string $sql
*/
public function prepare($sql = null)
{
$sql = $sql ?: $this->sql;
$pCount = 1;
$sql = preg_replace_callback(
'#\$\##',
function () use (&$pCount) {
return '$' . $pCount++;
},
$sql
);
$this->sql = $sql;
$this->statementName = 'statement' . ++static::$statementIndex;
$this->resource = pg_prepare($this->pgsql, $this->statementName, $sql);
}
/**
* Is prepared
*
* @return bool
*/
public function isPrepared()
{
return isset($this->resource);
}
/**
* Execute
*
* @param null|array|ParameterContainer $parameters
* @throws Exception\InvalidQueryException
* @return Result
*/
public function execute($parameters = null)
{
if (! $this->isPrepared()) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (! $this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
if ($this->parameterContainer->count() > 0) {
$parameters = $this->parameterContainer->getPositionalArray();
}
/** END Standard ParameterContainer Merging Block */
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
$resultResource = pg_execute($this->pgsql, $this->statementName, (array) $parameters);
if ($this->profiler) {
$this->profiler->profilerFinish();
}
if ($resultResource === false) {
throw new Exception\InvalidQueryException(pg_last_error());
}
return $this->driver->createResult($resultResource);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Profiler/ProfilerAwareInterface.php | src/Adapter/Profiler/ProfilerAwareInterface.php | <?php
namespace Laminas\Db\Adapter\Profiler;
interface ProfilerAwareInterface
{
public function setProfiler(ProfilerInterface $profiler);
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Profiler/ProfilerInterface.php | src/Adapter/Profiler/ProfilerInterface.php | <?php
namespace Laminas\Db\Adapter\Profiler;
use Laminas\Db\Adapter\StatementContainerInterface;
interface ProfilerInterface
{
/**
* @param string|StatementContainerInterface $target
* @return mixed
*/
public function profilerStart($target);
public function profilerFinish();
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Profiler/Profiler.php | src/Adapter/Profiler/Profiler.php | <?php
namespace Laminas\Db\Adapter\Profiler;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Exception\InvalidArgumentException;
use Laminas\Db\Adapter\StatementContainerInterface;
use function end;
use function is_string;
use function microtime;
class Profiler implements ProfilerInterface
{
/** @var array */
protected $profiles = [];
/** @var null */
protected $currentIndex = 0;
/**
* @param string|StatementContainerInterface $target
* @return $this Provides a fluent interface
* @throws InvalidArgumentException
*/
public function profilerStart($target)
{
$profileInformation = [
'sql' => '',
'parameters' => null,
'start' => microtime(true),
'end' => null,
'elapse' => null,
];
if ($target instanceof StatementContainerInterface) {
$profileInformation['sql'] = $target->getSql();
$profileInformation['parameters'] = clone $target->getParameterContainer();
} elseif (is_string($target)) {
$profileInformation['sql'] = $target;
} else {
throw new Exception\InvalidArgumentException(
__FUNCTION__ . ' takes either a StatementContainer or a string'
);
}
$this->profiles[$this->currentIndex] = $profileInformation;
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function profilerFinish()
{
if (! isset($this->profiles[$this->currentIndex])) {
throw new Exception\RuntimeException(
'A profile must be started before ' . __FUNCTION__ . ' can be called.'
);
}
$current = &$this->profiles[$this->currentIndex];
$current['end'] = microtime(true);
$current['elapse'] = $current['end'] - $current['start'];
$this->currentIndex++;
return $this;
}
/**
* @return array|null
*/
public function getLastProfile()
{
return end($this->profiles);
}
/**
* @return array
*/
public function getProfiles()
{
return $this->profiles;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Exception/InvalidConnectionParametersException.php | src/Adapter/Exception/InvalidConnectionParametersException.php | <?php
namespace Laminas\Db\Adapter\Exception;
class InvalidConnectionParametersException extends RuntimeException implements ExceptionInterface
{
/** @var int */
protected $parameters;
/**
* @param string $message
* @param int $parameters
*/
public function __construct($message, $parameters)
{
parent::__construct($message);
$this->parameters = $parameters;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Exception/InvalidQueryException.php | src/Adapter/Exception/InvalidQueryException.php | <?php
namespace Laminas\Db\Adapter\Exception;
class InvalidQueryException extends UnexpectedValueException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Exception/ExceptionInterface.php | src/Adapter/Exception/ExceptionInterface.php | <?php
namespace Laminas\Db\Adapter\Exception;
use Laminas\Db\Exception;
interface ExceptionInterface extends Exception\ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Exception/RuntimeException.php | src/Adapter/Exception/RuntimeException.php | <?php
namespace Laminas\Db\Adapter\Exception;
use Laminas\Db\Exception;
class RuntimeException extends Exception\RuntimeException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Exception/UnexpectedValueException.php | src/Adapter/Exception/UnexpectedValueException.php | <?php
namespace Laminas\Db\Adapter\Exception;
use Laminas\Db\Exception;
class UnexpectedValueException extends Exception\UnexpectedValueException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Exception/InvalidArgumentException.php | src/Adapter/Exception/InvalidArgumentException.php | <?php
namespace Laminas\Db\Adapter\Exception;
use Laminas\Db\Exception;
class InvalidArgumentException extends Exception\InvalidArgumentException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Exception/ErrorException.php | src/Adapter/Exception/ErrorException.php | <?php
namespace Laminas\Db\Adapter\Exception;
use Laminas\Db\Exception;
class ErrorException extends Exception\ErrorException implements ExceptionInterface
{
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Platform/IbmDb2.php | src/Adapter/Platform/IbmDb2.php | <?php
namespace Laminas\Db\Adapter\Platform;
use function db2_escape_string;
use function function_exists;
use function implode;
use function is_array;
use function preg_split;
use function sprintf;
use function str_replace;
use function strtolower;
use function trigger_error;
use const PREG_SPLIT_DELIM_CAPTURE;
use const PREG_SPLIT_NO_EMPTY;
class IbmDb2 extends AbstractPlatform
{
/** @var string */
protected $identifierSeparator = '.';
/**
* @param array $options
*/
public function __construct($options = [])
{
if (
isset($options['quote_identifiers'])
&& ($options['quote_identifiers'] === false
|| $options['quote_identifiers'] === 'false'
)
) {
$this->quoteIdentifiers = false;
}
if (isset($options['identifier_separator'])) {
$this->identifierSeparator = $options['identifier_separator'];
}
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'IBM DB2';
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierInFragment($identifier, array $safeWords = [])
{
if (! $this->quoteIdentifiers) {
return $identifier;
}
$safeWordsInt = ['*' => true, ' ' => true, '.' => true, 'as' => true];
foreach ($safeWords as $sWord) {
$safeWordsInt[strtolower($sWord)] = true;
}
$parts = preg_split(
'/([^0-9,a-z,A-Z$#_:])/i',
$identifier,
-1,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
);
$identifier = '';
foreach ($parts as $part) {
$identifier .= isset($safeWordsInt[strtolower($part)])
? $part
: $this->quoteIdentifier[0]
. str_replace($this->quoteIdentifier[0], $this->quoteIdentifierTo, $part)
. $this->quoteIdentifier[1];
}
return $identifier;
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierChain($identifierChain)
{
if ($this->quoteIdentifiers === false) {
if (is_array($identifierChain)) {
return implode($this->identifierSeparator, $identifierChain);
} else {
return $identifierChain;
}
}
$identifierChain = str_replace('"', '\\"', $identifierChain);
if (is_array($identifierChain)) {
$identifierChain = implode('"' . $this->identifierSeparator . '"', $identifierChain);
}
return '"' . $identifierChain . '"';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
if (function_exists('db2_escape_string')) {
return '\'' . db2_escape_string($value) . '\'';
}
trigger_error(sprintf(
'Attempting to quote a value in %s without extension/driver support '
. 'can introduce security vulnerabilities in a production environment.',
static::class
));
return '\'' . str_replace("'", "''", $value) . '\'';
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
if (function_exists('db2_escape_string')) {
return '\'' . db2_escape_string($value) . '\'';
}
return '\'' . str_replace("'", "''", $value) . '\'';
}
/**
* {@inheritDoc}
*/
public function getIdentifierSeparator()
{
return $this->identifierSeparator;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Platform/Oracle.php | src/Adapter/Platform/Oracle.php | <?php
namespace Laminas\Db\Adapter\Platform;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Driver\Oci8\Oci8;
use Laminas\Db\Adapter\Driver\Pdo\Pdo;
use Laminas\Db\Adapter\Exception\InvalidArgumentException;
use function addcslashes;
use function get_resource_type;
use function implode;
use function str_replace;
use function trigger_error;
class Oracle extends AbstractPlatform
{
/** @var null|Pdo|Oci8|\PDO */
protected $resource;
/**
* @param array $options
* @param null|Oci8|Pdo $driver
*/
public function __construct($options = [], $driver = null)
{
if (
isset($options['quote_identifiers'])
&& ($options['quote_identifiers'] === false
|| $options['quote_identifiers'] === 'false')
) {
$this->quoteIdentifiers = false;
}
if ($driver) {
$this->setDriver($driver);
}
}
/**
* @param Pdo|Oci8 $driver
* @return $this Provides a fluent interface
* @throws InvalidArgumentException
*/
public function setDriver($driver)
{
if (
$driver instanceof Oci8
|| ($driver instanceof Pdo && $driver->getDatabasePlatformName() === 'Oracle')
|| $driver instanceof \oci8
|| ($driver instanceof \PDO && $driver->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'oci')
) {
$this->resource = $driver;
return $this;
}
throw new InvalidArgumentException(
'$driver must be a Oci8 or Oracle PDO Laminas\Db\Adapter\Driver, '
. 'Oci8 instance, or Oci PDO instance'
);
}
/**
* @return null|Pdo|Oci8
*/
public function getDriver()
{
return $this->resource;
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'Oracle';
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierChain($identifierChain)
{
if ($this->quoteIdentifiers === false) {
return implode('.', (array) $identifierChain);
}
return '"' . implode('"."', (array) str_replace('"', '\\"', $identifierChain)) . '"';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
if ($this->resource instanceof DriverInterface) {
$resource = $this->resource->getConnection()->getResource();
} else {
$resource = $this->resource;
}
if ($resource) {
if ($resource instanceof \PDO) {
return $resource->quote($value);
}
if (
get_resource_type($resource) === 'oci8 connection'
|| get_resource_type($resource) === 'oci8 persistent connection'
) {
return "'" . addcslashes(str_replace("'", "''", $value), "\x00\n\r\"\x1a") . "'";
}
}
trigger_error(
'Attempting to quote a value in ' . self::class . ' without extension/driver support '
. 'can introduce security vulnerabilities in a production environment.'
);
return "'" . addcslashes(str_replace("'", "''", $value), "\x00\n\r\"\x1a") . "'";
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
return "'" . addcslashes(str_replace('\'', '\'\'', $value), "\x00\n\r\"\x1a") . "'";
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Platform/Mysql.php | src/Adapter/Platform/Mysql.php | <?php
namespace Laminas\Db\Adapter\Platform;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Driver\Mysqli;
use Laminas\Db\Adapter\Driver\Pdo;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Exception\InvalidArgumentException;
use function implode;
use function str_replace;
class Mysql extends AbstractPlatform
{
/**
* {@inheritDoc}
*/
protected $quoteIdentifier = ['`', '`'];
/**
* {@inheritDoc}
*/
protected $quoteIdentifierTo = '``';
/** @var \mysqli|\PDO|Pdo\Pdo|Mysqli\Mysqli */
protected $driver;
/**
* NOTE: Include dashes for MySQL only, need tests for others platforms
*
* @var string
*/
protected $quoteIdentifierFragmentPattern = '/([^0-9,a-z,A-Z$_\-:])/i';
/**
* @param null|\Laminas\Db\Adapter\Driver\Mysqli\Mysqli|\Laminas\Db\Adapter\Driver\Pdo\Pdo|\mysqli|\PDO $driver
*/
public function __construct($driver = null)
{
if ($driver) {
$this->setDriver($driver);
}
}
/**
* @param \Laminas\Db\Adapter\Driver\Mysqli\Mysqli|\Laminas\Db\Adapter\Driver\Pdo\Pdo|\mysqli|\PDO $driver
* @return $this Provides a fluent interface
* @throws InvalidArgumentException
*/
public function setDriver($driver)
{
// handle Laminas\Db drivers
if (
$driver instanceof Mysqli\Mysqli
|| ($driver instanceof Pdo\Pdo && $driver->getDatabasePlatformName() === 'Mysql')
|| $driver instanceof \mysqli
|| ($driver instanceof \PDO && $driver->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'mysql')
) {
$this->driver = $driver;
return $this;
}
throw new Exception\InvalidArgumentException(
'$driver must be a Mysqli or Mysql PDO Laminas\Db\Adapter\Driver, Mysqli instance or MySQL PDO instance'
);
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'MySQL';
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierChain($identifierChain)
{
return '`' . implode('`.`', (array) str_replace('`', '``', $identifierChain)) . '`';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
$quotedViaDriverValue = $this->quoteViaDriver($value);
return $quotedViaDriverValue ?? parent::quoteValue($value);
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
$quotedViaDriverValue = $this->quoteViaDriver($value);
return $quotedViaDriverValue ?? parent::quoteTrustedValue($value);
}
/**
* @param string $value
* @return string|null
*/
protected function quoteViaDriver($value)
{
if ($this->driver instanceof DriverInterface) {
$resource = $this->driver->getConnection()->getResource();
} else {
$resource = $this->driver;
}
if ($resource instanceof \mysqli) {
return '\'' . $resource->real_escape_string($value) . '\'';
}
if ($resource instanceof \PDO) {
return $resource->quote($value);
}
return null;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Platform/Postgresql.php | src/Adapter/Platform/Postgresql.php | <?php
namespace Laminas\Db\Adapter\Platform;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Driver\Pdo;
use Laminas\Db\Adapter\Driver\Pgsql;
use Laminas\Db\Adapter\Exception;
use PgSql\Connection as PgSqlConnection;
use function get_resource_type;
use function implode;
use function in_array;
use function is_resource;
use function pg_escape_string;
use function str_replace;
class Postgresql extends AbstractPlatform
{
/**
* Overrides value from AbstractPlatform to use proper escaping for Postgres
*
* @var string
*/
protected $quoteIdentifierTo = '""';
/** @var null|resource|\PDO|Pdo\Pdo|Pgsql\Pgsql */
protected $driver;
/** @var string[] */
private $knownPgsqlResources = [
'pgsql link',
'pgsql link persistent',
];
/**
* @param null|\Laminas\Db\Adapter\Driver\Pgsql\Pgsql|\Laminas\Db\Adapter\Driver\Pdo\Pdo|resource|\PDO $driver
*/
public function __construct($driver = null)
{
if ($driver) {
$this->setDriver($driver);
}
}
/**
* @param Pgsql\Pgsql|Pdo\Pdo|resource|\PDO $driver
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setDriver($driver)
{
if (
$driver instanceof Pgsql\Pgsql
|| ($driver instanceof Pdo\Pdo && $driver->getDatabasePlatformName() === 'Postgresql')
|| $driver instanceof PgSqlConnection // PHP 8.1+
|| (is_resource($driver) && in_array(get_resource_type($driver), $this->knownPgsqlResources, true))
|| ($driver instanceof \PDO && $driver->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'pgsql')
) {
$this->driver = $driver;
return $this;
}
throw new Exception\InvalidArgumentException(
'$driver must be a Pgsql or Postgresql PDO Laminas\Db\Adapter\Driver, pgsql link resource'
. ' or Postgresql PDO instance'
);
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'PostgreSQL';
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierChain($identifierChain)
{
return '"' . implode('"."', (array) str_replace('"', '""', $identifierChain)) . '"';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
$quotedViaDriverValue = $this->quoteViaDriver($value);
return $quotedViaDriverValue ?? 'E' . parent::quoteValue($value);
}
/**
* {@inheritDoc}
*
* @param scalar $value
* @return string
*/
public function quoteTrustedValue($value)
{
$quotedViaDriverValue = $this->quoteViaDriver($value);
if ($quotedViaDriverValue === null) {
return 'E' . parent::quoteTrustedValue($value);
}
return $quotedViaDriverValue;
}
/**
* @param string $value
* @return string|null
*/
protected function quoteViaDriver($value)
{
$resource = $this->driver instanceof DriverInterface
? $this->driver->getConnection()->getResource()
: $this->driver;
if ($resource instanceof PgSqlConnection || is_resource($resource)) {
return '\'' . pg_escape_string($resource, $value) . '\'';
}
if ($resource instanceof \PDO) {
return $resource->quote($value);
}
return null;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Platform/Sql92.php | src/Adapter/Platform/Sql92.php | <?php
namespace Laminas\Db\Adapter\Platform;
use function addcslashes;
use function trigger_error;
class Sql92 extends AbstractPlatform
{
/**
* {@inheritDoc}
*/
public function getName()
{
return 'SQL92';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
trigger_error(
'Attempting to quote a value without specific driver level support'
. ' can introduce security vulnerabilities in a production environment.'
);
return '\'' . addcslashes($value ?? '', "\x00\n\r\\'\"\x1a") . '\'';
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Platform/PlatformInterface.php | src/Adapter/Platform/PlatformInterface.php | <?php
namespace Laminas\Db\Adapter\Platform;
interface PlatformInterface
{
/**
* Get name
*
* @return string
*/
public function getName();
/**
* Get quote identifier symbol
*
* @return string
*/
public function getQuoteIdentifierSymbol();
/**
* Quote identifier
*
* @param string $identifier
* @return string
*/
public function quoteIdentifier($identifier);
/**
* Quote identifier chain
*
* @param string|string[] $identifierChain
* @return string
*/
public function quoteIdentifierChain($identifierChain);
/**
* Get quote value symbol
*
* @return string
*/
public function getQuoteValueSymbol();
/**
* Quote value
*
* Will throw a notice when used in a workflow that can be considered "unsafe"
*
* @param string $value
* @return string
*/
public function quoteValue($value);
/**
* Quote Trusted Value
*
* The ability to quote values without notices
*
* @param scalar $value
* @return string
*/
public function quoteTrustedValue($value);
/**
* Quote value list
*
* @param string|string[] $valueList
* @return string
*/
public function quoteValueList($valueList);
/**
* Get identifier separator
*
* @return string
*/
public function getIdentifierSeparator();
/**
* Quote identifier in fragment
*
* @param string $identifier
* @param array $additionalSafeWords
* @return string
*/
public function quoteIdentifierInFragment($identifier, array $additionalSafeWords = []);
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Platform/SqlServer.php | src/Adapter/Platform/SqlServer.php | <?php
namespace Laminas\Db\Adapter\Platform;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Driver\Pdo;
use Laminas\Db\Adapter\Driver\Sqlsrv\Sqlsrv;
use Laminas\Db\Adapter\Exception;
use Laminas\Db\Adapter\Exception\InvalidArgumentException;
use function addcslashes;
use function implode;
use function in_array;
use function str_replace;
use function trigger_error;
class SqlServer extends AbstractPlatform
{
/**
* {@inheritDoc}
*/
protected $quoteIdentifier = ['[', ']'];
/**
* {@inheritDoc}
*/
protected $quoteIdentifierTo = '\\';
/** @var resource|\PDO */
protected $resource;
/**
* @param null|Sqlsrv|\Laminas\Db\Adapter\Driver\Pdo\Pdo|resource|\PDO $driver
*/
public function __construct($driver = null)
{
if ($driver) {
$this->setDriver($driver);
}
}
/**
* @param Sqlsrv|\Laminas\Db\Adapter\Driver\Pdo\Pdo|resource|\PDO $driver
* @return $this Provides a fluent interface
* @throws InvalidArgumentException
*/
public function setDriver($driver)
{
// handle Laminas\Db drivers
if (
($driver instanceof Pdo\Pdo && in_array($driver->getDatabasePlatformName(), ['SqlServer', 'Dblib']))
|| ($driver instanceof \PDO && in_array($driver->getAttribute(\PDO::ATTR_DRIVER_NAME), ['sqlsrv', 'dblib']))
) {
$this->resource = $driver;
return $this;
}
throw new Exception\InvalidArgumentException(
'$driver must be a Sqlsrv PDO Laminas\Db\Adapter\Driver or Sqlsrv PDO instance'
);
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'SQLServer';
}
/**
* {@inheritDoc}
*/
public function getQuoteIdentifierSymbol()
{
return $this->quoteIdentifier;
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierChain($identifierChain)
{
return '[' . implode('].[', (array) $identifierChain) . ']';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
$resource = $this->resource;
if ($resource instanceof DriverInterface) {
$resource = $resource->getConnection()->getResource();
}
if ($resource instanceof \PDO) {
return $resource->quote($value);
}
trigger_error(
'Attempting to quote a value in ' . self::class . ' without extension/driver support '
. 'can introduce security vulnerabilities in a production environment.'
);
return '\'' . str_replace('\'', '\'\'', addcslashes($value, "\000\032")) . '\'';
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
$resource = $this->resource;
if ($resource instanceof DriverInterface) {
$resource = $resource->getConnection()->getResource();
}
if ($resource instanceof \PDO) {
return $resource->quote($value);
}
return '\'' . str_replace('\'', '\'\'', $value) . '\'';
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Platform/Sqlite.php | src/Adapter/Platform/Sqlite.php | <?php
namespace Laminas\Db\Adapter\Platform;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Driver\Pdo;
use Laminas\Db\Adapter\Exception;
class Sqlite extends AbstractPlatform
{
/** @var string[] */
protected $quoteIdentifier = ['"', '"'];
/**
* {@inheritDoc}
*/
protected $quoteIdentifierTo = '\'';
/** @var \PDO */
protected $resource;
/** @param null|Pdo\Pdo|\PDO $driver */
public function __construct($driver = null)
{
if ($driver) {
$this->setDriver($driver);
}
}
/**
* @param Pdo\Pdo|\PDO $driver
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setDriver($driver)
{
if (
(
$driver instanceof \PDO
&& $driver->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'sqlite'
)
|| (
$driver instanceof Pdo\Pdo
&& $driver->getDatabasePlatformName() === 'Sqlite'
)
) {
$this->resource = $driver;
return $this;
}
throw new Exception\InvalidArgumentException(
'$driver must be a Sqlite PDO Laminas\Db\Adapter\Driver, Sqlite PDO instance'
);
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'SQLite';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
$resource = $this->resource;
if ($resource instanceof DriverInterface) {
$resource = $resource->getConnection()->getResource();
}
if ($resource instanceof \PDO) {
return $resource->quote($value);
}
return parent::quoteValue($value);
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
$resource = $this->resource;
if ($resource instanceof DriverInterface) {
$resource = $resource->getConnection()->getResource();
}
if ($resource instanceof \PDO) {
return $resource->quote($value);
}
return parent::quoteTrustedValue($value);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Adapter/Platform/AbstractPlatform.php | src/Adapter/Platform/AbstractPlatform.php | <?php
namespace Laminas\Db\Adapter\Platform;
use function addcslashes;
use function array_map;
use function implode;
use function preg_split;
use function str_replace;
use function strtolower;
use function trigger_error;
use const PREG_SPLIT_DELIM_CAPTURE;
use const PREG_SPLIT_NO_EMPTY;
abstract class AbstractPlatform implements PlatformInterface
{
/** @var string[] */
protected $quoteIdentifier = ['"', '"'];
/** @var string */
protected $quoteIdentifierTo = '\'';
/** @var bool */
protected $quoteIdentifiers = true;
/** @var string */
protected $quoteIdentifierFragmentPattern = '/([^0-9,a-z,A-Z$_:])/i';
/**
* {@inheritDoc}
*/
public function quoteIdentifierInFragment($identifier, array $safeWords = [])
{
if (! $this->quoteIdentifiers) {
return $identifier;
}
$safeWordsInt = ['*' => true, ' ' => true, '.' => true, 'as' => true];
foreach ($safeWords as $sWord) {
$safeWordsInt[strtolower($sWord)] = true;
}
$parts = preg_split(
$this->quoteIdentifierFragmentPattern,
$identifier,
-1,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
);
$identifier = '';
foreach ($parts as $part) {
$identifier .= isset($safeWordsInt[strtolower($part)])
? $part
: $this->quoteIdentifier[0]
. str_replace($this->quoteIdentifier[0], $this->quoteIdentifierTo, $part)
. $this->quoteIdentifier[1];
}
return $identifier;
}
/**
* {@inheritDoc}
*/
public function quoteIdentifier($identifier)
{
if (! $this->quoteIdentifiers) {
return $identifier;
}
return $this->quoteIdentifier[0]
. str_replace($this->quoteIdentifier[0], $this->quoteIdentifierTo, $identifier)
. $this->quoteIdentifier[1];
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierChain($identifierChain)
{
return '"' . implode('"."', (array) str_replace('"', '\\"', $identifierChain)) . '"';
}
/**
* {@inheritDoc}
*/
public function getQuoteIdentifierSymbol()
{
return $this->quoteIdentifier[0];
}
/**
* {@inheritDoc}
*/
public function getQuoteValueSymbol()
{
return '\'';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
trigger_error(
'Attempting to quote a value in ' . static::class
. ' without extension/driver support can introduce security vulnerabilities in a production environment'
);
return '\'' . addcslashes((string) $value, "\x00\n\r\\'\"\x1a") . '\'';
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
return '\'' . addcslashes((string) $value, "\x00\n\r\\'\"\x1a") . '\'';
}
/**
* {@inheritDoc}
*/
public function quoteValueList($valueList)
{
return implode(', ', array_map([$this, 'quoteValue'], (array) $valueList));
}
/**
* {@inheritDoc}
*/
public function getIdentifierSeparator()
{
return '.';
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Sql/SqlInterface.php | src/Sql/SqlInterface.php | <?php
namespace Laminas\Db\Sql;
use Laminas\Db\Adapter\Platform\PlatformInterface;
interface SqlInterface
{
/**
* Get SQL string for statement
*
* @return string
*/
public function getSqlString(?PlatformInterface $adapterPlatform = null);
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Sql/Insert.php | src/Sql/Insert.php | <?php
namespace Laminas\Db\Sql;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Driver\Pdo\Pdo;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use function array_combine;
use function array_flip;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_values;
use function count;
use function implode;
use function is_array;
use function is_scalar;
use function range;
use function sprintf;
class Insert extends AbstractPreparableSql
{
/**
* Constants
*
* @const
*/
public const SPECIFICATION_INSERT = 'insert';
public const SPECIFICATION_SELECT = 'select';
public const VALUES_MERGE = 'merge';
public const VALUES_SET = 'set';
/**#@-*/
/** @var array Specification array */
protected $specifications = [
self::SPECIFICATION_INSERT => 'INSERT INTO %1$s (%2$s) VALUES (%3$s)',
self::SPECIFICATION_SELECT => 'INSERT INTO %1$s %2$s %3$s',
];
/** @var string|TableIdentifier */
protected $table;
/** @var string[] */
protected $columns = [];
/** @var array|Select */
protected $select;
/**
* Constructor
*
* @param null|string|TableIdentifier $table
*/
public function __construct($table = null)
{
if ($table) {
$this->into($table);
}
}
/**
* Create INTO clause
*
* @param string|TableIdentifier $table
* @return $this Provides a fluent interface
*/
public function into($table)
{
$this->table = $table;
return $this;
}
/**
* Specify columns
*
* @param array $columns
* @return $this Provides a fluent interface
*/
public function columns(array $columns)
{
$this->columns = array_flip($columns);
return $this;
}
/**
* Specify values to insert
*
* @param array|Select $values
* @param string $flag one of VALUES_MERGE or VALUES_SET; defaults to VALUES_SET
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function values($values, $flag = self::VALUES_SET)
{
if ($values instanceof Select) {
if ($flag === self::VALUES_MERGE) {
throw new Exception\InvalidArgumentException(
'A Laminas\Db\Sql\Select instance cannot be provided with the merge flag'
);
}
$this->select = $values;
return $this;
}
if (! is_array($values)) {
throw new Exception\InvalidArgumentException(
'values() expects an array of values or Laminas\Db\Sql\Select instance'
);
}
if ($this->select && $flag === self::VALUES_MERGE) {
throw new Exception\InvalidArgumentException(
'An array of values cannot be provided with the merge flag when a Laminas\Db\Sql\Select'
. ' instance already exists as the value source'
);
}
if ($flag === self::VALUES_SET) {
$this->columns = $this->isAssocativeArray($values)
? $values
: array_combine(array_keys($this->columns), array_values($values));
} else {
foreach ($values as $column => $value) {
$this->columns[$column] = $value;
}
}
return $this;
}
/**
* Simple test for an associative array
*
* @link http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
*
* @param array $array
* @return bool
*/
private function isAssocativeArray(array $array)
{
return array_keys($array) !== range(0, count($array) - 1);
}
/**
* Create INTO SELECT clause
*
* @return $this
*/
public function select(Select $select)
{
return $this->values($select);
}
/**
* Get raw state
*
* @param string $key
* @return mixed
*/
public function getRawState($key = null)
{
$rawState = [
'table' => $this->table,
'columns' => array_keys($this->columns),
'values' => array_values($this->columns),
];
return isset($key) && array_key_exists($key, $rawState) ? $rawState[$key] : $rawState;
}
protected function processInsert(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->select) {
return;
}
if (! $this->columns) {
throw new Exception\InvalidArgumentException('values or select should be present');
}
$columns = [];
$values = [];
$i = 0;
foreach ($this->columns as $column => $value) {
$columns[] = $platform->quoteIdentifier($column);
if (is_scalar($value) && $parameterContainer) {
// use incremental value instead of column name for PDO
// @see https://github.com/zendframework/zend-db/issues/35
if ($driver instanceof Pdo) {
$column = 'c_' . $i++;
}
$values[] = $driver->formatParameterName($column);
$parameterContainer->offsetSet($column, $value);
} else {
$values[] = $this->resolveColumnValue(
$value,
$platform,
$driver,
$parameterContainer
);
}
}
return sprintf(
$this->specifications[static::SPECIFICATION_INSERT],
$this->resolveTable($this->table, $platform, $driver, $parameterContainer),
implode(', ', $columns),
implode(', ', $values)
);
}
protected function processSelect(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if (! $this->select) {
return;
}
$selectSql = $this->processSubSelect($this->select, $platform, $driver, $parameterContainer);
$columns = array_map([$platform, 'quoteIdentifier'], array_keys($this->columns));
$columns = implode(', ', $columns);
return sprintf(
$this->specifications[static::SPECIFICATION_SELECT],
$this->resolveTable($this->table, $platform, $driver, $parameterContainer),
$columns ? "($columns)" : "",
$selectSql
);
}
/**
* Overloading: variable setting
*
* Proxies to values, using VALUES_MERGE strategy
*
* @param string $name
* @param mixed $value
* @return $this Provides a fluent interface
*/
public function __set($name, $value)
{
$this->columns[$name] = $value;
return $this;
}
/**
* Overloading: variable unset
*
* Proxies to values and columns
*
* @param string $name
* @throws Exception\InvalidArgumentException
* @return void
*/
public function __unset($name)
{
if (! array_key_exists($name, $this->columns)) {
throw new Exception\InvalidArgumentException(
'The key ' . $name . ' was not found in this objects column list'
);
}
unset($this->columns[$name]);
}
/**
* Overloading: variable isset
*
* Proxies to columns; does a column of that name exist?
*
* @param string $name
* @return bool
*/
public function __isset($name)
{
return array_key_exists($name, $this->columns);
}
/**
* Overloading: variable retrieval
*
* Retrieves value by column name
*
* @param string $name
* @throws Exception\InvalidArgumentException
* @return mixed
*/
public function __get($name)
{
if (! array_key_exists($name, $this->columns)) {
throw new Exception\InvalidArgumentException(
'The key ' . $name . ' was not found in this objects column list'
);
}
return $this->columns[$name];
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Sql/Expression.php | src/Sql/Expression.php | <?php
namespace Laminas\Db\Sql;
use function array_unique;
use function count;
use function is_array;
use function is_scalar;
use function is_string;
use function preg_match_all;
use function str_ireplace;
use function str_replace;
class Expression extends AbstractExpression
{
/**
* @const
*/
public const PLACEHOLDER = '?';
/** @var string */
protected $expression = '';
/** @var array */
protected $parameters = [];
/** @var array */
protected $types = [];
/**
* @param string $expression
* @param string|array $parameters
* @param array $types @deprecated will be dropped in version 3.0.0
*/
public function __construct($expression = '', $parameters = null, array $types = [])
{
if ($expression !== '') {
$this->setExpression($expression);
}
if ($types) { // should be deprecated and removed version 3.0.0
if (is_array($parameters)) {
foreach ($parameters as $i => $parameter) {
$parameters[$i] = [
$parameter => $types[$i] ?? self::TYPE_VALUE,
];
}
} elseif (is_scalar($parameters)) {
$parameters = [
$parameters => $types[0],
];
}
}
if ($parameters !== null) {
$this->setParameters($parameters);
}
}
/**
* @param string $expression
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setExpression($expression)
{
if (! is_string($expression) || $expression === '') {
throw new Exception\InvalidArgumentException('Supplied expression must be a string.');
}
$this->expression = $expression;
return $this;
}
/**
* @return string
*/
public function getExpression()
{
return $this->expression;
}
/**
* @param scalar|array $parameters
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setParameters($parameters)
{
if (! is_scalar($parameters) && ! is_array($parameters)) {
throw new Exception\InvalidArgumentException('Expression parameters must be a scalar or array.');
}
$this->parameters = $parameters;
return $this;
}
/**
* @return array
*/
public function getParameters()
{
return $this->parameters;
}
/**
* @deprecated
*
* @param array $types
* @return $this Provides a fluent interface
*/
public function setTypes(array $types)
{
$this->types = $types;
return $this;
}
/**
* @deprecated
*
* @return array
*/
public function getTypes()
{
return $this->types;
}
/**
* @return array
* @throws Exception\RuntimeException
*/
public function getExpressionData()
{
$parameters = is_scalar($this->parameters) ? [$this->parameters] : $this->parameters;
$parametersCount = count($parameters);
$expression = str_replace('%', '%%', $this->expression);
if ($parametersCount === 0) {
return [
str_ireplace(self::PLACEHOLDER, '', $expression),
];
}
// assign locally, escaping % signs
$expression = str_replace(self::PLACEHOLDER, '%s', $expression, $count);
// test number of replacements without considering same variable begin used many times first, which is
// faster, if the test fails then resort to regex which are slow and used rarely
if ($count !== $parametersCount) {
preg_match_all('/\:\w*/', $expression, $matches);
if ($parametersCount !== count(array_unique($matches[0]))) {
throw new Exception\RuntimeException(
'The number of replacements in the expression does not match the number of parameters'
);
}
}
foreach ($parameters as $parameter) {
[$values[], $types[]] = $this->normalizeArgument($parameter, self::TYPE_VALUE);
}
return [
[
$expression,
$values,
$types,
],
];
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/src/Sql/Update.php | src/Sql/Update.php | <?php
namespace Laminas\Db\Sql;
use Closure;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\Driver\Pdo\Pdo;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\Predicate\PredicateInterface;
use Laminas\Stdlib\PriorityList;
use function array_key_exists;
use function implode;
use function is_numeric;
use function is_scalar;
use function is_string;
use function sprintf;
use function strtolower;
/**
* @property Where $where
*/
class Update extends AbstractPreparableSql
{
/**@#++
* @const
*/
public const SPECIFICATION_UPDATE = 'update';
public const SPECIFICATION_SET = 'set';
public const SPECIFICATION_WHERE = 'where';
public const SPECIFICATION_JOIN = 'joins';
public const VALUES_MERGE = 'merge';
public const VALUES_SET = 'set';
/**@#-**/
/** @var array<string, string>|array<string, array> */
protected $specifications = [
self::SPECIFICATION_UPDATE => 'UPDATE %1$s',
self::SPECIFICATION_JOIN => [
'%1$s' => [
[3 => '%1$s JOIN %2$s ON %3$s', 'combinedby' => ' '],
],
],
self::SPECIFICATION_SET => 'SET %1$s',
self::SPECIFICATION_WHERE => 'WHERE %1$s',
];
/** @var string|TableIdentifier */
protected $table = '';
/** @var bool */
protected $emptyWhereProtection = true;
/** @var PriorityList */
protected $set;
/** @var string|Where */
protected $where;
/** @var null|Join */
protected $joins;
/**
* Constructor
*
* @param null|string|TableIdentifier $table
*/
public function __construct($table = null)
{
if ($table) {
$this->table($table);
}
$this->where = new Where();
$this->joins = new Join();
$this->set = new PriorityList();
$this->set->isLIFO(false);
}
/**
* Specify table for statement
*
* @param string|TableIdentifier $table
* @return $this Provides a fluent interface
*/
public function table($table)
{
$this->table = $table;
return $this;
}
/**
* Set key/value pairs to update
*
* @param array $values Associative array of key values
* @param string $flag One of the VALUES_* constants
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function set(array $values, $flag = self::VALUES_SET)
{
if ($flag === self::VALUES_SET) {
$this->set->clear();
}
$priority = is_numeric($flag) ? $flag : 0;
foreach ($values as $k => $v) {
if (! is_string($k)) {
throw new Exception\InvalidArgumentException('set() expects a string for the value key');
}
$this->set->insert($k, $v, $priority);
}
return $this;
}
/**
* Create where clause
*
* @param Where|Closure|string|array|PredicateInterface $predicate
* @param string $combination One of the OP_* constants from Predicate\PredicateSet
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function where($predicate, $combination = Predicate\PredicateSet::OP_AND)
{
if ($predicate instanceof Where) {
$this->where = $predicate;
} else {
$this->where->addPredicates($predicate, $combination);
}
return $this;
}
/**
* Create join clause
*
* @param string|array $name
* @param string $on
* @param string $type one of the JOIN_* constants
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function join($name, $on, $type = Join::JOIN_INNER)
{
$this->joins->join($name, $on, [], $type);
return $this;
}
/**
* @param null|string $key
* @return mixed|array<string, mixed>
*/
public function getRawState($key = null)
{
$rawState = [
'emptyWhereProtection' => $this->emptyWhereProtection,
'table' => $this->table,
'set' => $this->set->toArray(),
'where' => $this->where,
'joins' => $this->joins,
];
return isset($key) && array_key_exists($key, $rawState) ? $rawState[$key] : $rawState;
}
/** @return string */
protected function processUpdate(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
return sprintf(
$this->specifications[static::SPECIFICATION_UPDATE],
$this->resolveTable($this->table, $platform, $driver, $parameterContainer)
);
}
/** @return string */
protected function processSet(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
$setSql = [];
$i = 0;
foreach ($this->set as $column => $value) {
$prefix = $this->resolveColumnValue(
[
'column' => $column,
'fromTable' => '',
'isIdentifier' => true,
],
$platform,
$driver,
$parameterContainer,
'column'
);
$prefix .= ' = ';
if (is_scalar($value) && $parameterContainer) {
// use incremental value instead of column name for PDO
// @see https://github.com/zendframework/zend-db/issues/35
if ($driver instanceof Pdo) {
$column = 'c_' . $i++;
}
$setSql[] = $prefix . $driver->formatParameterName($column);
$parameterContainer->offsetSet($column, $value);
} else {
$setSql[] = $prefix . $this->resolveColumnValue(
$value,
$platform,
$driver,
$parameterContainer
);
}
}
return sprintf(
$this->specifications[static::SPECIFICATION_SET],
implode(', ', $setSql)
);
}
protected function processWhere(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->where->count() === 0) {
return;
}
return sprintf(
$this->specifications[static::SPECIFICATION_WHERE],
$this->processExpression($this->where, $platform, $driver, $parameterContainer, 'where')
);
}
/** @return null|string[] */
protected function processJoins(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
return $this->processJoin($this->joins, $platform, $driver, $parameterContainer);
}
/**
* Variable overloading
*
* Proxies to "where" only
*
* @param string $name
* @return mixed
*/
public function __get($name)
{
if (strtolower($name) === 'where') {
return $this->where;
}
}
/**
* __clone
*
* Resets the where object each time the Update is cloned.
*
* @return void
*/
public function __clone()
{
$this->where = clone $this->where;
$this->set = clone $this->set;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.