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/Sql/Where.php | src/Sql/Where.php | <?php
namespace Laminas\Db\Sql;
class Where extends Predicate\Predicate
{
}
| 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/TableIdentifier.php | src/Sql/TableIdentifier.php | <?php
namespace Laminas\Db\Sql;
use function gettype;
use function is_callable;
use function is_object;
use function is_string;
use function sprintf;
class TableIdentifier
{
/** @var string */
protected $table;
/** @var null|string */
protected $schema;
/**
* @param string $table
* @param null|string $schema
*/
public function __construct($table, $schema = null)
{
if (! (is_string($table) || is_callable([$table, '__toString']))) {
throw new Exception\InvalidArgumentException(sprintf(
'$table must be a valid table name, parameter of type %s given',
is_object($table) ? $table::class : gettype($table)
));
}
$this->table = (string) $table;
if ('' === $this->table) {
throw new Exception\InvalidArgumentException('$table must be a valid table name, empty string given');
}
if (null === $schema) {
$this->schema = null;
} else {
if (! (is_string($schema) || is_callable([$schema, '__toString']))) {
throw new Exception\InvalidArgumentException(sprintf(
'$schema must be a valid schema name, parameter of type %s given',
is_object($schema) ? $schema::class : gettype($schema)
));
}
$this->schema = (string) $schema;
if ('' === $this->schema) {
throw new Exception\InvalidArgumentException(
'$schema must be a valid schema name or null, empty string given'
);
}
}
}
/**
* @deprecated please use the constructor and build a new {@see TableIdentifier} instead
*
* @param string $table
*/
public function setTable($table)
{
$this->table = $table;
}
/**
* @return string
*/
public function getTable()
{
return $this->table;
}
/**
* @return bool
*/
public function hasSchema()
{
return $this->schema !== null;
}
/**
* @deprecated please use the constructor and build a new {@see TableIdentifier} instead
*
* @param null|string $schema
* @return void
*/
public function setSchema($schema)
{
$this->schema = $schema;
}
/**
* @return null|string
*/
public function getSchema()
{
return $this->schema;
}
/** @return array{0: string, 1: null|string} */
public function getTableAndSchema()
{
return [$this->table, $this->schema];
}
}
| 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/Join.php | src/Sql/Join.php | <?php
namespace Laminas\Db\Sql;
use Countable;
use Iterator;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use ReturnTypeWillChange;
use function array_shift;
use function count;
use function is_array;
use function is_string;
use function key;
use function sprintf;
/**
* Aggregate JOIN specifications.
*
* Each specification is an array with the following keys:
*
* - name: the JOIN name
* - on: the table on which the JOIN occurs
* - columns: the columns to include with the JOIN operation; defaults to
* `Select::SQL_STAR`.
* - type: the type of JOIN being performed; see the `JOIN_*` constants;
* defaults to `JOIN_INNER`
*/
class Join implements Iterator, Countable
{
public const JOIN_INNER = 'inner';
public const JOIN_OUTER = 'outer';
public const JOIN_FULL_OUTER = 'full outer';
public const JOIN_LEFT = 'left';
public const JOIN_RIGHT = 'right';
public const JOIN_RIGHT_OUTER = 'right outer';
public const JOIN_LEFT_OUTER = 'left outer';
/**
* Current iterator position.
*
* @var int
*/
private $position = 0;
/**
* JOIN specifications
*
* @var array
*/
protected $joins = [];
/**
* Initialize iterator position.
*/
public function __construct()
{
$this->position = 0;
}
/**
* Rewind iterator.
*/
#[ReturnTypeWillChange]
public function rewind()
{
$this->position = 0;
}
/**
* Return current join specification.
*
* @return array
*/
#[ReturnTypeWillChange]
public function current()
{
return $this->joins[$this->position];
}
/**
* Return the current iterator index.
*
* @return int
*/
#[ReturnTypeWillChange]
public function key()
{
return $this->position;
}
/**
* Advance to the next JOIN specification.
*/
#[ReturnTypeWillChange]
public function next()
{
++$this->position;
}
/**
* Is the iterator at a valid position?
*
* @return bool
*/
#[ReturnTypeWillChange]
public function valid()
{
return isset($this->joins[$this->position]);
}
/**
* @return array
*/
public function getJoins()
{
return $this->joins;
}
/**
* @param string|array|TableIdentifier $name A table name on which to join, or a single
* element associative array, of the form alias => table, or TableIdentifier instance
* @param string|Predicate\Expression $on A specification describing the fields to join on.
* @param string|string[]|int|int[] $columns A single column name, an array
* of column names, or (a) specification(s) such as SQL_STAR representing
* the columns to join.
* @param string $type The JOIN type to use; see the JOIN_* constants.
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException For invalid $name values.
*/
public function join($name, $on, $columns = [Select::SQL_STAR], $type = self::JOIN_INNER)
{
if (is_array($name) && (! is_string(key($name)) || count($name) !== 1)) {
throw new Exception\InvalidArgumentException(
sprintf("join() expects '%s' as a single element associative array", array_shift($name))
);
}
if (! is_array($columns)) {
$columns = [$columns];
}
$this->joins[] = [
'name' => $name,
'on' => $on,
'columns' => $columns,
'type' => $type ? $type : self::JOIN_INNER,
];
return $this;
}
/**
* Reset to an empty list of JOIN specifications.
*
* @return $this Provides a fluent interface
*/
public function reset()
{
$this->joins = [];
return $this;
}
/**
* Get count of attached predicates
*
* @return int
*/
#[ReturnTypeWillChange]
public function count()
{
return count($this->joins);
}
}
| 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/Having.php | src/Sql/Having.php | <?php
namespace Laminas\Db\Sql;
class Having extends Predicate\Predicate
{
}
| 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/Combine.php | src/Sql/Combine.php | <?php
namespace Laminas\Db\Sql;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use function array_key_exists;
use function array_merge;
use function gettype;
use function is_array;
use function is_object;
use function sprintf;
use function strtoupper;
use function trim;
/**
* Combine SQL statement - allows combining multiple select statements into one
*/
class Combine extends AbstractPreparableSql
{
public const COLUMNS = 'columns';
public const COMBINE = 'combine';
public const COMBINE_UNION = 'union';
public const COMBINE_EXCEPT = 'except';
public const COMBINE_INTERSECT = 'intersect';
/** @var string[] */
protected $specifications = [
self::COMBINE => '%1$s (%2$s) ',
];
/** @var Select[][] */
private $combine = [];
/**
* @param Select|array|null $select
* @param string $type
* @param string $modifier
*/
public function __construct($select = null, $type = self::COMBINE_UNION, $modifier = '')
{
if ($select) {
$this->combine($select, $type, $modifier);
}
}
/**
* Create combine clause
*
* @param Select|array $select
* @param string $type
* @param string $modifier
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function combine($select, $type = self::COMBINE_UNION, $modifier = '')
{
if (is_array($select)) {
foreach ($select as $combine) {
if ($combine instanceof Select) {
$combine = [$combine];
}
$this->combine(
$combine[0],
$combine[1] ?? $type,
$combine[2] ?? $modifier
);
}
return $this;
}
if (! $select instanceof Select) {
throw new Exception\InvalidArgumentException(sprintf(
'$select must be a array or instance of Select, "%s" given',
is_object($select) ? $select::class : gettype($select)
));
}
$this->combine[] = [
'select' => $select,
'type' => $type,
'modifier' => $modifier,
];
return $this;
}
/**
* Create union clause
*
* @param Select|array $select
* @param string $modifier
* @return $this
*/
public function union($select, $modifier = '')
{
return $this->combine($select, self::COMBINE_UNION, $modifier);
}
/**
* Create except clause
*
* @param Select|array $select
* @param string $modifier
* @return $this
*/
public function except($select, $modifier = '')
{
return $this->combine($select, self::COMBINE_EXCEPT, $modifier);
}
/**
* Create intersect clause
*
* @param Select|array $select
* @param string $modifier
* @return $this
*/
public function intersect($select, $modifier = '')
{
return $this->combine($select, self::COMBINE_INTERSECT, $modifier);
}
/**
* Build sql string
*
* @return string
*/
protected function buildSqlString(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if (! $this->combine) {
return;
}
$sql = '';
foreach ($this->combine as $i => $combine) {
$type = $i === 0
? ''
: strtoupper($combine['type'] . ($combine['modifier'] ? ' ' . $combine['modifier'] : ''));
$select = $this->processSubSelect($combine['select'], $platform, $driver, $parameterContainer);
$sql .= sprintf(
$this->specifications[self::COMBINE],
$type,
$select
);
}
return trim($sql, ' ');
}
/**
* @return $this Provides a fluent interface
*/
public function alignColumns()
{
if (! $this->combine) {
return $this;
}
$allColumns = [];
foreach ($this->combine as $combine) {
$allColumns = array_merge(
$allColumns,
$combine['select']->getRawState(self::COLUMNS)
);
}
foreach ($this->combine as $combine) {
$combineColumns = $combine['select']->getRawState(self::COLUMNS);
$aligned = [];
foreach ($allColumns as $alias => $column) {
$aligned[$alias] = $combineColumns[$alias] ?? new Predicate\Expression('NULL');
}
$combine['select']->columns($aligned, false);
}
return $this;
}
/**
* Get raw state
*
* @param string $key
* @return array
*/
public function getRawState($key = null)
{
$rawState = [
self::COMBINE => $this->combine,
self::COLUMNS => $this->combine
? $this->combine[0]['select']->getRawState(self::COLUMNS)
: [],
];
return isset($key) && array_key_exists($key, $rawState) ? $rawState[$key] : $rawState;
}
}
| 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/PreparableSqlInterface.php | src/Sql/PreparableSqlInterface.php | <?php
namespace Laminas\Db\Sql;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\Adapter\StatementContainerInterface;
interface PreparableSqlInterface
{
/**
* @return void
*/
public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer);
}
| 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/Literal.php | src/Sql/Literal.php | <?php
namespace Laminas\Db\Sql;
use function str_replace;
class Literal implements ExpressionInterface
{
/** @var string */
protected $literal = '';
/**
* @param string $literal
*/
public function __construct($literal = '')
{
$this->literal = $literal;
}
/**
* @param string $literal
* @return $this Provides a fluent interface
*/
public function setLiteral($literal)
{
$this->literal = $literal;
return $this;
}
/**
* @return string
*/
public function getLiteral()
{
return $this->literal;
}
/**
* @return array
*/
public function getExpressionData()
{
return [
[
str_replace('%', '%%', $this->literal),
[],
[],
],
];
}
}
| 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/ExpressionInterface.php | src/Sql/ExpressionInterface.php | <?php
namespace Laminas\Db\Sql;
interface ExpressionInterface
{
public const TYPE_IDENTIFIER = 'identifier';
public const TYPE_VALUE = 'value';
public const TYPE_LITERAL = 'literal';
public const TYPE_SELECT = 'select';
/**
* @abstract
* @return array of array|string should return an array in the format:
*
* array (
* // a sprintf formatted string
* string $specification,
*
* // the values for the above sprintf formatted string
* array $values,
*
* // an array of equal length of the $values array, with either TYPE_IDENTIFIER or TYPE_VALUE for each value
* array $types,
* )
*/
public function getExpressionData();
}
| 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/AbstractSql.php | src/Sql/AbstractSql.php | <?php
namespace Laminas\Db\Sql;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Adapter\Platform\Sql92 as DefaultAdapterPlatform;
use Laminas\Db\Sql\Platform\PlatformDecoratorInterface;
use function count;
use function current;
use function get_object_vars;
use function gettype;
use function implode;
use function is_array;
use function is_callable;
use function is_object;
use function is_string;
use function key;
use function preg_replace;
use function rtrim;
use function sprintf;
use function strtoupper;
use function vsprintf;
abstract class AbstractSql implements SqlInterface
{
/**
* Specifications for Sql String generation
*
* @var string[]|array[]
*/
protected $specifications = [];
/** @var string */
protected $processInfo = ['paramPrefix' => '', 'subselectCount' => 0];
/** @var array */
protected $instanceParameterIndex = [];
/**
* {@inheritDoc}
*/
public function getSqlString(?PlatformInterface $adapterPlatform = null)
{
$adapterPlatform = $adapterPlatform ?: new DefaultAdapterPlatform();
return $this->buildSqlString($adapterPlatform);
}
/**
* @return string
*/
protected function buildSqlString(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
$this->localizeVariables();
$sqls = [];
$parameters = [];
foreach ($this->specifications as $name => $specification) {
$parameters[$name] = $this->{'process' . $name}(
$platform,
$driver,
$parameterContainer,
$sqls,
$parameters
);
if ($specification && is_array($parameters[$name])) {
$sqls[$name] = $this->createSqlFromSpecificationAndParameters($specification, $parameters[$name]);
continue;
}
if (is_string($parameters[$name])) {
$sqls[$name] = $parameters[$name];
}
}
return rtrim(implode(' ', $sqls), "\n ,");
}
/**
* Render table with alias in from/join parts
*
* @todo move TableIdentifier concatenation here
* @param string $table
* @param string $alias
* @return string
*/
protected function renderTable($table, $alias = null)
{
return $table . ($alias ? ' AS ' . $alias : '');
}
/**
* @staticvar int $runtimeExpressionPrefix
* @param null|string $namedParameterPrefix
* @return string
* @throws Exception\RuntimeException
*/
protected function processExpression(
ExpressionInterface $expression,
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null,
$namedParameterPrefix = null
) {
$namedParameterPrefix = ! $namedParameterPrefix
? ''
: $this->processInfo['paramPrefix'] . $namedParameterPrefix;
// static counter for the number of times this method was invoked across the PHP runtime
static $runtimeExpressionPrefix = 0;
if ($parameterContainer && (! is_string($namedParameterPrefix) || $namedParameterPrefix === '')) {
$namedParameterPrefix = sprintf('expr%04dParam', ++$runtimeExpressionPrefix);
} else {
$namedParameterPrefix = preg_replace('/\s/', '__', $namedParameterPrefix);
}
$sql = '';
// initialize variables
$parts = $expression->getExpressionData();
if (! isset($this->instanceParameterIndex[$namedParameterPrefix])) {
$this->instanceParameterIndex[$namedParameterPrefix] = 1;
}
$expressionParamIndex = &$this->instanceParameterIndex[$namedParameterPrefix];
foreach ($parts as $part) {
// #7407: use $expression->getExpression() to get the unescaped
// version of the expression
if (is_string($part) && $expression instanceof Expression) {
$sql .= $expression->getExpression();
continue;
}
// If it is a string, simply tack it onto the return sql
// "specification" string
if (is_string($part)) {
$sql .= $part;
continue;
}
if (! is_array($part)) {
throw new Exception\RuntimeException(
'Elements returned from getExpressionData() array must be a string or array.'
);
}
// Process values and types (the middle and last position of the
// expression data)
$values = $part[1];
$types = $part[2] ?? [];
foreach ($values as $vIndex => $value) {
if (! isset($types[$vIndex])) {
continue;
}
$type = $types[$vIndex];
if ($value instanceof Select) {
// process sub-select
$values[$vIndex] = '('
. $this->processSubSelect($value, $platform, $driver, $parameterContainer)
. ')';
} elseif ($value instanceof ExpressionInterface) {
// recursive call to satisfy nested expressions
$values[$vIndex] = $this->processExpression(
$value,
$platform,
$driver,
$parameterContainer,
$namedParameterPrefix . $vIndex . 'subpart'
);
} elseif ($type === ExpressionInterface::TYPE_IDENTIFIER) {
$values[$vIndex] = $platform->quoteIdentifierInFragment($value);
} elseif ($type === ExpressionInterface::TYPE_VALUE) {
// if prepareType is set, it means that this particular value must be
// passed back to the statement in a way it can be used as a placeholder value
if ($parameterContainer) {
$name = $namedParameterPrefix . $expressionParamIndex++;
$parameterContainer->offsetSet($name, $value);
$values[$vIndex] = $driver->formatParameterName($name);
continue;
}
// if not a preparable statement, simply quote the value and move on
$values[$vIndex] = $platform->quoteValue($value);
} elseif ($type === ExpressionInterface::TYPE_LITERAL) {
$values[$vIndex] = $value;
}
}
// After looping the values, interpolate them into the sql string
// (they might be placeholder names, or values)
$sql .= vsprintf($part[0], $values);
}
return $sql;
}
/**
* @param string|array $specifications
* @param array $parameters
* @return string
* @throws Exception\RuntimeException
*/
protected function createSqlFromSpecificationAndParameters($specifications, $parameters)
{
if (is_string($specifications)) {
return vsprintf($specifications, $parameters);
}
$parametersCount = count($parameters);
foreach ($specifications as $specificationString => $paramSpecs) {
if ($parametersCount === count($paramSpecs)) {
break;
}
unset($specificationString, $paramSpecs);
}
if (! isset($specificationString)) {
throw new Exception\RuntimeException(
'A number of parameters was found that is not supported by this specification'
);
}
$topParameters = [];
foreach ($parameters as $position => $paramsForPosition) {
if (isset($paramSpecs[$position]['combinedby'])) {
$multiParamValues = [];
foreach ($paramsForPosition as $multiParamsForPosition) {
if (is_array($multiParamsForPosition)) {
$ppCount = count($multiParamsForPosition);
} else {
$ppCount = 1;
$multiParamsForPosition = [$multiParamsForPosition];
}
if (! isset($paramSpecs[$position][$ppCount])) {
throw new Exception\RuntimeException(sprintf(
'A number of parameters (%d) was found that is not supported by this specification',
$ppCount
));
}
$multiParamValues[] = vsprintf($paramSpecs[$position][$ppCount], $multiParamsForPosition);
}
$topParameters[] = implode($paramSpecs[$position]['combinedby'], $multiParamValues);
} elseif ($paramSpecs[$position] !== null) {
$ppCount = count($paramsForPosition);
if (! isset($paramSpecs[$position][$ppCount])) {
throw new Exception\RuntimeException(sprintf(
'A number of parameters (%d) was found that is not supported by this specification',
$ppCount
));
}
$topParameters[] = vsprintf($paramSpecs[$position][$ppCount], $paramsForPosition);
} else {
$topParameters[] = $paramsForPosition;
}
}
return vsprintf($specificationString, $topParameters);
}
/**
* @return string
*/
protected function processSubSelect(
Select $subselect,
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this instanceof PlatformDecoratorInterface) {
$decorator = clone $this;
$decorator->setSubject($subselect);
} else {
$decorator = $subselect;
}
if ($parameterContainer) {
// Track subselect prefix and count for parameters
$processInfoContext = $decorator instanceof PlatformDecoratorInterface ? $subselect : $decorator;
$this->processInfo['subselectCount']++;
$processInfoContext->processInfo['subselectCount'] = $this->processInfo['subselectCount'];
$processInfoContext->processInfo['paramPrefix'] = 'subselect'
. $processInfoContext->processInfo['subselectCount'];
$sql = $decorator->buildSqlString($platform, $driver, $parameterContainer);
// copy count
$this->processInfo['subselectCount'] = $decorator->processInfo['subselectCount'];
return $sql;
}
return $decorator->buildSqlString($platform, $driver, $parameterContainer);
}
/**
* @param Join[] $joins
* @return null|string[] Null if no joins present, array of JOIN statements
* otherwise
* @throws Exception\InvalidArgumentException For invalid JOIN table names.
*/
protected function processJoin(
Join $joins,
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if (! $joins->count()) {
return;
}
// process joins
$joinSpecArgArray = [];
foreach ($joins->getJoins() as $j => $join) {
$joinName = null;
$joinAs = null;
// table name
if (is_array($join['name'])) {
$joinName = current($join['name']);
$joinAs = $platform->quoteIdentifier(key($join['name']));
} else {
$joinName = $join['name'];
}
if ($joinName instanceof Expression) {
$joinName = $joinName->getExpression();
} elseif ($joinName instanceof TableIdentifier) {
$joinName = $joinName->getTableAndSchema();
$joinName = ($joinName[1]
? $platform->quoteIdentifier($joinName[1]) . $platform->getIdentifierSeparator()
: '') . $platform->quoteIdentifier($joinName[0]);
} elseif ($joinName instanceof Select) {
$joinName = '(' . $this->processSubSelect($joinName, $platform, $driver, $parameterContainer) . ')';
} elseif (is_string($joinName) || (is_object($joinName) && is_callable([$joinName, '__toString']))) {
$joinName = $platform->quoteIdentifier($joinName);
} else {
throw new Exception\InvalidArgumentException(sprintf(
'Join name expected to be Expression|TableIdentifier|Select|string, "%s" given',
gettype($joinName)
));
}
$joinSpecArgArray[$j] = [
strtoupper($join['type']),
$this->renderTable($joinName, $joinAs),
];
// on expression
// note: for Expression objects, pass them to processExpression with a prefix specific to each join
// (used for named parameters)
if ($join['on'] instanceof ExpressionInterface) {
$joinSpecArgArray[$j][] = $this->processExpression(
$join['on'],
$platform,
$driver,
$parameterContainer,
'join' . ($j + 1) . 'part'
);
} else {
// on
$joinSpecArgArray[$j][] = $platform->quoteIdentifierInFragment(
$join['on'],
['=', 'AND', 'OR', '(', ')', 'BETWEEN', '<', '>']
);
}
}
return [$joinSpecArgArray];
}
/**
* @param null|array|ExpressionInterface|Select $column
* @param null|string $namedParameterPrefix
* @return string
*/
protected function resolveColumnValue(
$column,
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null,
$namedParameterPrefix = null
) {
$namedParameterPrefix = ! $namedParameterPrefix
? $namedParameterPrefix
: $this->processInfo['paramPrefix'] . $namedParameterPrefix;
$isIdentifier = false;
$fromTable = '';
if (is_array($column)) {
if (isset($column['isIdentifier'])) {
$isIdentifier = (bool) $column['isIdentifier'];
}
if (isset($column['fromTable']) && $column['fromTable'] !== null) {
$fromTable = $column['fromTable'];
}
$column = $column['column'];
}
if ($column instanceof ExpressionInterface) {
return $this->processExpression($column, $platform, $driver, $parameterContainer, $namedParameterPrefix);
}
if ($column instanceof Select) {
return '(' . $this->processSubSelect($column, $platform, $driver, $parameterContainer) . ')';
}
if ($column === null) {
return 'NULL';
}
return $isIdentifier
? $fromTable . $platform->quoteIdentifierInFragment($column)
: $platform->quoteValue($column);
}
/**
* @param string|TableIdentifier|Select $table
* @return string
*/
protected function resolveTable(
$table,
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
$schema = null;
if ($table instanceof TableIdentifier) {
[$table, $schema] = $table->getTableAndSchema();
}
if ($table instanceof Select) {
$table = '(' . $this->processSubselect($table, $platform, $driver, $parameterContainer) . ')';
} elseif ($table) {
$table = $platform->quoteIdentifier($table);
}
if ($schema && $table) {
$table = $platform->quoteIdentifier($schema) . $platform->getIdentifierSeparator() . $table;
}
return $table;
}
/**
* Copy variables from the subject into the local properties
*/
protected function localizeVariables()
{
if (! $this instanceof PlatformDecoratorInterface) {
return;
}
foreach (get_object_vars($this->subject) as $name => $value) {
$this->{$name} = $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/Sql/InsertIgnore.php | src/Sql/InsertIgnore.php | <?php
namespace Laminas\Db\Sql;
class InsertIgnore extends Insert
{
/** @var array Specification array */
protected $specifications = [
self::SPECIFICATION_INSERT => 'INSERT IGNORE INTO %1$s (%2$s) VALUES (%3$s)',
self::SPECIFICATION_SELECT => 'INSERT IGNORE INTO %1$s %2$s %3$s',
];
}
| 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/Sql.php | src/Sql/Sql.php | <?php
namespace Laminas\Db\Sql;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\Adapter\Driver\StatementInterface;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use function is_array;
use function is_string;
use function sprintf;
class Sql
{
/** @var AdapterInterface */
protected $adapter;
/** @var string|array|TableIdentifier */
protected $table;
/** @var Platform\Platform */
protected $sqlPlatform;
/**
* @param null|string|array|TableIdentifier $table
* @param null|Platform\AbstractPlatform $sqlPlatform @deprecated since version 3.0
*/
public function __construct(
AdapterInterface $adapter,
$table = null,
?Platform\AbstractPlatform $sqlPlatform = null
) {
$this->adapter = $adapter;
if ($table) {
$this->setTable($table);
}
$this->sqlPlatform = $sqlPlatform ?: new Platform\Platform($adapter);
}
/**
* @return null|AdapterInterface
*/
public function getAdapter()
{
return $this->adapter;
}
/** @return bool */
public function hasTable()
{
return $this->table !== null;
}
/**
* @param string|array|TableIdentifier $table
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setTable($table)
{
if (is_string($table) || is_array($table) || $table instanceof TableIdentifier) {
$this->table = $table;
} else {
throw new Exception\InvalidArgumentException(
'Table must be a string, array or instance of TableIdentifier.'
);
}
return $this;
}
/** @return string|array|TableIdentifier */
public function getTable()
{
return $this->table;
}
/** @return Platform\Platform */
public function getSqlPlatform()
{
return $this->sqlPlatform;
}
/**
* @param null|string|TableIdentifier $table
* @return Select
*/
public function select($table = null)
{
if ($this->table !== null && $table !== null) {
throw new Exception\InvalidArgumentException(sprintf(
'This Sql object is intended to work with only the table "%s" provided at construction time.',
$this->table
));
}
return new Select($table ?: $this->table);
}
/**
* @param null|string|TableIdentifier $table
* @return Insert
*/
public function insert($table = null)
{
if ($this->table !== null && $table !== null) {
throw new Exception\InvalidArgumentException(sprintf(
'This Sql object is intended to work with only the table "%s" provided at construction time.',
$this->table
));
}
return new Insert($table ?: $this->table);
}
/**
* @param null|string|TableIdentifier $table
* @return Update
*/
public function update($table = null)
{
if ($this->table !== null && $table !== null) {
throw new Exception\InvalidArgumentException(sprintf(
'This Sql object is intended to work with only the table "%s" provided at construction time.',
$this->table
));
}
return new Update($table ?: $this->table);
}
/**
* @param null|string|TableIdentifier $table
* @return Delete
*/
public function delete($table = null)
{
if ($this->table !== null && $table !== null) {
throw new Exception\InvalidArgumentException(sprintf(
'This Sql object is intended to work with only the table "%s" provided at construction time.',
$this->table
));
}
return new Delete($table ?: $this->table);
}
/**
* @return StatementInterface
*/
public function prepareStatementForSqlObject(
PreparableSqlInterface $sqlObject,
?StatementInterface $statement = null,
?AdapterInterface $adapter = null
) {
$adapter = $adapter ?: $this->adapter;
$statement = $statement ?: $adapter->getDriver()->createStatement();
return $this->sqlPlatform->setSubject($sqlObject)->prepareStatement($adapter, $statement);
}
/**
* Get sql string using platform or sql object
*
* @deprecated Deprecated in 2.4. Use buildSqlString() instead
*
* @return string
*/
public function getSqlStringForSqlObject(SqlInterface $sqlObject, ?PlatformInterface $platform = null)
{
$platform = $platform ?: $this->adapter->getPlatform();
return $this->sqlPlatform->setSubject($sqlObject)->getSqlString($platform);
}
/**
* @return string
* @throws Exception\InvalidArgumentException
*/
public function buildSqlString(SqlInterface $sqlObject, ?AdapterInterface $adapter = null)
{
return $this
->sqlPlatform
->setSubject($sqlObject)
->getSqlString($adapter ? $adapter->getPlatform() : $this->adapter->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/Sql/Delete.php | src/Sql/Delete.php | <?php
namespace Laminas\Db\Sql;
use Closure;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\Predicate\PredicateInterface;
use function array_key_exists;
use function sprintf;
use function strtolower;
/**
* @property Where $where
*/
class Delete extends AbstractPreparableSql
{
/**@#+
* @const
*/
public const SPECIFICATION_DELETE = 'delete';
public const SPECIFICATION_WHERE = 'where';
/**@#-*/
/**
* {@inheritDoc}
*/
protected $specifications = [
self::SPECIFICATION_DELETE => 'DELETE FROM %1$s',
self::SPECIFICATION_WHERE => 'WHERE %1$s',
];
/** @var string|TableIdentifier */
protected $table = '';
/** @var bool */
protected $emptyWhereProtection = true;
/** @var array */
protected $set = [];
/** @var null|string|Where */
protected $where;
/**
* Constructor
*
* @param null|string|TableIdentifier $table
*/
public function __construct($table = null)
{
if ($table) {
$this->from($table);
}
$this->where = new Where();
}
/**
* Create from statement
*
* @param string|TableIdentifier $table
* @return $this Provides a fluent interface
*/
public function from($table)
{
$this->table = $table;
return $this;
}
/**
* @param null $key
* @return mixed
*/
public function getRawState($key = null)
{
$rawState = [
'emptyWhereProtection' => $this->emptyWhereProtection,
'table' => $this->table,
'set' => $this->set,
'where' => $this->where,
];
return isset($key) && array_key_exists($key, $rawState) ? $rawState[$key] : $rawState;
}
/**
* 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
*/
public function where($predicate, $combination = Predicate\PredicateSet::OP_AND)
{
if ($predicate instanceof Where) {
$this->where = $predicate;
} else {
$this->where->addPredicates($predicate, $combination);
}
return $this;
}
/**
* @return string
*/
protected function processDelete(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
return sprintf(
$this->specifications[static::SPECIFICATION_DELETE],
$this->resolveTable($this->table, $platform, $driver, $parameterContainer)
);
}
/**
* @return null|string
*/
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')
);
}
/**
* Property overloading
*
* Overloads "where" only.
*
* @param string $name
* @return Where|null
*/
public function __get($name)
{
switch (strtolower($name)) {
case 'where':
return $this->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/Sql/Select.php | src/Sql/Select.php | <?php
namespace Laminas\Db\Sql;
use Closure;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\Predicate\PredicateInterface;
use function array_key_exists;
use function count;
use function current;
use function gettype;
use function is_array;
use function is_int;
use function is_numeric;
use function is_object;
use function is_scalar;
use function is_string;
use function key;
use function method_exists;
use function preg_split;
use function sprintf;
use function strcasecmp;
use function stripos;
use function strpos;
use function strtolower;
use function strtoupper;
use function trim;
/**
* @property Where $where
* @property Having $having
* @property Join $joins
*/
class Select extends AbstractPreparableSql
{
/**#@+
* Constant
*
* @const
*/
public const SELECT = 'select';
public const QUANTIFIER = 'quantifier';
public const COLUMNS = 'columns';
public const TABLE = 'table';
public const JOINS = 'joins';
public const WHERE = 'where';
public const GROUP = 'group';
public const HAVING = 'having';
public const ORDER = 'order';
public const LIMIT = 'limit';
public const OFFSET = 'offset';
public const QUANTIFIER_DISTINCT = 'DISTINCT';
public const QUANTIFIER_ALL = 'ALL';
public const JOIN_INNER = Join::JOIN_INNER;
public const JOIN_OUTER = Join::JOIN_OUTER;
public const JOIN_FULL_OUTER = Join::JOIN_FULL_OUTER;
public const JOIN_LEFT = Join::JOIN_LEFT;
public const JOIN_RIGHT = Join::JOIN_RIGHT;
public const JOIN_RIGHT_OUTER = Join::JOIN_RIGHT_OUTER;
public const JOIN_LEFT_OUTER = Join::JOIN_LEFT_OUTER;
public const SQL_STAR = '*';
public const ORDER_ASCENDING = 'ASC';
public const ORDER_DESCENDING = 'DESC';
public const COMBINE = 'combine';
public const COMBINE_UNION = 'union';
public const COMBINE_EXCEPT = 'except';
public const COMBINE_INTERSECT = 'intersect';
/**#@-*/
/**
* @deprecated use JOIN_LEFT_OUTER instead
*/
public const JOIN_OUTER_LEFT = 'outer left';
/**
* @deprecated use JOIN_LEFT_OUTER instead
*/
public const JOIN_OUTER_RIGHT = 'outer right';
/** @var array Specifications */
protected $specifications = [
'statementStart' => '%1$s',
self::SELECT => [
'SELECT %1$s FROM %2$s' => [
[1 => '%1$s', 2 => '%1$s AS %2$s', 'combinedby' => ', '],
null,
],
'SELECT %1$s %2$s FROM %3$s' => [
null,
[1 => '%1$s', 2 => '%1$s AS %2$s', 'combinedby' => ', '],
null,
],
'SELECT %1$s' => [
[1 => '%1$s', 2 => '%1$s AS %2$s', 'combinedby' => ', '],
],
],
self::JOINS => [
'%1$s' => [
[3 => '%1$s JOIN %2$s ON %3$s', 'combinedby' => ' '],
],
],
self::WHERE => 'WHERE %1$s',
self::GROUP => [
'GROUP BY %1$s' => [
[1 => '%1$s', 'combinedby' => ', '],
],
],
self::HAVING => 'HAVING %1$s',
self::ORDER => [
'ORDER BY %1$s' => [
[1 => '%1$s', 2 => '%1$s %2$s', 'combinedby' => ', '],
],
],
self::LIMIT => 'LIMIT %1$s',
self::OFFSET => 'OFFSET %1$s',
'statementEnd' => '%1$s',
self::COMBINE => '%1$s ( %2$s )',
];
/** @var bool */
protected $tableReadOnly = false;
/** @var bool */
protected $prefixColumnsWithTable = true;
/** @var string|array|TableIdentifier */
protected $table;
/** @var null|string|Expression */
protected $quantifier;
/** @var array */
protected $columns = [self::SQL_STAR];
/** @var null|Join */
protected $joins;
/** @var Where */
protected $where;
/** @var array */
protected $order = [];
/** @var null|array */
protected $group;
/** @var null|string|array */
protected $having;
/** @var int|null */
protected $limit;
/** @var int|null */
protected $offset;
/** @var array */
protected $combine = [];
/**
* Constructor
*
* @param null|string|array|TableIdentifier $table
*/
public function __construct($table = null)
{
if ($table) {
$this->from($table);
$this->tableReadOnly = true;
}
$this->where = new Where();
$this->joins = new Join();
$this->having = new Having();
}
/**
* Create from clause
*
* @param string|array|TableIdentifier $table
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function from($table)
{
if ($this->tableReadOnly) {
throw new Exception\InvalidArgumentException(
'Since this object was created with a table and/or schema in the constructor, it is read only.'
);
}
if (! is_string($table) && ! is_array($table) && ! $table instanceof TableIdentifier) {
throw new Exception\InvalidArgumentException(
'$table must be a string, array, or an instance of TableIdentifier'
);
}
if (is_array($table) && (! is_string(key($table)) || count($table) !== 1)) {
throw new Exception\InvalidArgumentException(
'from() expects $table as an array is a single element associative array'
);
}
$this->table = $table;
return $this;
}
/**
* @param string|Expression $quantifier DISTINCT|ALL
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function quantifier($quantifier)
{
if (! is_string($quantifier) && ! $quantifier instanceof ExpressionInterface) {
throw new Exception\InvalidArgumentException(
'Quantifier must be one of DISTINCT, ALL, or some platform specific object implementing '
. 'ExpressionInterface'
);
}
$this->quantifier = $quantifier;
return $this;
}
/**
* Specify columns from which to select
*
* Possible valid states:
*
* array(*)
*
* array(value, ...)
* value can be strings or Expression objects
*
* array(string => value, ...)
* key string will be use as alias,
* value can be string or Expression objects
*
* @param array $columns
* @param bool $prefixColumnsWithTable
* @return $this Provides a fluent interface
*/
public function columns(array $columns, $prefixColumnsWithTable = true)
{
$this->columns = $columns;
$this->prefixColumnsWithTable = (bool) $prefixColumnsWithTable;
return $this;
}
/**
* Create join clause
*
* @param string|array|TableIdentifier $name
* @param string|Predicate\Expression $on
* @param string|array $columns
* @param string $type one of the JOIN_* constants
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function join($name, $on, $columns = self::SQL_STAR, $type = self::JOIN_INNER)
{
$this->joins->join($name, $on, $columns, $type);
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;
}
/**
* @param mixed $group
* @return $this Provides a fluent interface
*/
public function group($group)
{
if (is_array($group)) {
foreach ($group as $o) {
$this->group[] = $o;
}
} else {
$this->group[] = $group;
}
return $this;
}
/**
* Create having clause
*
* @param Having|Closure|string|array|PredicateInterface $predicate
* @param string $combination One of the OP_* constants from Predicate\PredicateSet
* @return $this Provides a fluent interface
*/
public function having($predicate, $combination = Predicate\PredicateSet::OP_AND)
{
if ($predicate instanceof Having) {
$this->having = $predicate;
} else {
$this->having->addPredicates($predicate, $combination);
}
return $this;
}
/**
* @param string|array|Expression $order
* @return $this Provides a fluent interface
*/
public function order($order)
{
if (is_string($order)) {
if (strpos($order, ',') !== false) {
$order = preg_split('#,\s+#', $order);
} else {
$order = (array) $order;
}
} elseif (! is_array($order)) {
$order = [$order];
}
foreach ($order as $k => $v) {
if (is_string($k)) {
$this->order[$k] = $v;
} else {
$this->order[] = $v;
}
}
return $this;
}
/**
* @param int $limit
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function limit($limit)
{
if (! is_numeric($limit)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects parameter to be numeric, "%s" given',
__METHOD__,
is_object($limit) ? $limit::class : gettype($limit)
));
}
$this->limit = $limit;
return $this;
}
/**
* @param int $offset
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function offset($offset)
{
if (! is_numeric($offset)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects parameter to be numeric, "%s" given',
__METHOD__,
is_object($offset) ? $offset::class : gettype($offset)
));
}
$this->offset = $offset;
return $this;
}
/**
* @param string $type
* @param string $modifier
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function combine(Select $select, $type = self::COMBINE_UNION, $modifier = '')
{
if ($this->combine !== []) {
throw new Exception\InvalidArgumentException(
'This Select object is already combined and cannot be combined with multiple Selects objects'
);
}
$this->combine = [
'select' => $select,
'type' => $type,
'modifier' => $modifier,
];
return $this;
}
/**
* @param string $part
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function reset($part)
{
switch ($part) {
case self::TABLE:
if ($this->tableReadOnly) {
throw new Exception\InvalidArgumentException(
'Since this object was created with a table and/or schema in the constructor, it is read only.'
);
}
$this->table = null;
break;
case self::QUANTIFIER:
$this->quantifier = null;
break;
case self::COLUMNS:
$this->columns = [];
break;
case self::JOINS:
$this->joins = new Join();
break;
case self::WHERE:
$this->where = new Where();
break;
case self::GROUP:
$this->group = null;
break;
case self::HAVING:
$this->having = new Having();
break;
case self::LIMIT:
$this->limit = null;
break;
case self::OFFSET:
$this->offset = null;
break;
case self::ORDER:
$this->order = [];
break;
case self::COMBINE:
$this->combine = [];
break;
}
return $this;
}
/**
* @param string $index
* @param string|array<string, array> $specification
* @return $this Provides a fluent interface
*/
public function setSpecification($index, $specification)
{
if (! method_exists($this, 'process' . $index)) {
throw new Exception\InvalidArgumentException('Not a valid specification name.');
}
$this->specifications[$index] = $specification;
return $this;
}
/**
* @param null|string $key
* @return array<string, mixed>|mixed
*/
public function getRawState($key = null)
{
$rawState = [
self::TABLE => $this->table,
self::QUANTIFIER => $this->quantifier,
self::COLUMNS => $this->columns,
self::JOINS => $this->joins,
self::WHERE => $this->where,
self::ORDER => $this->order,
self::GROUP => $this->group,
self::HAVING => $this->having,
self::LIMIT => $this->limit,
self::OFFSET => $this->offset,
self::COMBINE => $this->combine,
];
return isset($key) && array_key_exists($key, $rawState) ? $rawState[$key] : $rawState;
}
/**
* Returns whether the table is read only or not.
*
* @return bool
*/
public function isTableReadOnly()
{
return $this->tableReadOnly;
}
/** @return string[]|null */
protected function processStatementStart(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->combine !== []) {
return ['('];
}
return null;
}
/** @return string[]|null */
protected function processStatementEnd(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->combine !== []) {
return [')'];
}
return null;
}
/**
* Process the select part
*
* @return null|array
*/
protected function processSelect(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
$expr = 1;
[$table, $fromTable] = $this->resolveTable($this->table, $platform, $driver, $parameterContainer);
// process table columns
$columns = [];
foreach ($this->columns as $columnIndexOrAs => $column) {
if ($column === self::SQL_STAR) {
$columns[] = [$fromTable . self::SQL_STAR];
continue;
}
$columnName = $this->resolveColumnValue(
[
'column' => $column,
'fromTable' => $fromTable,
'isIdentifier' => true,
],
$platform,
$driver,
$parameterContainer,
is_string($columnIndexOrAs) ? $columnIndexOrAs : 'column'
);
// process As portion
if (is_string($columnIndexOrAs)) {
$columnAs = $platform->quoteIdentifier($columnIndexOrAs);
} elseif (stripos($columnName, ' as ') === false) {
$columnAs = is_string($column) ? $platform->quoteIdentifier($column) : 'Expression' . $expr++;
}
$columns[] = isset($columnAs) ? [$columnName, $columnAs] : [$columnName];
}
// process join columns
foreach ($this->joins->getJoins() as $join) {
$joinName = is_array($join['name']) ? key($join['name']) : $join['name'];
$joinName = parent::resolveTable($joinName, $platform, $driver, $parameterContainer);
foreach ($join['columns'] as $jKey => $jColumn) {
$jColumns = [];
$jFromTable = is_scalar($jColumn)
? $joinName . $platform->getIdentifierSeparator()
: '';
$jColumns[] = $this->resolveColumnValue(
[
'column' => $jColumn,
'fromTable' => $jFromTable,
'isIdentifier' => true,
],
$platform,
$driver,
$parameterContainer,
is_string($jKey) ? $jKey : 'column'
);
if (is_string($jKey)) {
$jColumns[] = $platform->quoteIdentifier($jKey);
} elseif ($jColumn !== self::SQL_STAR) {
$jColumns[] = $platform->quoteIdentifier($jColumn);
}
$columns[] = $jColumns;
}
}
if ($this->quantifier) {
$quantifier = $this->quantifier instanceof ExpressionInterface
? $this->processExpression($this->quantifier, $platform, $driver, $parameterContainer, 'quantifier')
: $this->quantifier;
}
if (! isset($table)) {
return [$columns];
} elseif (isset($quantifier)) {
return [$quantifier, $columns, $table];
} else {
return [$columns, $table];
}
}
/** @return null|string[] */
protected function processJoins(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
return $this->processJoin($this->joins, $platform, $driver, $parameterContainer);
}
protected function processWhere(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->where->count() === 0) {
return;
}
return [
$this->processExpression($this->where, $platform, $driver, $parameterContainer, 'where'),
];
}
protected function processGroup(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->group === null) {
return;
}
// process table columns
$groups = [];
foreach ($this->group as $column) {
$groups[] = $this->resolveColumnValue(
[
'column' => $column,
'isIdentifier' => true,
],
$platform,
$driver,
$parameterContainer,
'group'
);
}
return [$groups];
}
protected function processHaving(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->having->count() === 0) {
return;
}
return [
$this->processExpression($this->having, $platform, $driver, $parameterContainer, 'having'),
];
}
protected function processOrder(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if (empty($this->order)) {
return;
}
$orders = [];
foreach ($this->order as $k => $v) {
if ($v instanceof ExpressionInterface) {
$orders[] = [
$this->processExpression($v, $platform, $driver, $parameterContainer),
];
continue;
}
if (is_int($k)) {
if (strpos($v, ' ') !== false) {
[$k, $v] = preg_split('# #', $v, 2);
} else {
$k = $v;
$v = self::ORDER_ASCENDING;
}
}
if (strcasecmp(trim($v), self::ORDER_DESCENDING) === 0) {
$orders[] = [$platform->quoteIdentifierInFragment($k), self::ORDER_DESCENDING];
} else {
$orders[] = [$platform->quoteIdentifierInFragment($k), self::ORDER_ASCENDING];
}
}
return [$orders];
}
protected function processLimit(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->limit === null) {
return;
}
if ($parameterContainer) {
$paramPrefix = $this->processInfo['paramPrefix'];
$parameterContainer->offsetSet($paramPrefix . 'limit', $this->limit, ParameterContainer::TYPE_INTEGER);
return [$driver->formatParameterName($paramPrefix . 'limit')];
}
return [$platform->quoteValue($this->limit)];
}
protected function processOffset(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->offset === null) {
return;
}
if ($parameterContainer) {
$paramPrefix = $this->processInfo['paramPrefix'];
$parameterContainer->offsetSet($paramPrefix . 'offset', $this->offset, ParameterContainer::TYPE_INTEGER);
return [$driver->formatParameterName($paramPrefix . 'offset')];
}
return [$platform->quoteValue($this->offset)];
}
protected function processCombine(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->combine === []) {
return;
}
$type = $this->combine['type'];
if ($this->combine['modifier']) {
$type .= ' ' . $this->combine['modifier'];
}
return [
strtoupper($type),
$this->processSubSelect($this->combine['select'], $platform, $driver, $parameterContainer),
];
}
/**
* Variable overloading
*
* @param string $name
* @throws Exception\InvalidArgumentException
* @return mixed
*/
public function __get($name)
{
switch (strtolower($name)) {
case 'where':
return $this->where;
case 'having':
return $this->having;
case 'joins':
return $this->joins;
default:
throw new Exception\InvalidArgumentException('Not a valid magic property for this object');
}
}
/**
* __clone
*
* Resets the where object each time the Select is cloned.
*
* @return void
*/
public function __clone()
{
$this->where = clone $this->where;
$this->joins = clone $this->joins;
$this->having = clone $this->having;
}
/**
* @param string|TableIdentifier|Select $table
* @return string
*/
protected function resolveTable(
$table,
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
$alias = null;
if (is_array($table)) {
$alias = key($table);
$table = current($table);
}
$table = parent::resolveTable($table, $platform, $driver, $parameterContainer);
if ($alias) {
$fromTable = $platform->quoteIdentifier($alias);
$table = $this->renderTable($table, $fromTable);
} else {
$fromTable = $table;
}
if ($this->prefixColumnsWithTable && $fromTable) {
$fromTable .= $platform->getIdentifierSeparator();
} else {
$fromTable = '';
}
return [
$table,
$fromTable,
];
}
}
| 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/AbstractExpression.php | src/Sql/AbstractExpression.php | <?php
namespace Laminas\Db\Sql;
use Laminas\Db\Sql\ExpressionInterface;
use Laminas\Db\Sql\SqlInterface;
use function current;
use function gettype;
use function implode;
use function in_array;
use function is_array;
use function is_int;
use function is_object;
use function is_scalar;
use function key;
use function sprintf;
abstract class AbstractExpression implements ExpressionInterface
{
/** @var string[] */
protected $allowedTypes = [
self::TYPE_IDENTIFIER,
self::TYPE_LITERAL,
self::TYPE_SELECT,
self::TYPE_VALUE,
];
/**
* Normalize Argument
*
* @param mixed $argument
* @param string $defaultType
* @return array
* @throws Exception\InvalidArgumentException
*/
protected function normalizeArgument($argument, $defaultType = self::TYPE_VALUE)
{
if ($argument instanceof ExpressionInterface || $argument instanceof SqlInterface) {
return $this->buildNormalizedArgument($argument, self::TYPE_VALUE);
}
if (is_scalar($argument) || $argument === null) {
return $this->buildNormalizedArgument($argument, $defaultType);
}
if (is_array($argument)) {
$value = current($argument);
if ($value instanceof ExpressionInterface || $value instanceof SqlInterface) {
return $this->buildNormalizedArgument($value, self::TYPE_VALUE);
}
$key = key($argument);
if (is_int($key) && ! in_array($value, $this->allowedTypes)) {
return $this->buildNormalizedArgument($value, $defaultType);
}
return $this->buildNormalizedArgument($key, $value);
}
throw new Exception\InvalidArgumentException(sprintf(
'$argument should be %s or %s or %s or %s or %s, "%s" given',
'null',
'scalar',
'array',
ExpressionInterface::class,
SqlInterface::class,
is_object($argument) ? $argument::class : gettype($argument)
));
}
/**
* @param mixed $argument
* @param string $argumentType
* @return array
* @throws Exception\InvalidArgumentException
*/
private function buildNormalizedArgument($argument, $argumentType)
{
if (! in_array($argumentType, $this->allowedTypes)) {
throw new Exception\InvalidArgumentException(sprintf(
'Argument type should be in array(%s)',
implode(',', $this->allowedTypes)
));
}
return [
$argument,
$argumentType,
];
}
}
| 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/AbstractPreparableSql.php | src/Sql/AbstractPreparableSql.php | <?php
namespace Laminas\Db\Sql;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\StatementContainerInterface;
abstract class AbstractPreparableSql extends AbstractSql implements PreparableSqlInterface
{
/**
* {@inheritDoc}
*
* @return StatementContainerInterface
*/
public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer)
{
$parameterContainer = $statementContainer->getParameterContainer();
if (! $parameterContainer instanceof ParameterContainer) {
$parameterContainer = new ParameterContainer();
$statementContainer->setParameterContainer($parameterContainer);
}
$statementContainer->setSql(
$this->buildSqlString($adapter->getPlatform(), $adapter->getDriver(), $parameterContainer)
);
return $statementContainer;
}
}
| 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/Ddl/DropTable.php | src/Sql/Ddl/DropTable.php | <?php
namespace Laminas\Db\Sql\Ddl;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\AbstractSql;
use Laminas\Db\Sql\TableIdentifier;
class DropTable extends AbstractSql implements SqlInterface
{
public const TABLE = 'table';
/** @var array */
protected $specifications = [
self::TABLE => 'DROP TABLE %1$s',
];
/** @var string */
protected $table = '';
/**
* @param string|TableIdentifier $table
*/
public function __construct($table = '')
{
$this->table = $table;
}
/** @return string[] */
protected function processTable(?PlatformInterface $adapterPlatform = null)
{
return [$this->resolveTable($this->table, $adapterPlatform)];
}
}
| 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/Ddl/SqlInterface.php | src/Sql/Ddl/SqlInterface.php | <?php
namespace Laminas\Db\Sql\Ddl;
use Laminas\Db\Sql\SqlInterface as BaseSqlInterface;
interface SqlInterface extends BaseSqlInterface
{
}
| 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/Ddl/CreateTable.php | src/Sql/Ddl/CreateTable.php | <?php
namespace Laminas\Db\Sql\Ddl;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\AbstractSql;
use Laminas\Db\Sql\TableIdentifier;
use function array_key_exists;
class CreateTable extends AbstractSql implements SqlInterface
{
public const COLUMNS = 'columns';
public const CONSTRAINTS = 'constraints';
public const TABLE = 'table';
/** @var Column\ColumnInterface[] */
protected $columns = [];
/** @var string[] */
protected $constraints = [];
/** @var bool */
protected $isTemporary = false;
/**
* {@inheritDoc}
*/
protected $specifications = [
self::TABLE => 'CREATE %1$sTABLE %2$s (',
self::COLUMNS => [
"\n %1\$s" => [
[1 => '%1$s', 'combinedby' => ",\n "],
],
],
'combinedBy' => ",",
self::CONSTRAINTS => [
"\n %1\$s" => [
[1 => '%1$s', 'combinedby' => ",\n "],
],
],
'statementEnd' => '%1$s',
];
/** @var string */
protected $table = '';
/**
* @param string|TableIdentifier $table
* @param bool $isTemporary
*/
public function __construct($table = '', $isTemporary = false)
{
$this->table = $table;
$this->setTemporary($isTemporary);
}
/**
* @param bool $temporary
* @return $this Provides a fluent interface
*/
public function setTemporary($temporary)
{
$this->isTemporary = (bool) $temporary;
return $this;
}
/**
* @return bool
*/
public function isTemporary()
{
return $this->isTemporary;
}
/**
* @param string $name
* @return $this Provides a fluent interface
*/
public function setTable($name)
{
$this->table = $name;
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function addColumn(Column\ColumnInterface $column)
{
$this->columns[] = $column;
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function addConstraint(Constraint\ConstraintInterface $constraint)
{
$this->constraints[] = $constraint;
return $this;
}
/**
* @param string|null $key
* @return array
*/
public function getRawState($key = null)
{
$rawState = [
self::COLUMNS => $this->columns,
self::CONSTRAINTS => $this->constraints,
self::TABLE => $this->table,
];
return isset($key) && array_key_exists($key, $rawState) ? $rawState[$key] : $rawState;
}
/**
* @return string[]
*/
protected function processTable(?PlatformInterface $adapterPlatform = null)
{
return [
$this->isTemporary ? 'TEMPORARY ' : '',
$this->resolveTable($this->table, $adapterPlatform),
];
}
/**
* @return string[][]|null
*/
protected function processColumns(?PlatformInterface $adapterPlatform = null)
{
if (! $this->columns) {
return;
}
$sqls = [];
foreach ($this->columns as $column) {
$sqls[] = $this->processExpression($column, $adapterPlatform);
}
return [$sqls];
}
/**
* @return array|string
*/
protected function processCombinedby(?PlatformInterface $adapterPlatform = null)
{
if ($this->constraints && $this->columns) {
return $this->specifications['combinedBy'];
}
}
/**
* @return string[][]|null
*/
protected function processConstraints(?PlatformInterface $adapterPlatform = null)
{
if (! $this->constraints) {
return;
}
$sqls = [];
foreach ($this->constraints as $constraint) {
$sqls[] = $this->processExpression($constraint, $adapterPlatform);
}
return [$sqls];
}
/**
* @return string[]
*/
protected function processStatementEnd(?PlatformInterface $adapterPlatform = null)
{
return ["\n)"];
}
}
| 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/Ddl/AlterTable.php | src/Sql/Ddl/AlterTable.php | <?php
namespace Laminas\Db\Sql\Ddl;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\AbstractSql;
use Laminas\Db\Sql\TableIdentifier;
use function array_key_exists;
class AlterTable extends AbstractSql implements SqlInterface
{
public const ADD_COLUMNS = 'addColumns';
public const ADD_CONSTRAINTS = 'addConstraints';
public const CHANGE_COLUMNS = 'changeColumns';
public const DROP_COLUMNS = 'dropColumns';
public const DROP_CONSTRAINTS = 'dropConstraints';
public const DROP_INDEXES = 'dropIndexes';
public const TABLE = 'table';
/** @var array */
protected $addColumns = [];
/** @var array */
protected $addConstraints = [];
/** @var array */
protected $changeColumns = [];
/** @var array */
protected $dropColumns = [];
/** @var array */
protected $dropConstraints = [];
/** @var array */
protected $dropIndexes = [];
/**
* Specifications for Sql String generation
*
* @var array
*/
protected $specifications = [
self::TABLE => "ALTER TABLE %1\$s\n",
self::ADD_COLUMNS => [
"%1\$s" => [
[1 => "ADD COLUMN %1\$s,\n", 'combinedby' => ""],
],
],
self::CHANGE_COLUMNS => [
"%1\$s" => [
[2 => "CHANGE COLUMN %1\$s %2\$s,\n", 'combinedby' => ""],
],
],
self::DROP_COLUMNS => [
"%1\$s" => [
[1 => "DROP COLUMN %1\$s,\n", 'combinedby' => ""],
],
],
self::ADD_CONSTRAINTS => [
"%1\$s" => [
[1 => "ADD %1\$s,\n", 'combinedby' => ""],
],
],
self::DROP_CONSTRAINTS => [
"%1\$s" => [
[1 => "DROP CONSTRAINT %1\$s,\n", 'combinedby' => ""],
],
],
self::DROP_INDEXES => [
'%1$s' => [
[1 => "DROP INDEX %1\$s,\n", 'combinedby' => ''],
],
],
];
/** @var string */
protected $table = '';
/**
* @param string|TableIdentifier $table
*/
public function __construct($table = '')
{
$table ? $this->setTable($table) : null;
}
/**
* @param string $name
* @return $this Provides a fluent interface
*/
public function setTable($name)
{
$this->table = $name;
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function addColumn(Column\ColumnInterface $column)
{
$this->addColumns[] = $column;
return $this;
}
/**
* @param string $name
* @return $this Provides a fluent interface
*/
public function changeColumn($name, Column\ColumnInterface $column)
{
$this->changeColumns[$name] = $column;
return $this;
}
/**
* @param string $name
* @return $this Provides a fluent interface
*/
public function dropColumn($name)
{
$this->dropColumns[] = $name;
return $this;
}
/**
* @param string $name
* @return $this Provides a fluent interface
*/
public function dropConstraint($name)
{
$this->dropConstraints[] = $name;
return $this;
}
/**
* @return $this Provides a fluent interface
*/
public function addConstraint(Constraint\ConstraintInterface $constraint)
{
$this->addConstraints[] = $constraint;
return $this;
}
/**
* @param string $name
* @return self Provides a fluent interface
*/
public function dropIndex($name)
{
$this->dropIndexes[] = $name;
return $this;
}
/**
* @param string|null $key
* @return array
*/
public function getRawState($key = null)
{
$rawState = [
self::TABLE => $this->table,
self::ADD_COLUMNS => $this->addColumns,
self::DROP_COLUMNS => $this->dropColumns,
self::CHANGE_COLUMNS => $this->changeColumns,
self::ADD_CONSTRAINTS => $this->addConstraints,
self::DROP_CONSTRAINTS => $this->dropConstraints,
self::DROP_INDEXES => $this->dropIndexes,
];
return isset($key) && array_key_exists($key, $rawState) ? $rawState[$key] : $rawState;
}
/** @return string[] */
protected function processTable(?PlatformInterface $adapterPlatform = null)
{
return [$this->resolveTable($this->table, $adapterPlatform)];
}
/** @return string[] */
protected function processAddColumns(?PlatformInterface $adapterPlatform = null)
{
$sqls = [];
foreach ($this->addColumns as $column) {
$sqls[] = $this->processExpression($column, $adapterPlatform);
}
return [$sqls];
}
/** @return string[] */
protected function processChangeColumns(?PlatformInterface $adapterPlatform = null)
{
$sqls = [];
foreach ($this->changeColumns as $name => $column) {
$sqls[] = [
$adapterPlatform->quoteIdentifier($name),
$this->processExpression($column, $adapterPlatform),
];
}
return [$sqls];
}
/** @return string[] */
protected function processDropColumns(?PlatformInterface $adapterPlatform = null)
{
$sqls = [];
foreach ($this->dropColumns as $column) {
$sqls[] = $adapterPlatform->quoteIdentifier($column);
}
return [$sqls];
}
/** @return string[] */
protected function processAddConstraints(?PlatformInterface $adapterPlatform = null)
{
$sqls = [];
foreach ($this->addConstraints as $constraint) {
$sqls[] = $this->processExpression($constraint, $adapterPlatform);
}
return [$sqls];
}
/** @return string[] */
protected function processDropConstraints(?PlatformInterface $adapterPlatform = null)
{
$sqls = [];
foreach ($this->dropConstraints as $constraint) {
$sqls[] = $adapterPlatform->quoteIdentifier($constraint);
}
return [$sqls];
}
/** @return string[] */
protected function processDropIndexes(?PlatformInterface $adapterPlatform = null)
{
$sqls = [];
foreach ($this->dropIndexes as $index) {
$sqls[] = $adapterPlatform->quoteIdentifier($index);
}
return [$sqls];
}
}
| 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/Ddl/Column/Decimal.php | src/Sql/Ddl/Column/Decimal.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Decimal extends AbstractPrecisionColumn
{
/** @var string */
protected $type = 'DECIMAL';
}
| 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/Ddl/Column/AbstractPrecisionColumn.php | src/Sql/Ddl/Column/AbstractPrecisionColumn.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
abstract class AbstractPrecisionColumn extends AbstractLengthColumn
{
/** @var int|null */
protected $decimal;
/**
* {@inheritDoc}
*
* @param int|null $decimal
* @param int $digits
*/
public function __construct(
$name,
$digits = null,
$decimal = null,
$nullable = false,
$default = null,
array $options = []
) {
$this->setDecimal($decimal);
parent::__construct($name, $digits, $nullable, $default, $options);
}
/**
* @param int $digits
* @return $this
*/
public function setDigits($digits)
{
return $this->setLength($digits);
}
/**
* @return int
*/
public function getDigits()
{
return $this->getLength();
}
/**
* @param int|null $decimal
* @return $this Provides a fluent interface
*/
public function setDecimal($decimal)
{
$this->decimal = null === $decimal ? null : (int) $decimal;
return $this;
}
/**
* @return int|null
*/
public function getDecimal()
{
return $this->decimal;
}
/**
* {@inheritDoc}
*/
protected function getLengthExpression()
{
if ($this->decimal !== null) {
return $this->length . ',' . $this->decimal;
}
return $this->length;
}
}
| 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/Ddl/Column/Text.php | src/Sql/Ddl/Column/Text.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Text extends AbstractLengthColumn
{
/** @var string */
protected $type = 'TEXT';
}
| 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/Ddl/Column/Datetime.php | src/Sql/Ddl/Column/Datetime.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Datetime extends Column
{
/** @var string */
protected $type = 'DATETIME';
}
| 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/Ddl/Column/Date.php | src/Sql/Ddl/Column/Date.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Date extends Column
{
/** @var string */
protected $type = 'DATE';
}
| 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/Ddl/Column/Time.php | src/Sql/Ddl/Column/Time.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Time extends Column
{
/** @var string */
protected $type = 'TIME';
}
| 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/Ddl/Column/Binary.php | src/Sql/Ddl/Column/Binary.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Binary extends AbstractLengthColumn
{
/** @var string */
protected $type = 'BINARY';
}
| 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/Ddl/Column/ColumnInterface.php | src/Sql/Ddl/Column/ColumnInterface.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
use Laminas\Db\Sql\ExpressionInterface;
/**
* Interface ColumnInterface describes the protocol on how Column objects interact
*/
interface ColumnInterface extends ExpressionInterface
{
/**
* @return string
*/
public function getName();
/**
* @return bool
*/
public function isNullable();
/**
* @return null|string|int
*/
public function getDefault();
/**
* @return array
*/
public function getOptions();
}
| 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/Ddl/Column/AbstractLengthColumn.php | src/Sql/Ddl/Column/AbstractLengthColumn.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
abstract class AbstractLengthColumn extends Column
{
/** @var int */
protected $length;
/**
* {@inheritDoc}
*
* @param int $length
*/
public function __construct($name, $length = null, $nullable = false, $default = null, array $options = [])
{
$this->setLength($length);
parent::__construct($name, $nullable, $default, $options);
}
/**
* @param int $length
* @return $this Provides a fluent interface
*/
public function setLength($length)
{
$this->length = (int) $length;
return $this;
}
/**
* @return int
*/
public function getLength()
{
return $this->length;
}
/**
* @return string
*/
protected function getLengthExpression()
{
return (string) $this->length;
}
/**
* @return array
*/
public function getExpressionData()
{
$data = parent::getExpressionData();
if ($this->getLengthExpression()) {
$data[0][1][1] .= '(' . $this->getLengthExpression() . ')';
}
return $data;
}
}
| 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/Ddl/Column/AbstractTimestampColumn.php | src/Sql/Ddl/Column/AbstractTimestampColumn.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
use function array_merge;
/**
* @see doc section http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html
*/
abstract class AbstractTimestampColumn extends Column
{
/**
* @return array
*/
public function getExpressionData()
{
$spec = $this->specification;
$params = [];
$params[] = $this->name;
$params[] = $this->type;
$types = [self::TYPE_IDENTIFIER, self::TYPE_LITERAL];
if (! $this->isNullable) {
$spec .= ' NOT NULL';
}
if ($this->default !== null) {
$spec .= ' DEFAULT %s';
$params[] = $this->default;
$types[] = self::TYPE_VALUE;
}
$options = $this->getOptions();
if (isset($options['on_update'])) {
$spec .= ' %s';
$params[] = 'ON UPDATE CURRENT_TIMESTAMP';
$types[] = self::TYPE_LITERAL;
}
$data = [
[
$spec,
$params,
$types,
],
];
foreach ($this->constraints as $constraint) {
$data[] = ' ';
$data = array_merge($data, $constraint->getExpressionData());
}
return $data;
}
}
| 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/Ddl/Column/Integer.php | src/Sql/Ddl/Column/Integer.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Integer extends Column
{
/**
* @return array
*/
public function getExpressionData()
{
$data = parent::getExpressionData();
$options = $this->getOptions();
if (isset($options['length'])) {
$data[0][1][1] .= '(' . $options['length'] . ')';
}
return $data;
}
}
| 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/Ddl/Column/Floating.php | src/Sql/Ddl/Column/Floating.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
/**
* Column representing a FLOAT type.
*
* Cannot name a class "float" starting in PHP 7, as it's a reserved keyword;
* hence, "floating", with a type of "FLOAT".
*/
class Floating extends AbstractPrecisionColumn
{
/** @var string */
protected $type = 'FLOAT';
}
| 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/Ddl/Column/Timestamp.php | src/Sql/Ddl/Column/Timestamp.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Timestamp extends AbstractTimestampColumn
{
/** @var string */
protected $type = 'TIMESTAMP';
}
| 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/Ddl/Column/Boolean.php | src/Sql/Ddl/Column/Boolean.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Boolean extends Column
{
/** @var string */
protected $type = 'BOOLEAN';
/**
* {@inheritDoc}
*/
protected $isNullable = false;
/**
* {@inheritDoc}
*/
public function setNullable($nullable)
{
return parent::setNullable(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/Sql/Ddl/Column/Blob.php | src/Sql/Ddl/Column/Blob.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Blob extends AbstractLengthColumn
{
/** @var string Change type to blob */
protected $type = 'BLOB';
}
| 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/Ddl/Column/Varchar.php | src/Sql/Ddl/Column/Varchar.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Varchar extends AbstractLengthColumn
{
/** @var string */
protected $type = 'VARCHAR';
}
| 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/Ddl/Column/Varbinary.php | src/Sql/Ddl/Column/Varbinary.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Varbinary extends AbstractLengthColumn
{
/** @var string */
protected $type = 'VARBINARY';
}
| 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/Ddl/Column/Char.php | src/Sql/Ddl/Column/Char.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class Char extends AbstractLengthColumn
{
/** @var string */
protected $type = 'CHAR';
}
| 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/Ddl/Column/Column.php | src/Sql/Ddl/Column/Column.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
use Laminas\Db\Sql\Ddl\Constraint\ConstraintInterface;
use function array_merge;
class Column implements ColumnInterface
{
/** @var null|string|int */
protected $default;
/** @var bool */
protected $isNullable = false;
/** @var string */
protected $name = '';
/** @var array */
protected $options = [];
/** @var ConstraintInterface[] */
protected $constraints = [];
/** @var string */
protected $specification = '%s %s';
/** @var string */
protected $type = 'INTEGER';
/**
* @param null|string $name
* @param bool $nullable
* @param mixed|null $default
* @param mixed[] $options
*/
public function __construct($name = null, $nullable = false, $default = null, array $options = [])
{
$this->setName($name);
$this->setNullable($nullable);
$this->setDefault($default);
$this->setOptions($options);
}
/**
* @param string $name
* @return $this Provides a fluent interface
*/
public function setName($name)
{
$this->name = (string) $name;
return $this;
}
/**
* @return null|string
*/
public function getName()
{
return $this->name;
}
/**
* @param bool $nullable
* @return $this Provides a fluent interface
*/
public function setNullable($nullable)
{
$this->isNullable = (bool) $nullable;
return $this;
}
/**
* @return bool
*/
public function isNullable()
{
return $this->isNullable;
}
/**
* @param null|string|int $default
* @return $this Provides a fluent interface
*/
public function setDefault($default)
{
$this->default = $default;
return $this;
}
/**
* @return null|string|int
*/
public function getDefault()
{
return $this->default;
}
/**
* @param array $options
* @return $this Provides a fluent interface
*/
public function setOptions(array $options)
{
$this->options = $options;
return $this;
}
/**
* @param string $name
* @param string $value
* @return $this Provides a fluent interface
*/
public function setOption($name, $value)
{
$this->options[$name] = $value;
return $this;
}
/**
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* @return $this Provides a fluent interface
*/
public function addConstraint(ConstraintInterface $constraint)
{
$this->constraints[] = $constraint;
return $this;
}
/**
* @return array
*/
public function getExpressionData()
{
$spec = $this->specification;
$params = [];
$params[] = $this->name;
$params[] = $this->type;
$types = [self::TYPE_IDENTIFIER, self::TYPE_LITERAL];
if (! $this->isNullable) {
$spec .= ' NOT NULL';
}
if ($this->default !== null) {
$spec .= ' DEFAULT %s';
$params[] = $this->default;
$types[] = self::TYPE_VALUE;
}
$data = [
[
$spec,
$params,
$types,
],
];
foreach ($this->constraints as $constraint) {
$data[] = ' ';
$data = array_merge($data, $constraint->getExpressionData());
}
return $data;
}
}
| 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/Ddl/Column/BigInteger.php | src/Sql/Ddl/Column/BigInteger.php | <?php
namespace Laminas\Db\Sql\Ddl\Column;
class BigInteger extends Integer
{
/** @var string */
protected $type = 'BIGINT';
}
| 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/Ddl/Index/AbstractIndex.php | src/Sql/Ddl/Index/AbstractIndex.php | <?php
namespace Laminas\Db\Sql\Ddl\Index;
use Laminas\Db\Sql\Ddl\Constraint\AbstractConstraint;
abstract class AbstractIndex extends AbstractConstraint
{
}
| 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/Ddl/Index/Index.php | src/Sql/Ddl/Index/Index.php | <?php
namespace Laminas\Db\Sql\Ddl\Index;
use function array_merge;
use function count;
use function implode;
use function str_replace;
class Index extends AbstractIndex
{
/** @var string */
protected $specification = 'INDEX %s(...)';
/** @var array */
protected $lengths;
/**
* @param string|array|null $columns
* @param null|string $name
* @param array $lengths
*/
public function __construct($columns, $name = null, array $lengths = [])
{
$this->setColumns($columns);
$this->name = null === $name ? null : (string) $name;
$this->lengths = $lengths;
}
/**
* @return array of array|string should return an array in the format:
*
* array (
* // a sprintf formatted string
* string $specification,
*
* // the values for the above sprintf formatted string
* array $values,
*
* // an array of equal length of the $values array, with either TYPE_IDENTIFIER or TYPE_VALUE for each value
* array $types,
* )
*/
public function getExpressionData()
{
$colCount = count($this->columns);
$values = [];
$values[] = $this->name ?: '';
$newSpecTypes = [self::TYPE_IDENTIFIER];
$newSpecParts = [];
for ($i = 0; $i < $colCount; $i++) {
$specPart = '%s';
if (isset($this->lengths[$i])) {
$specPart .= "({$this->lengths[$i]})";
}
$newSpecParts[] = $specPart;
$newSpecTypes[] = self::TYPE_IDENTIFIER;
}
$newSpec = str_replace('...', implode(', ', $newSpecParts), $this->specification);
return [
[
$newSpec,
array_merge($values, $this->columns),
$newSpecTypes,
],
];
}
}
| 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/Ddl/Constraint/ConstraintInterface.php | src/Sql/Ddl/Constraint/ConstraintInterface.php | <?php
namespace Laminas\Db\Sql\Ddl\Constraint;
use Laminas\Db\Sql\ExpressionInterface;
interface ConstraintInterface extends ExpressionInterface
{
public function getColumns();
}
| 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/Ddl/Constraint/ForeignKey.php | src/Sql/Ddl/Constraint/ForeignKey.php | <?php
namespace Laminas\Db\Sql\Ddl\Constraint;
use function array_fill;
use function array_merge;
use function count;
use function implode;
use function sprintf;
class ForeignKey extends AbstractConstraint
{
/** @var string */
protected $onDeleteRule = 'NO ACTION';
/** @var string */
protected $onUpdateRule = 'NO ACTION';
/** @var string[] */
protected $referenceColumn = [];
/** @var string */
protected $referenceTable = '';
/**
* {@inheritDoc}
*/
protected $columnSpecification = 'FOREIGN KEY (%s) ';
/** @var string[] */
protected $referenceSpecification = [
'REFERENCES %s ',
'ON DELETE %s ON UPDATE %s',
];
/**
* @param null|string $name
* @param null|string|array $columns
* @param string $referenceTable
* @param null|string|array $referenceColumn
* @param null|string $onDeleteRule
* @param null|string $onUpdateRule
*/
public function __construct(
$name,
$columns,
$referenceTable,
$referenceColumn,
$onDeleteRule = null,
$onUpdateRule = null
) {
$this->setName($name);
$this->setColumns($columns);
$this->setReferenceTable($referenceTable);
$this->setReferenceColumn($referenceColumn);
if ($onDeleteRule) {
$this->setOnDeleteRule($onDeleteRule);
}
if ($onUpdateRule) {
$this->setOnUpdateRule($onUpdateRule);
}
}
/**
* @param string $referenceTable
* @return $this Provides a fluent interface
*/
public function setReferenceTable($referenceTable)
{
$this->referenceTable = (string) $referenceTable;
return $this;
}
/**
* @return string
*/
public function getReferenceTable()
{
return $this->referenceTable;
}
/**
* @param null|string|array $referenceColumn
* @return $this Provides a fluent interface
*/
public function setReferenceColumn($referenceColumn)
{
$this->referenceColumn = (array) $referenceColumn;
return $this;
}
/**
* @return array
*/
public function getReferenceColumn()
{
return $this->referenceColumn;
}
/**
* @param string $onDeleteRule
* @return $this Provides a fluent interface
*/
public function setOnDeleteRule($onDeleteRule)
{
$this->onDeleteRule = (string) $onDeleteRule;
return $this;
}
/**
* @return string
*/
public function getOnDeleteRule()
{
return $this->onDeleteRule;
}
/**
* @param string $onUpdateRule
* @return $this Provides a fluent interface
*/
public function setOnUpdateRule($onUpdateRule)
{
$this->onUpdateRule = (string) $onUpdateRule;
return $this;
}
/**
* @return string
*/
public function getOnUpdateRule()
{
return $this->onUpdateRule;
}
/**
* @return array
*/
public function getExpressionData()
{
$data = parent::getExpressionData();
$colCount = count($this->referenceColumn);
$newSpecTypes = [self::TYPE_IDENTIFIER];
$values = [$this->referenceTable];
$data[0][0] .= $this->referenceSpecification[0];
if ($colCount) {
$values = array_merge($values, $this->referenceColumn);
$newSpecParts = array_fill(0, $colCount, '%s');
$newSpecTypes = array_merge($newSpecTypes, array_fill(0, $colCount, self::TYPE_IDENTIFIER));
$data[0][0] .= sprintf('(%s) ', implode(', ', $newSpecParts));
}
$data[0][0] .= $this->referenceSpecification[1];
$values[] = $this->onDeleteRule;
$values[] = $this->onUpdateRule;
$newSpecTypes[] = self::TYPE_LITERAL;
$newSpecTypes[] = self::TYPE_LITERAL;
$data[0][1] = array_merge($data[0][1], $values);
$data[0][2] = array_merge($data[0][2], $newSpecTypes);
return $data;
}
}
| 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/Ddl/Constraint/UniqueKey.php | src/Sql/Ddl/Constraint/UniqueKey.php | <?php
namespace Laminas\Db\Sql\Ddl\Constraint;
class UniqueKey extends AbstractConstraint
{
/** @var string */
protected $specification = 'UNIQUE';
}
| 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/Ddl/Constraint/Check.php | src/Sql/Ddl/Constraint/Check.php | <?php
namespace Laminas\Db\Sql\Ddl\Constraint;
use Laminas\Db\Sql\ExpressionInterface;
use function array_unshift;
class Check extends AbstractConstraint
{
/** @var string|ExpressionInterface */
protected $expression;
/**
* {@inheritDoc}
*/
protected $specification = 'CHECK (%s)';
/**
* @param string|ExpressionInterface $expression
* @param null|string $name
*/
public function __construct($expression, $name)
{
$this->expression = $expression;
$this->name = $name;
}
/**
* {@inheritDoc}
*/
public function getExpressionData()
{
$newSpecTypes = [self::TYPE_LITERAL];
$values = [$this->expression];
$newSpec = '';
if ($this->name) {
$newSpec .= $this->namedSpecification;
array_unshift($values, $this->name);
array_unshift($newSpecTypes, self::TYPE_IDENTIFIER);
}
return [
[
$newSpec . $this->specification,
$values,
$newSpecTypes,
],
];
}
}
| 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/Ddl/Constraint/PrimaryKey.php | src/Sql/Ddl/Constraint/PrimaryKey.php | <?php
namespace Laminas\Db\Sql\Ddl\Constraint;
class PrimaryKey extends AbstractConstraint
{
/** @var string */
protected $specification = 'PRIMARY KEY';
}
| 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/Ddl/Constraint/AbstractConstraint.php | src/Sql/Ddl/Constraint/AbstractConstraint.php | <?php
namespace Laminas\Db\Sql\Ddl\Constraint;
use function array_fill;
use function array_merge;
use function count;
use function implode;
use function sprintf;
abstract class AbstractConstraint implements ConstraintInterface
{
/** @var string */
protected $columnSpecification = ' (%s)';
/** @var string */
protected $namedSpecification = 'CONSTRAINT %s ';
/** @var string */
protected $specification = '';
/** @var string */
protected $name = '';
/** @var array */
protected $columns = [];
/**
* @param null|string|array $columns
* @param null|string $name
*/
public function __construct($columns = null, $name = null)
{
if ($columns) {
$this->setColumns($columns);
}
$this->setName($name);
}
/**
* @param string $name
* @return $this Provides a fluent interface
*/
public function setName($name)
{
$this->name = (string) $name;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param null|string|array $columns
* @return $this Provides a fluent interface
*/
public function setColumns($columns)
{
$this->columns = (array) $columns;
return $this;
}
/**
* @param string $column
* @return $this Provides a fluent interface
*/
public function addColumn($column)
{
$this->columns[] = $column;
return $this;
}
/**
* {@inheritDoc}
*/
public function getColumns()
{
return $this->columns;
}
/**
* {@inheritDoc}
*/
public function getExpressionData()
{
$colCount = count($this->columns);
$newSpecTypes = [];
$values = [];
$newSpec = '';
if ($this->name) {
$newSpec .= $this->namedSpecification;
$values[] = $this->name;
$newSpecTypes[] = self::TYPE_IDENTIFIER;
}
$newSpec .= $this->specification;
if ($colCount) {
$values = array_merge($values, $this->columns);
$newSpecParts = array_fill(0, $colCount, '%s');
$newSpecTypes = array_merge($newSpecTypes, array_fill(0, $colCount, self::TYPE_IDENTIFIER));
$newSpec .= sprintf($this->columnSpecification, implode(', ', $newSpecParts));
}
return [
[
$newSpec,
$values,
$newSpecTypes,
],
];
}
}
| 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/Exception/ExceptionInterface.php | src/Sql/Exception/ExceptionInterface.php | <?php
namespace Laminas\Db\Sql\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/Sql/Exception/RuntimeException.php | src/Sql/Exception/RuntimeException.php | <?php
namespace Laminas\Db\Sql\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/Sql/Exception/InvalidArgumentException.php | src/Sql/Exception/InvalidArgumentException.php | <?php
namespace Laminas\Db\Sql\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/Sql/Predicate/Expression.php | src/Sql/Predicate/Expression.php | <?php
namespace Laminas\Db\Sql\Predicate;
use Laminas\Db\Sql\Expression as BaseExpression;
use function array_slice;
use function func_get_args;
use function is_array;
class Expression extends BaseExpression implements PredicateInterface
{
/**
* Constructor
*
* @param string $expression
* @param int|float|bool|string|array $valueParameter
*/
public function __construct($expression = null, $valueParameter = null) /*[, $valueParameter, ... ]*/
{
if ($expression) {
$this->setExpression($expression);
}
$this->setParameters(is_array($valueParameter) ? $valueParameter : array_slice(func_get_args(), 1));
}
}
| 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/Predicate/In.php | src/Sql/Predicate/In.php | <?php
namespace Laminas\Db\Sql\Predicate;
use Laminas\Db\Sql\AbstractExpression;
use Laminas\Db\Sql\Exception;
use Laminas\Db\Sql\Select;
use function array_fill;
use function count;
use function gettype;
use function implode;
use function is_array;
use function vsprintf;
class In extends AbstractExpression implements PredicateInterface
{
/** @var null|string|array */
protected $identifier;
/** @var null|array|Select */
protected $valueSet;
/** @var string */
protected $specification = '%s IN %s';
/** @var string */
protected $valueSpecSpecification = '%%s IN (%s)';
/**
* Constructor
*
* @param null|string|array $identifier
* @param null|array|Select $valueSet
*/
public function __construct($identifier = null, $valueSet = null)
{
if ($identifier) {
$this->setIdentifier($identifier);
}
if ($valueSet !== null) {
$this->setValueSet($valueSet);
}
}
/**
* Set identifier for comparison
*
* @param string|array $identifier
* @return $this Provides a fluent interface
*/
public function setIdentifier($identifier)
{
$this->identifier = $identifier;
return $this;
}
/**
* Get identifier of comparison
*
* @return null|string|array
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Set set of values for IN comparison
*
* @param array|Select $valueSet
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setValueSet($valueSet)
{
if (! is_array($valueSet) && ! $valueSet instanceof Select) {
throw new Exception\InvalidArgumentException(
'$valueSet must be either an array or a Laminas\Db\Sql\Select object, ' . gettype($valueSet) . ' given'
);
}
$this->valueSet = $valueSet;
return $this;
}
/**
* Gets set of values in IN comparison
*
* @return array|Select
*/
public function getValueSet()
{
return $this->valueSet;
}
/**
* Return array of parts for where statement
*
* @return array
*/
public function getExpressionData()
{
$identifier = $this->getIdentifier();
$values = $this->getValueSet();
$replacements = [];
if (is_array($identifier)) {
$countIdentifier = count($identifier);
$identifierSpecFragment = '(' . implode(', ', array_fill(0, $countIdentifier, '%s')) . ')';
$types = array_fill(0, $countIdentifier, self::TYPE_IDENTIFIER);
$replacements = $identifier;
} else {
$identifierSpecFragment = '%s';
$replacements[] = $identifier;
$types = [self::TYPE_IDENTIFIER];
}
if ($values instanceof Select) {
$specification = vsprintf(
$this->specification,
[$identifierSpecFragment, '%s']
);
$replacements[] = $values;
$types[] = self::TYPE_VALUE;
} else {
foreach ($values as $argument) {
[$replacements[], $types[]] = $this->normalizeArgument($argument, self::TYPE_VALUE);
}
$countValues = count($values);
$valuePlaceholders = $countValues > 0 ? array_fill(0, $countValues, '%s') : [];
$inValueList = implode(', ', $valuePlaceholders);
if ('' === $inValueList) {
$inValueList = 'NULL';
}
$specification = vsprintf(
$this->specification,
[$identifierSpecFragment, '(' . $inValueList . ')']
);
}
return [
[
$specification,
$replacements,
$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/Predicate/IsNotNull.php | src/Sql/Predicate/IsNotNull.php | <?php
namespace Laminas\Db\Sql\Predicate;
class IsNotNull extends IsNull
{
/** @var string */
protected $specification = '%1$s IS NOT 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/Predicate/NotLike.php | src/Sql/Predicate/NotLike.php | <?php
namespace Laminas\Db\Sql\Predicate;
class NotLike extends Like
{
/** @var string */
protected $specification = '%1$s NOT LIKE %2$s';
}
| 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/Predicate/NotIn.php | src/Sql/Predicate/NotIn.php | <?php
namespace Laminas\Db\Sql\Predicate;
class NotIn extends In
{
/** @var string */
protected $specification = '%s NOT IN %s';
}
| 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/Predicate/IsNull.php | src/Sql/Predicate/IsNull.php | <?php
namespace Laminas\Db\Sql\Predicate;
use Laminas\Db\Sql\AbstractExpression;
class IsNull extends AbstractExpression implements PredicateInterface
{
/** @var string */
protected $specification = '%1$s IS NULL';
/** @var nuill|string */
protected $identifier;
/**
* Constructor
*
* @param string $identifier
*/
public function __construct($identifier = null)
{
if ($identifier) {
$this->setIdentifier($identifier);
}
}
/**
* Set identifier for comparison
*
* @param string $identifier
* @return $this Provides a fluent interface
*/
public function setIdentifier($identifier)
{
$this->identifier = $identifier;
return $this;
}
/**
* Get identifier of comparison
*
* @return null|string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Set specification string to use in forming SQL predicate
*
* @param string $specification
* @return $this Provides a fluent interface
*/
public function setSpecification($specification)
{
$this->specification = $specification;
return $this;
}
/**
* Get specification string to use in forming SQL predicate
*
* @return string
*/
public function getSpecification()
{
return $this->specification;
}
/**
* Get parts for where statement
*
* @return array
*/
public function getExpressionData()
{
$identifier = $this->normalizeArgument($this->identifier, self::TYPE_IDENTIFIER);
return [
[
$this->getSpecification(),
[$identifier[0]],
[$identifier[1]],
],
];
}
}
| 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/Predicate/NotBetween.php | src/Sql/Predicate/NotBetween.php | <?php
namespace Laminas\Db\Sql\Predicate;
class NotBetween extends Between
{
/** @var string */
protected $specification = '%1$s NOT BETWEEN %2$s AND %3$s';
}
| 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/Predicate/Literal.php | src/Sql/Predicate/Literal.php | <?php
namespace Laminas\Db\Sql\Predicate;
use Laminas\Db\Sql\Literal as BaseLiteral;
class Literal extends BaseLiteral implements PredicateInterface
{
}
| 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/Predicate/Predicate.php | src/Sql/Predicate/Predicate.php | <?php
namespace Laminas\Db\Sql\Predicate;
use Laminas\Db\Sql\Exception\RuntimeException;
use Laminas\Db\Sql\Select;
use function func_get_arg;
use function func_num_args;
use function strtolower;
/**
* @property Predicate $and
* @property Predicate $or
* @property Predicate $AND
* @property Predicate $OR
* @property Predicate $NEST
* @property Predicate $UNNEST
*/
class Predicate extends PredicateSet
{
/** @var null|Predicate */
protected $unnest;
/** @var null|string */
protected $nextPredicateCombineOperator;
/**
* Begin nesting predicates
*
* @return Predicate
*/
public function nest()
{
$predicateSet = new Predicate();
$predicateSet->setUnnest($this);
$this->addPredicate($predicateSet, $this->nextPredicateCombineOperator ?: $this->defaultCombination);
$this->nextPredicateCombineOperator = null;
return $predicateSet;
}
/**
* Indicate what predicate will be unnested
*
* @return void
*/
public function setUnnest(Predicate $predicate)
{
$this->unnest = $predicate;
}
/**
* Indicate end of nested predicate
*
* @return Predicate
* @throws RuntimeException
*/
public function unnest()
{
if ($this->unnest === null) {
throw new RuntimeException('Not nested');
}
$unnest = $this->unnest;
$this->unnest = null;
return $unnest;
}
/**
* Create "Equal To" predicate
*
* Utilizes Operator predicate
*
* @param int|float|bool|string|Expression $left
* @param int|float|bool|string|Expression $right
* @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes}
* @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes}
* @return $this Provides a fluent interface
*/
public function equalTo($left, $right, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE)
{
$this->addPredicate(
new Operator($left, Operator::OPERATOR_EQUAL_TO, $right, $leftType, $rightType),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "Not Equal To" predicate
*
* Utilizes Operator predicate
*
* @param int|float|bool|string|Expression $left
* @param int|float|bool|string|Expression $right
* @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes}
* @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes}
* @return $this Provides a fluent interface
*/
public function notEqualTo($left, $right, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE)
{
$this->addPredicate(
new Operator($left, Operator::OPERATOR_NOT_EQUAL_TO, $right, $leftType, $rightType),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "Less Than" predicate
*
* Utilizes Operator predicate
*
* @param int|float|bool|string|Expression $left
* @param int|float|bool|string|Expression $right
* @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes}
* @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes}
* @return $this Provides a fluent interface
*/
public function lessThan($left, $right, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE)
{
$this->addPredicate(
new Operator($left, Operator::OPERATOR_LESS_THAN, $right, $leftType, $rightType),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "Greater Than" predicate
*
* Utilizes Operator predicate
*
* @param int|float|bool|string|Expression $left
* @param int|float|bool|string|Expression $right
* @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes}
* @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes}
* @return $this Provides a fluent interface
*/
public function greaterThan($left, $right, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE)
{
$this->addPredicate(
new Operator($left, Operator::OPERATOR_GREATER_THAN, $right, $leftType, $rightType),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "Less Than Or Equal To" predicate
*
* Utilizes Operator predicate
*
* @param int|float|bool|string|Expression $left
* @param int|float|bool|string|Expression $right
* @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes}
* @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes}
* @return $this Provides a fluent interface
*/
public function lessThanOrEqualTo($left, $right, $leftType = self::TYPE_IDENTIFIER, $rightType = self::TYPE_VALUE)
{
$this->addPredicate(
new Operator($left, Operator::OPERATOR_LESS_THAN_OR_EQUAL_TO, $right, $leftType, $rightType),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "Greater Than Or Equal To" predicate
*
* Utilizes Operator predicate
*
* @param int|float|bool|string|Expression $left
* @param int|float|bool|string|Expression $right
* @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes}
* @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes}
* @return $this Provides a fluent interface
*/
public function greaterThanOrEqualTo(
$left,
$right,
$leftType = self::TYPE_IDENTIFIER,
$rightType = self::TYPE_VALUE
) {
$this->addPredicate(
new Operator($left, Operator::OPERATOR_GREATER_THAN_OR_EQUAL_TO, $right, $leftType, $rightType),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "Like" predicate
*
* Utilizes Like predicate
*
* @param string|Expression $identifier
* @param string $like
* @return $this Provides a fluent interface
*/
public function like($identifier, $like)
{
$this->addPredicate(
new Like($identifier, $like),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "notLike" predicate
*
* Utilizes In predicate
*
* @param string|Expression $identifier
* @param string $notLike
* @return $this Provides a fluent interface
*/
public function notLike($identifier, $notLike)
{
$this->addPredicate(
new NotLike($identifier, $notLike),
$this->nextPredicateCombineOperator ? : $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create an expression, with parameter placeholders
*
* @param string $expression
* @param null|array $parameters
* @return $this Provides a fluent interface
*/
public function expression($expression, $parameters = null)
{
$this->addPredicate(
new Expression($expression, func_num_args() > 1 ? $parameters : []),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "Literal" predicate
*
* Literal predicate, for parameters, use expression()
*
* @param string $literal
* @return $this Provides a fluent interface
*/
public function literal($literal)
{
// process deprecated parameters from previous literal($literal, $parameters = null) signature
if (func_num_args() >= 2) {
$parameters = func_get_arg(1);
$predicate = new Expression($literal, $parameters);
}
// normal workflow for "Literals" here
if (! isset($predicate)) {
$predicate = new Literal($literal);
}
$this->addPredicate(
$predicate,
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "IS NULL" predicate
*
* Utilizes IsNull predicate
*
* @param string|Expression $identifier
* @return $this Provides a fluent interface
*/
public function isNull($identifier)
{
$this->addPredicate(
new IsNull($identifier),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "IS NOT NULL" predicate
*
* Utilizes IsNotNull predicate
*
* @param string|Expression $identifier
* @return $this Provides a fluent interface
*/
public function isNotNull($identifier)
{
$this->addPredicate(
new IsNotNull($identifier),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "IN" predicate
*
* Utilizes In predicate
*
* @param string|Expression $identifier
* @param array|Select $valueSet
* @return $this Provides a fluent interface
*/
public function in($identifier, $valueSet = null)
{
$this->addPredicate(
new In($identifier, $valueSet),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "NOT IN" predicate
*
* Utilizes NotIn predicate
*
* @param string|Expression $identifier
* @param array|Select $valueSet
* @return $this Provides a fluent interface
*/
public function notIn($identifier, $valueSet = null)
{
$this->addPredicate(
new NotIn($identifier, $valueSet),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "between" predicate
*
* Utilizes Between predicate
*
* @param string|Expression $identifier
* @param int|float|string $minValue
* @param int|float|string $maxValue
* @return $this Provides a fluent interface
*/
public function between($identifier, $minValue, $maxValue)
{
$this->addPredicate(
new Between($identifier, $minValue, $maxValue),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Create "NOT BETWEEN" predicate
*
* Utilizes NotBetween predicate
*
* @param string|Expression $identifier
* @param int|float|string $minValue
* @param int|float|string $maxValue
* @return $this Provides a fluent interface
*/
public function notBetween($identifier, $minValue, $maxValue)
{
$this->addPredicate(
new NotBetween($identifier, $minValue, $maxValue),
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Use given predicate directly
*
* Contrary to {@link addPredicate()} this method respects formerly set
* AND / OR combination operator, thus allowing generic predicates to be
* used fluently within where chains as any other concrete predicate.
*
* @return $this Provides a fluent interface
*/
// phpcs:ignore Generic.NamingConventions.ConstructorName.OldStyle
public function predicate(PredicateInterface $predicate)
{
$this->addPredicate(
$predicate,
$this->nextPredicateCombineOperator ?: $this->defaultCombination
);
$this->nextPredicateCombineOperator = null;
return $this;
}
/**
* Overloading
*
* Overloads "or", "and", "nest", and "unnest"
*
* @param string $name
* @return $this Provides a fluent interface
*/
public function __get($name)
{
switch (strtolower($name)) {
case 'or':
$this->nextPredicateCombineOperator = self::OP_OR;
break;
case 'and':
$this->nextPredicateCombineOperator = self::OP_AND;
break;
case 'nest':
return $this->nest();
case 'unnest':
return $this->unnest();
}
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/Sql/Predicate/Operator.php | src/Sql/Predicate/Operator.php | <?php
namespace Laminas\Db\Sql\Predicate;
use Laminas\Db\Sql\AbstractExpression;
use Laminas\Db\Sql\Exception;
use function in_array;
use function is_array;
use function sprintf;
class Operator extends AbstractExpression implements PredicateInterface
{
public const OPERATOR_EQUAL_TO = '=';
public const OP_EQ = '=';
public const OPERATOR_NOT_EQUAL_TO = '!=';
public const OP_NE = '!=';
public const OPERATOR_LESS_THAN = '<';
public const OP_LT = '<';
public const OPERATOR_LESS_THAN_OR_EQUAL_TO = '<=';
public const OP_LTE = '<=';
public const OPERATOR_GREATER_THAN = '>';
public const OP_GT = '>';
public const OPERATOR_GREATER_THAN_OR_EQUAL_TO = '>=';
public const OP_GTE = '>=';
/**
* {@inheritDoc}
*/
protected $allowedTypes = [
self::TYPE_IDENTIFIER,
self::TYPE_VALUE,
];
/** @var int|float|bool|string */
protected $left;
/** @var int|float|bool|string */
protected $right;
/** @var string */
protected $leftType = self::TYPE_IDENTIFIER;
/** @var string */
protected $rightType = self::TYPE_VALUE;
/** @var string */
protected $operator = self::OPERATOR_EQUAL_TO;
/**
* Constructor
*
* @param int|float|bool|string $left
* @param string $operator
* @param int|float|bool|string $right
* @param string $leftType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_IDENTIFIER {@see allowedTypes}
* @param string $rightType TYPE_IDENTIFIER or TYPE_VALUE by default TYPE_VALUE {@see allowedTypes}
*/
public function __construct(
$left = null,
$operator = self::OPERATOR_EQUAL_TO,
$right = null,
$leftType = self::TYPE_IDENTIFIER,
$rightType = self::TYPE_VALUE
) {
if ($left !== null) {
$this->setLeft($left);
}
if ($operator !== self::OPERATOR_EQUAL_TO) {
$this->setOperator($operator);
}
if ($right !== null) {
$this->setRight($right);
}
if ($leftType !== self::TYPE_IDENTIFIER) {
$this->setLeftType($leftType);
}
if ($rightType !== self::TYPE_VALUE) {
$this->setRightType($rightType);
}
}
/**
* Set left side of operator
*
* @param int|float|bool|string $left
* @return $this Provides a fluent interface
*/
public function setLeft($left)
{
$this->left = $left;
if (is_array($left)) {
$left = $this->normalizeArgument($left, $this->leftType);
$this->leftType = $left[1];
}
return $this;
}
/**
* Get left side of operator
*
* @return int|float|bool|string
*/
public function getLeft()
{
return $this->left;
}
/**
* Set parameter type for left side of operator
*
* @param string $type TYPE_IDENTIFIER or TYPE_VALUE {@see allowedTypes}
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setLeftType($type)
{
if (! in_array($type, $this->allowedTypes)) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid type "%s" provided; must be of type "%s" or "%s"',
$type,
self::class . '::TYPE_IDENTIFIER',
self::class . '::TYPE_VALUE'
));
}
$this->leftType = $type;
return $this;
}
/**
* Get parameter type on left side of operator
*
* @return string
*/
public function getLeftType()
{
return $this->leftType;
}
/**
* Set operator string
*
* @param string $operator
* @return $this Provides a fluent interface
*/
public function setOperator($operator)
{
$this->operator = $operator;
return $this;
}
/**
* Get operator string
*
* @return string
*/
public function getOperator()
{
return $this->operator;
}
/**
* Set right side of operator
*
* @param int|float|bool|string $right
* @return $this Provides a fluent interface
*/
public function setRight($right)
{
$this->right = $right;
if (is_array($right)) {
$right = $this->normalizeArgument($right, $this->rightType);
$this->rightType = $right[1];
}
return $this;
}
/**
* Get right side of operator
*
* @return int|float|bool|string
*/
public function getRight()
{
return $this->right;
}
/**
* Set parameter type for right side of operator
*
* @param string $type TYPE_IDENTIFIER or TYPE_VALUE {@see allowedTypes}
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setRightType($type)
{
if (! in_array($type, $this->allowedTypes)) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid type "%s" provided; must be of type "%s" or "%s"',
$type,
self::class . '::TYPE_IDENTIFIER',
self::class . '::TYPE_VALUE'
));
}
$this->rightType = $type;
return $this;
}
/**
* Get parameter type on right side of operator
*
* @return string
*/
public function getRightType()
{
return $this->rightType;
}
/**
* Get predicate parts for where statement
*
* @return array
*/
public function getExpressionData()
{
[$values[], $types[]] = $this->normalizeArgument($this->left, $this->leftType);
[$values[], $types[]] = $this->normalizeArgument($this->right, $this->rightType);
return [
[
'%s ' . $this->operator . ' %s',
$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/Predicate/PredicateInterface.php | src/Sql/Predicate/PredicateInterface.php | <?php
namespace Laminas\Db\Sql\Predicate;
use Laminas\Db\Sql\ExpressionInterface;
interface PredicateInterface extends ExpressionInterface
{
}
| 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/Predicate/PredicateSet.php | src/Sql/Predicate/PredicateSet.php | <?php
namespace Laminas\Db\Sql\Predicate;
use Closure;
use Countable;
use Laminas\Db\Sql\Exception;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use ReturnTypeWillChange;
use function array_merge;
use function count;
use function in_array;
use function is_array;
use function is_string;
use function sprintf;
use function strpos;
class PredicateSet implements PredicateInterface, Countable
{
public const COMBINED_BY_AND = 'AND';
public const OP_AND = 'AND';
public const COMBINED_BY_OR = 'OR';
public const OP_OR = 'OR';
/** @var string */
protected $defaultCombination = self::COMBINED_BY_AND;
/** @var PredicateInterface[] */
protected $predicates = [];
/**
* Constructor
*
* @param null|array $predicates
* @param string $defaultCombination
*/
public function __construct(?array $predicates = null, $defaultCombination = self::COMBINED_BY_AND)
{
$this->defaultCombination = $defaultCombination;
if ($predicates) {
foreach ($predicates as $predicate) {
$this->addPredicate($predicate);
}
}
}
/**
* Add predicate to set
*
* @param string $combination
* @return $this Provides a fluent interface
*/
public function addPredicate(PredicateInterface $predicate, $combination = null)
{
if ($combination === null || ! in_array($combination, [self::OP_AND, self::OP_OR])) {
$combination = $this->defaultCombination;
}
if ($combination === self::OP_OR) {
$this->orPredicate($predicate);
return $this;
}
$this->andPredicate($predicate);
return $this;
}
/**
* Add predicates to set
*
* @param PredicateInterface|Closure|string|array $predicates
* @param string $combination
* @return $this Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function addPredicates($predicates, $combination = self::OP_AND)
{
if ($predicates === null) {
throw new Exception\InvalidArgumentException('Predicate cannot be null');
}
if ($predicates instanceof PredicateInterface) {
$this->addPredicate($predicates, $combination);
return $this;
}
if ($predicates instanceof Closure) {
$predicates($this);
return $this;
}
if (is_string($predicates)) {
// String $predicate should be passed as an expression
$predicate = strpos($predicates, Expression::PLACEHOLDER) !== false
? new Expression($predicates) : new Literal($predicates);
$this->addPredicate($predicate, $combination);
return $this;
}
if (is_array($predicates)) {
foreach ($predicates as $pkey => $pvalue) {
// loop through predicates
if (is_string($pkey)) {
if (strpos($pkey, '?') !== false) {
// First, process strings that the abstraction replacement character ?
// as an Expression predicate
$predicate = new Expression($pkey, $pvalue);
} elseif ($pvalue === null) {
// Otherwise, if still a string, do something intelligent with the PHP type provided
// map PHP null to SQL IS NULL expression
$predicate = new IsNull($pkey);
} elseif (is_array($pvalue)) {
// if the value is an array, assume IN() is desired
$predicate = new In($pkey, $pvalue);
} elseif ($pvalue instanceof PredicateInterface) {
throw new Exception\InvalidArgumentException(
'Using Predicate must not use string keys'
);
} else {
// otherwise assume that array('foo' => 'bar') means "foo" = 'bar'
$predicate = new Operator($pkey, Operator::OP_EQ, $pvalue);
}
} elseif ($pvalue instanceof PredicateInterface) {
// Predicate type is ok
$predicate = $pvalue;
} else {
// must be an array of expressions (with int-indexed array)
$predicate = strpos($pvalue, Expression::PLACEHOLDER) !== false
? new Expression($pvalue) : new Literal($pvalue);
}
$this->addPredicate($predicate, $combination);
}
}
return $this;
}
/**
* Return the predicates
*
* @return PredicateInterface[]
*/
public function getPredicates()
{
return $this->predicates;
}
/**
* Add predicate using OR operator
*
* @return $this Provides a fluent interface
*/
public function orPredicate(PredicateInterface $predicate)
{
$this->predicates[] = [self::OP_OR, $predicate];
return $this;
}
/**
* Add predicate using AND operator
*
* @return $this Provides a fluent interface
*/
public function andPredicate(PredicateInterface $predicate)
{
$this->predicates[] = [self::OP_AND, $predicate];
return $this;
}
/**
* Get predicate parts for where statement
*
* @return array
*/
public function getExpressionData()
{
$parts = [];
for ($i = 0, $count = count($this->predicates); $i < $count; $i++) {
/** @var PredicateInterface $predicate */
$predicate = $this->predicates[$i][1];
if ($predicate instanceof PredicateSet) {
$parts[] = '(';
}
$parts = array_merge($parts, $predicate->getExpressionData());
if ($predicate instanceof PredicateSet) {
$parts[] = ')';
}
if (isset($this->predicates[$i + 1])) {
$parts[] = sprintf(' %s ', $this->predicates[$i + 1][0]);
}
}
return $parts;
}
/**
* Get count of attached predicates
*
* @return int
*/
#[ReturnTypeWillChange]
public function count()
{
return count($this->predicates);
}
}
| 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/Predicate/Like.php | src/Sql/Predicate/Like.php | <?php
namespace Laminas\Db\Sql\Predicate;
use Laminas\Db\Sql\AbstractExpression;
class Like extends AbstractExpression implements PredicateInterface
{
/** @var string */
protected $specification = '%1$s LIKE %2$s';
/** @var string */
protected $identifier = '';
/** @var string */
protected $like = '';
/**
* @param string $identifier
* @param string $like
*/
public function __construct($identifier = null, $like = null)
{
if ($identifier) {
$this->setIdentifier($identifier);
}
if ($like) {
$this->setLike($like);
}
}
/**
* @param string $identifier
* @return $this Provides a fluent interface
*/
public function setIdentifier($identifier)
{
$this->identifier = $identifier;
return $this;
}
/**
* @return string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* @param string $like
* @return $this Provides a fluent interface
*/
public function setLike($like)
{
$this->like = $like;
return $this;
}
/**
* @return string
*/
public function getLike()
{
return $this->like;
}
/**
* @param string $specification
* @return $this Provides a fluent interface
*/
public function setSpecification($specification)
{
$this->specification = $specification;
return $this;
}
/**
* @return string
*/
public function getSpecification()
{
return $this->specification;
}
/**
* @return array
*/
public function getExpressionData()
{
[$values[], $types[]] = $this->normalizeArgument($this->identifier, self::TYPE_IDENTIFIER);
[$values[], $types[]] = $this->normalizeArgument($this->like, self::TYPE_VALUE);
return [
[
$this->specification,
$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/Predicate/Between.php | src/Sql/Predicate/Between.php | <?php
namespace Laminas\Db\Sql\Predicate;
use Laminas\Db\Sql\AbstractExpression;
class Between extends AbstractExpression implements PredicateInterface
{
/** @var string */
protected $specification = '%1$s BETWEEN %2$s AND %3$s';
/** @var string */
protected $identifier;
/** @var null|int */
protected $minValue;
/** @var null|int */
protected $maxValue;
/**
* Constructor
*
* @param string $identifier
* @param int|float|string $minValue
* @param int|float|string $maxValue
*/
public function __construct($identifier = null, $minValue = null, $maxValue = null)
{
if ($identifier) {
$this->setIdentifier($identifier);
}
if ($minValue !== null) {
$this->setMinValue($minValue);
}
if ($maxValue !== null) {
$this->setMaxValue($maxValue);
}
}
/**
* Set identifier for comparison
*
* @param string $identifier
* @return $this Provides a fluent interface
*/
public function setIdentifier($identifier)
{
$this->identifier = $identifier;
return $this;
}
/**
* Get identifier of comparison
*
* @return null|string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Set minimum boundary for comparison
*
* @param int|float|string $minValue
* @return $this Provides a fluent interface
*/
public function setMinValue($minValue)
{
$this->minValue = $minValue;
return $this;
}
/**
* Get minimum boundary for comparison
*
* @return null|int|float|string
*/
public function getMinValue()
{
return $this->minValue;
}
/**
* Set maximum boundary for comparison
*
* @param int|float|string $maxValue
* @return $this Provides a fluent interface
*/
public function setMaxValue($maxValue)
{
$this->maxValue = $maxValue;
return $this;
}
/**
* Get maximum boundary for comparison
*
* @return null|int|float|string
*/
public function getMaxValue()
{
return $this->maxValue;
}
/**
* Set specification string to use in forming SQL predicate
*
* @param string $specification
* @return $this Provides a fluent interface
*/
public function setSpecification($specification)
{
$this->specification = $specification;
return $this;
}
/**
* Get specification string to use in forming SQL predicate
*
* @return string
*/
public function getSpecification()
{
return $this->specification;
}
/**
* Return "where" parts
*
* @return array
*/
public function getExpressionData()
{
[$values[], $types[]] = $this->normalizeArgument($this->identifier, self::TYPE_IDENTIFIER);
[$values[], $types[]] = $this->normalizeArgument($this->minValue, self::TYPE_VALUE);
[$values[], $types[]] = $this->normalizeArgument($this->maxValue, self::TYPE_VALUE);
return [
[
$this->getSpecification(),
$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/Platform/PlatformDecoratorInterface.php | src/Sql/Platform/PlatformDecoratorInterface.php | <?php
namespace Laminas\Db\Sql\Platform;
interface PlatformDecoratorInterface
{
/**
* @param null|object $subject
* @return $this
*/
public function setSubject($subject);
}
| 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/Platform/Platform.php | src/Sql/Platform/Platform.php | <?php
namespace Laminas\Db\Sql\Platform;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Adapter\StatementContainerInterface;
use Laminas\Db\Sql\Exception;
use Laminas\Db\Sql\PreparableSqlInterface;
use Laminas\Db\Sql\SqlInterface;
use function is_a;
use function sprintf;
use function str_replace;
use function strtolower;
class Platform extends AbstractPlatform
{
/** @var AdapterInterface */
protected $adapter;
/** @var PlatformInterface|null */
protected $defaultPlatform;
public function __construct(AdapterInterface $adapter)
{
$this->defaultPlatform = $adapter->getPlatform();
$mySqlPlatform = new Mysql\Mysql();
$sqlServerPlatform = new SqlServer\SqlServer();
$oraclePlatform = new Oracle\Oracle();
$ibmDb2Platform = new IbmDb2\IbmDb2();
$sqlitePlatform = new Sqlite\Sqlite();
$this->decorators['mysql'] = $mySqlPlatform->getDecorators();
$this->decorators['sqlserver'] = $sqlServerPlatform->getDecorators();
$this->decorators['oracle'] = $oraclePlatform->getDecorators();
$this->decorators['ibmdb2'] = $ibmDb2Platform->getDecorators();
$this->decorators['sqlite'] = $sqlitePlatform->getDecorators();
}
/**
* @param string $type
* @param AdapterInterface|PlatformInterface $adapterOrPlatform
*/
public function setTypeDecorator($type, PlatformDecoratorInterface $decorator, $adapterOrPlatform = null)
{
$platformName = $this->resolvePlatformName($adapterOrPlatform);
$this->decorators[$platformName][$type] = $decorator;
}
/**
* @param PreparableSqlInterface|SqlInterface $subject
* @param AdapterInterface|PlatformInterface|null $adapterOrPlatform
* @return PlatformDecoratorInterface|PreparableSqlInterface|SqlInterface
*/
public function getTypeDecorator($subject, $adapterOrPlatform = null)
{
$platformName = $this->resolvePlatformName($adapterOrPlatform);
if (isset($this->decorators[$platformName])) {
foreach ($this->decorators[$platformName] as $type => $decorator) {
if ($subject instanceof $type && is_a($decorator, $type, true)) {
$decorator->setSubject($subject);
return $decorator;
}
}
}
return $subject;
}
/**
* @return array|PlatformDecoratorInterface[]
*/
public function getDecorators()
{
$platformName = $this->resolvePlatformName($this->getDefaultPlatform());
return $this->decorators[$platformName];
}
/**
* {@inheritDoc}
*
* @throws Exception\RuntimeException
*/
public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer)
{
if (! $this->subject instanceof PreparableSqlInterface) {
throw new Exception\RuntimeException(
'The subject does not appear to implement Laminas\Db\Sql\PreparableSqlInterface, thus calling '
. 'prepareStatement() has no effect'
);
}
$this->getTypeDecorator($this->subject, $adapter)->prepareStatement($adapter, $statementContainer);
return $statementContainer;
}
/**
* {@inheritDoc}
*
* @throws Exception\RuntimeException
*/
public function getSqlString(?PlatformInterface $adapterPlatform = null)
{
if (! $this->subject instanceof SqlInterface) {
throw new Exception\RuntimeException(
'The subject does not appear to implement Laminas\Db\Sql\SqlInterface, thus calling '
. 'prepareStatement() has no effect'
);
}
$adapterPlatform = $this->resolvePlatform($adapterPlatform);
return $this->getTypeDecorator($this->subject, $adapterPlatform)->getSqlString($adapterPlatform);
}
/**
* @param AdapterInterface|PlatformInterface $adapterOrPlatform
* @return string
*/
protected function resolvePlatformName($adapterOrPlatform)
{
$platformName = $this->resolvePlatform($adapterOrPlatform)->getName();
return str_replace([' ', '_'], '', strtolower($platformName));
}
/**
* @param null|PlatformInterface|AdapterInterface $adapterOrPlatform
* @return PlatformInterface
* @throws Exception\InvalidArgumentException
*/
protected function resolvePlatform($adapterOrPlatform)
{
if (! $adapterOrPlatform) {
return $this->getDefaultPlatform();
}
if ($adapterOrPlatform instanceof AdapterInterface) {
return $adapterOrPlatform->getPlatform();
}
if ($adapterOrPlatform instanceof PlatformInterface) {
return $adapterOrPlatform;
}
throw new Exception\InvalidArgumentException(sprintf(
'$adapterOrPlatform should be null, %s, or %s',
AdapterInterface::class,
PlatformInterface::class
));
}
/**
* @return PlatformInterface
* @throws Exception\RuntimeException
*/
protected function getDefaultPlatform()
{
if (! $this->defaultPlatform) {
throw new Exception\RuntimeException('$this->defaultPlatform was not set');
}
return $this->defaultPlatform;
}
}
| 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/Platform/AbstractPlatform.php | src/Sql/Platform/AbstractPlatform.php | <?php
namespace Laminas\Db\Sql\Platform;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Adapter\StatementContainerInterface;
use Laminas\Db\Sql\Exception;
use Laminas\Db\Sql\PreparableSqlInterface;
use Laminas\Db\Sql\SqlInterface;
class AbstractPlatform implements PlatformDecoratorInterface, PreparableSqlInterface, SqlInterface
{
/** @var object|null */
protected $subject;
/** @var PlatformDecoratorInterface[] */
protected $decorators = [];
/**
* {@inheritDoc}
*/
public function setSubject($subject)
{
$this->subject = $subject;
return $this;
}
/**
* @param string $type
* @return void
*/
public function setTypeDecorator($type, PlatformDecoratorInterface $decorator)
{
$this->decorators[$type] = $decorator;
}
/**
* @param PreparableSqlInterface|SqlInterface $subject
* @return PlatformDecoratorInterface|PreparableSqlInterface|SqlInterface
*/
public function getTypeDecorator($subject)
{
foreach ($this->decorators as $type => $decorator) {
if ($subject instanceof $type) {
$decorator->setSubject($subject);
return $decorator;
}
}
return $subject;
}
/**
* @return array|PlatformDecoratorInterface[]
*/
public function getDecorators()
{
return $this->decorators;
}
/**
* {@inheritDoc}
*
* @throws Exception\RuntimeException
*/
public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer)
{
if (! $this->subject instanceof PreparableSqlInterface) {
throw new Exception\RuntimeException(
'The subject does not appear to implement Laminas\Db\Sql\PreparableSqlInterface, thus calling '
. 'prepareStatement() has no effect'
);
}
$this->getTypeDecorator($this->subject)->prepareStatement($adapter, $statementContainer);
return $statementContainer;
}
/**
* {@inheritDoc}
*
* @throws Exception\RuntimeException
*/
public function getSqlString(?PlatformInterface $adapterPlatform = null)
{
if (! $this->subject instanceof SqlInterface) {
throw new Exception\RuntimeException(
'The subject does not appear to implement Laminas\Db\Sql\SqlInterface, thus calling '
. 'prepareStatement() has no effect'
);
}
return $this->getTypeDecorator($this->subject)->getSqlString($adapterPlatform);
}
}
| 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/Platform/Mysql/Mysql.php | src/Sql/Platform/Mysql/Mysql.php | <?php
namespace Laminas\Db\Sql\Platform\Mysql;
use Laminas\Db\Sql\Ddl\AlterTable;
use Laminas\Db\Sql\Ddl\CreateTable;
use Laminas\Db\Sql\Platform\AbstractPlatform;
use Laminas\Db\Sql\Select;
class Mysql extends AbstractPlatform
{
public function __construct()
{
$this->setTypeDecorator(Select::class, new SelectDecorator());
$this->setTypeDecorator(CreateTable::class, new Ddl\CreateTableDecorator());
$this->setTypeDecorator(AlterTable::class, new Ddl\AlterTableDecorator());
}
}
| 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/Platform/Mysql/SelectDecorator.php | src/Sql/Platform/Mysql/SelectDecorator.php | <?php
namespace Laminas\Db\Sql\Platform\Mysql;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\Platform\PlatformDecoratorInterface;
use Laminas\Db\Sql\Select;
class SelectDecorator extends Select implements PlatformDecoratorInterface
{
/** @var Select */
protected $subject;
/**
* @param Select $select
*/
public function setSubject($select)
{
$this->subject = $select;
}
protected function localizeVariables()
{
parent::localizeVariables();
if ($this->limit === null && $this->offset !== null) {
$this->specifications[self::LIMIT] = 'LIMIT 18446744073709551615';
}
}
/** @return null|string[] */
protected function processLimit(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->limit === null && $this->offset !== null) {
return [''];
}
if ($this->limit === null) {
return null;
}
if ($parameterContainer) {
$paramPrefix = $this->processInfo['paramPrefix'];
$parameterContainer->offsetSet($paramPrefix . 'limit', $this->limit, ParameterContainer::TYPE_INTEGER);
return [$driver->formatParameterName($paramPrefix . 'limit')];
}
return [$this->limit];
}
protected function processOffset(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->offset === null) {
return;
}
if ($parameterContainer) {
$paramPrefix = $this->processInfo['paramPrefix'];
$parameterContainer->offsetSet($paramPrefix . 'offset', $this->offset, ParameterContainer::TYPE_INTEGER);
return [$driver->formatParameterName($paramPrefix . 'offset')];
}
return [$this->offset];
}
}
| 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/Platform/Mysql/Ddl/AlterTableDecorator.php | src/Sql/Platform/Mysql/Ddl/AlterTableDecorator.php | <?php
namespace Laminas\Db\Sql\Platform\Mysql\Ddl;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\Ddl\AlterTable;
use Laminas\Db\Sql\Platform\PlatformDecoratorInterface;
use function count;
use function range;
use function str_replace;
use function strlen;
use function strpos;
use function strtolower;
use function strtoupper;
use function substr_replace;
use function uksort;
class AlterTableDecorator extends AlterTable implements PlatformDecoratorInterface
{
/** @var AlterTable */
protected $subject;
/** @var int[] */
protected $columnOptionSortOrder = [
'unsigned' => 0,
'zerofill' => 1,
'identity' => 2,
'serial' => 2,
'autoincrement' => 2,
'comment' => 3,
'columnformat' => 4,
'format' => 4,
'storage' => 5,
'after' => 6,
];
/**
* @param AlterTable $subject
* @return $this Provides a fluent interface
*/
public function setSubject($subject)
{
$this->subject = $subject;
return $this;
}
/**
* @param string $sql
* @return array
*/
protected function getSqlInsertOffsets($sql)
{
$sqlLength = strlen($sql);
$insertStart = [];
foreach (['NOT NULL', 'NULL', 'DEFAULT', 'UNIQUE', 'PRIMARY', 'REFERENCES'] as $needle) {
$insertPos = strpos($sql, ' ' . $needle);
if ($insertPos !== false) {
switch ($needle) {
case 'REFERENCES':
$insertStart[2] = ! isset($insertStart[2]) ? $insertPos : $insertStart[2];
// no break
case 'PRIMARY':
case 'UNIQUE':
$insertStart[1] = ! isset($insertStart[1]) ? $insertPos : $insertStart[1];
// no break
default:
$insertStart[0] = ! isset($insertStart[0]) ? $insertPos : $insertStart[0];
}
}
}
foreach (range(0, 3) as $i) {
$insertStart[$i] = $insertStart[$i] ?? $sqlLength;
}
return $insertStart;
}
/**
* @return array
*/
protected function processAddColumns(?PlatformInterface $adapterPlatform = null)
{
$sqls = [];
foreach ($this->addColumns as $i => $column) {
$sql = $this->processExpression($column, $adapterPlatform);
$insertStart = $this->getSqlInsertOffsets($sql);
$columnOptions = $column->getOptions();
uksort($columnOptions, [$this, 'compareColumnOptions']);
foreach ($columnOptions as $coName => $coValue) {
$insert = '';
if (! $coValue) {
continue;
}
switch ($this->normalizeColumnOption($coName)) {
case 'unsigned':
$insert = ' UNSIGNED';
$j = 0;
break;
case 'zerofill':
$insert = ' ZEROFILL';
$j = 0;
break;
case 'identity':
case 'serial':
case 'autoincrement':
$insert = ' AUTO_INCREMENT';
$j = 1;
break;
case 'comment':
$insert = ' COMMENT ' . $adapterPlatform->quoteValue($coValue);
$j = 2;
break;
case 'columnformat':
case 'format':
$insert = ' COLUMN_FORMAT ' . strtoupper($coValue);
$j = 2;
break;
case 'storage':
$insert = ' STORAGE ' . strtoupper($coValue);
$j = 2;
break;
case 'after':
$insert = ' AFTER ' . $adapterPlatform->quoteIdentifier($coValue);
$j = 2;
}
if ($insert) {
$j = $j ?? 0;
$sql = substr_replace($sql, $insert, $insertStart[$j], 0);
$insertStartCount = count($insertStart);
for (; $j < $insertStartCount; ++$j) {
$insertStart[$j] += strlen($insert);
}
}
}
$sqls[$i] = $sql;
}
return [$sqls];
}
/**
* @return array
*/
protected function processChangeColumns(?PlatformInterface $adapterPlatform = null)
{
$sqls = [];
foreach ($this->changeColumns as $name => $column) {
$sql = $this->processExpression($column, $adapterPlatform);
$insertStart = $this->getSqlInsertOffsets($sql);
$columnOptions = $column->getOptions();
uksort($columnOptions, [$this, 'compareColumnOptions']);
foreach ($columnOptions as $coName => $coValue) {
$insert = '';
if (! $coValue) {
continue;
}
switch ($this->normalizeColumnOption($coName)) {
case 'unsigned':
$insert = ' UNSIGNED';
$j = 0;
break;
case 'zerofill':
$insert = ' ZEROFILL';
$j = 0;
break;
case 'identity':
case 'serial':
case 'autoincrement':
$insert = ' AUTO_INCREMENT';
$j = 1;
break;
case 'comment':
$insert = ' COMMENT ' . $adapterPlatform->quoteValue($coValue);
$j = 2;
break;
case 'columnformat':
case 'format':
$insert = ' COLUMN_FORMAT ' . strtoupper($coValue);
$j = 2;
break;
case 'storage':
$insert = ' STORAGE ' . strtoupper($coValue);
$j = 2;
break;
}
if ($insert) {
$j = $j ?? 0;
$sql = substr_replace($sql, $insert, $insertStart[$j], 0);
$insertStartCount = count($insertStart);
for (; $j < $insertStartCount; ++$j) {
$insertStart[$j] += strlen($insert);
}
}
}
$sqls[] = [
$adapterPlatform->quoteIdentifier($name),
$sql,
];
}
return [$sqls];
}
/**
* @param string $name
* @return string
*/
private function normalizeColumnOption($name)
{
return strtolower(str_replace(['-', '_', ' '], '', $name));
}
/**
* @param string $columnA
* @param string $columnB
* @return int
*/
// phpcs:ignore SlevomatCodingStandard.Classes.UnusedPrivateElements.UnusedMethod
private function compareColumnOptions($columnA, $columnB)
{
$columnA = $this->normalizeColumnOption($columnA);
$columnA = $this->columnOptionSortOrder[$columnA] ?? count($this->columnOptionSortOrder);
$columnB = $this->normalizeColumnOption($columnB);
$columnB = $this->columnOptionSortOrder[$columnB] ?? count($this->columnOptionSortOrder);
return $columnA - $columnB;
}
}
| 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/Platform/Mysql/Ddl/CreateTableDecorator.php | src/Sql/Platform/Mysql/Ddl/CreateTableDecorator.php | <?php
namespace Laminas\Db\Sql\Platform\Mysql\Ddl;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\Ddl\CreateTable;
use Laminas\Db\Sql\Platform\PlatformDecoratorInterface;
use function count;
use function range;
use function str_replace;
use function strlen;
use function strpos;
use function strtolower;
use function strtoupper;
use function substr_replace;
use function uksort;
class CreateTableDecorator extends CreateTable implements PlatformDecoratorInterface
{
/** @var CreateTable */
protected $subject;
/** @var int[] */
protected $columnOptionSortOrder = [
'unsigned' => 0,
'zerofill' => 1,
'identity' => 2,
'serial' => 2,
'autoincrement' => 2,
'comment' => 3,
'columnformat' => 4,
'format' => 4,
'storage' => 5,
];
/**
* @param CreateTable $subject
* @return $this Provides a fluent interface
*/
public function setSubject($subject)
{
$this->subject = $subject;
return $this;
}
/**
* @param string $sql
* @return array
*/
protected function getSqlInsertOffsets($sql)
{
$sqlLength = strlen($sql);
$insertStart = [];
foreach (['NOT NULL', 'NULL', 'DEFAULT', 'UNIQUE', 'PRIMARY', 'REFERENCES'] as $needle) {
$insertPos = strpos($sql, ' ' . $needle);
if ($insertPos !== false) {
switch ($needle) {
case 'REFERENCES':
$insertStart[2] = ! isset($insertStart[2]) ? $insertPos : $insertStart[2];
// no break
case 'PRIMARY':
case 'UNIQUE':
$insertStart[1] = ! isset($insertStart[1]) ? $insertPos : $insertStart[1];
// no break
default:
$insertStart[0] = ! isset($insertStart[0]) ? $insertPos : $insertStart[0];
}
}
}
foreach (range(0, 3) as $i) {
$insertStart[$i] = $insertStart[$i] ?? $sqlLength;
}
return $insertStart;
}
/**
* {@inheritDoc}
*/
protected function processColumns(?PlatformInterface $platform = null)
{
if (! $this->columns) {
return;
}
$sqls = [];
foreach ($this->columns as $i => $column) {
$sql = $this->processExpression($column, $platform);
$insertStart = $this->getSqlInsertOffsets($sql);
$columnOptions = $column->getOptions();
uksort($columnOptions, [$this, 'compareColumnOptions']);
foreach ($columnOptions as $coName => $coValue) {
$insert = '';
if (! $coValue) {
continue;
}
switch ($this->normalizeColumnOption($coName)) {
case 'unsigned':
$insert = ' UNSIGNED';
$j = 0;
break;
case 'zerofill':
$insert = ' ZEROFILL';
$j = 0;
break;
case 'identity':
case 'serial':
case 'autoincrement':
$insert = ' AUTO_INCREMENT';
$j = 1;
break;
case 'comment':
$insert = ' COMMENT ' . $platform->quoteValue($coValue);
$j = 2;
break;
case 'columnformat':
case 'format':
$insert = ' COLUMN_FORMAT ' . strtoupper($coValue);
$j = 2;
break;
case 'storage':
$insert = ' STORAGE ' . strtoupper($coValue);
$j = 2;
break;
}
if ($insert) {
$j = $j ?? 0;
$sql = substr_replace($sql, $insert, $insertStart[$j], 0);
$insertStartCount = count($insertStart);
for (; $j < $insertStartCount; ++$j) {
$insertStart[$j] += strlen($insert);
}
}
}
$sqls[$i] = $sql;
}
return [$sqls];
}
/**
* @param string $name
* @return string
*/
private function normalizeColumnOption($name)
{
return strtolower(str_replace(['-', '_', ' '], '', $name));
}
/**
* @param string $columnA
* @param string $columnB
* @return int
*/
// phpcs:ignore SlevomatCodingStandard.Classes.UnusedPrivateElements.UnusedMethod
private function compareColumnOptions($columnA, $columnB)
{
$columnA = $this->normalizeColumnOption($columnA);
$columnA = $this->columnOptionSortOrder[$columnA] ?? count($this->columnOptionSortOrder);
$columnB = $this->normalizeColumnOption($columnB);
$columnB = $this->columnOptionSortOrder[$columnB] ?? count($this->columnOptionSortOrder);
return $columnA - $columnB;
}
}
| 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/Platform/IbmDb2/IbmDb2.php | src/Sql/Platform/IbmDb2/IbmDb2.php | <?php
namespace Laminas\Db\Sql\Platform\IbmDb2;
use Laminas\Db\Sql\Platform\AbstractPlatform;
use Laminas\Db\Sql\Select;
class IbmDb2 extends AbstractPlatform
{
public function __construct(?SelectDecorator $selectDecorator = null)
{
$this->setTypeDecorator(Select::class, $selectDecorator ?: new SelectDecorator());
}
}
| 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/Platform/IbmDb2/SelectDecorator.php | src/Sql/Platform/IbmDb2/SelectDecorator.php | <?php
namespace Laminas\Db\Sql\Platform\IbmDb2;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\Platform\PlatformDecoratorInterface;
use Laminas\Db\Sql\Select;
use function array_push;
use function array_shift;
use function array_unshift;
use function current;
use function preg_match;
use function sprintf;
use function strpos;
class SelectDecorator extends Select implements PlatformDecoratorInterface
{
/** @var bool */
protected $isSelectContainDistinct = false;
/** @var Select */
protected $subject;
/** @var bool */
protected $supportsLimitOffset = false;
/**
* @return bool
*/
public function getIsSelectContainDistinct()
{
return $this->isSelectContainDistinct;
}
/**
* @param boolean $isSelectContainDistinct
*/
public function setIsSelectContainDistinct($isSelectContainDistinct)
{
$this->isSelectContainDistinct = $isSelectContainDistinct;
}
/**
* @param Select $select
*/
public function setSubject($select)
{
$this->subject = $select;
}
/**
* @return bool
*/
public function getSupportsLimitOffset()
{
return $this->supportsLimitOffset;
}
/**
* @param bool $supportsLimitOffset
*/
public function setSupportsLimitOffset($supportsLimitOffset)
{
$this->supportsLimitOffset = $supportsLimitOffset;
}
/**
* @see Select::renderTable
*
* @param string $table
* @param null|string $alias
* @return string
*/
protected function renderTable($table, $alias = null)
{
return $table . ' ' . $alias;
}
protected function localizeVariables()
{
parent::localizeVariables();
// set specifications
unset($this->specifications[self::LIMIT]);
unset($this->specifications[self::OFFSET]);
$this->specifications['LIMITOFFSET'] = null;
}
/**
* @param array $sqls
* @param array $parameters
*/
protected function processLimitOffset(
PlatformInterface $platform,
?DriverInterface $driver,
?ParameterContainer $parameterContainer,
&$sqls,
&$parameters
) {
if ($this->limit === null && $this->offset === null) {
return;
}
if ($this->supportsLimitOffset) {
// Note: db2_prepare/db2_execute fails with positional parameters, for LIMIT & OFFSET
$limit = (int) $this->limit;
if (! $limit) {
return;
}
$offset = (int) $this->offset;
if ($offset) {
array_push($sqls, sprintf("LIMIT %s OFFSET %s", $limit, $offset));
return;
}
array_push($sqls, sprintf("LIMIT %s", $limit));
return;
}
$selectParameters = $parameters[self::SELECT];
$starSuffix = $platform->getIdentifierSeparator() . self::SQL_STAR;
foreach ($selectParameters[0] as $i => $columnParameters) {
if (
$columnParameters[0] === self::SQL_STAR
|| (isset($columnParameters[1]) && $columnParameters[1] === self::SQL_STAR)
|| strpos($columnParameters[0], $starSuffix)
) {
$selectParameters[0] = [[self::SQL_STAR]];
break;
}
if (isset($columnParameters[1])) {
array_shift($columnParameters);
$selectParameters[0][$i] = $columnParameters;
}
}
// first, produce column list without compound names (using the AS portion only)
array_unshift($sqls, $this->createSqlFromSpecificationAndParameters(
['SELECT %1$s FROM (' => current($this->specifications[self::SELECT])],
$selectParameters
));
if (preg_match('/DISTINCT/i', $sqls[0])) {
$this->setIsSelectContainDistinct(true);
}
if ($parameterContainer) {
// create bottom part of query, with offset and limit using row_number
$limitParamName = $driver->formatParameterName('limit');
$offsetParamName = $driver->formatParameterName('offset');
array_push($sqls, sprintf(
// @codingStandardsIgnoreStart
") AS LAMINAS_IBMDB2_SERVER_LIMIT_OFFSET_EMULATION WHERE LAMINAS_IBMDB2_SERVER_LIMIT_OFFSET_EMULATION.LAMINAS_DB_ROWNUM BETWEEN %s AND %s",
// @codingStandardsIgnoreEnd
$offsetParamName,
$limitParamName
));
if ((int) $this->offset > 0) {
$parameterContainer->offsetSet('offset', (int) $this->offset + 1);
} else {
$parameterContainer->offsetSet('offset', (int) $this->offset);
}
$parameterContainer->offsetSet('limit', (int) $this->limit + (int) $this->offset);
} else {
if ((int) $this->offset > 0) {
$offset = (int) $this->offset + 1;
} else {
$offset = (int) $this->offset;
}
array_push($sqls, sprintf(
// @codingStandardsIgnoreStart
") AS LAMINAS_IBMDB2_SERVER_LIMIT_OFFSET_EMULATION WHERE LAMINAS_IBMDB2_SERVER_LIMIT_OFFSET_EMULATION.LAMINAS_DB_ROWNUM BETWEEN %d AND %d",
// @codingStandardsIgnoreEnd
$offset,
(int) $this->limit + (int) $this->offset
));
}
if (isset($sqls[self::ORDER])) {
$orderBy = $sqls[self::ORDER];
unset($sqls[self::ORDER]);
} else {
$orderBy = '';
}
// add a column for row_number() using the order specification //dense_rank()
if ($this->getIsSelectContainDistinct()) {
$parameters[self::SELECT][0][] = ['DENSE_RANK() OVER (' . $orderBy . ')', 'LAMINAS_DB_ROWNUM'];
} else {
$parameters[self::SELECT][0][] = ['ROW_NUMBER() OVER (' . $orderBy . ')', 'LAMINAS_DB_ROWNUM'];
}
$sqls[self::SELECT] = $this->createSqlFromSpecificationAndParameters(
$this->specifications[self::SELECT],
$parameters[self::SELECT]
);
}
}
| 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/Platform/Sqlite/SelectDecorator.php | src/Sql/Platform/Sqlite/SelectDecorator.php | <?php
namespace Laminas\Db\Sql\Platform\Sqlite;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\Platform\PlatformDecoratorInterface;
use Laminas\Db\Sql\Select;
class SelectDecorator extends Select implements PlatformDecoratorInterface
{
/** @var Select */
protected $subject;
/**
* Set Subject
*
* @param Select $select
* @return $this Provides a fluent interface
*/
public function setSubject($select)
{
$this->subject = $select;
return $this;
}
/**
* {@inheritDoc}
*/
protected function localizeVariables()
{
parent::localizeVariables();
$this->specifications[self::COMBINE] = '%1$s %2$s';
}
/**
* {@inheritDoc}
*/
protected function processStatementStart(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
return '';
}
/** @return string[] */
protected function processLimit(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->limit === null && $this->offset !== null) {
return [''];
}
if ($this->limit === null) {
return;
}
if ($parameterContainer) {
$paramPrefix = $this->processInfo['paramPrefix'];
$parameterContainer->offsetSet($paramPrefix . 'limit', $this->limit, ParameterContainer::TYPE_INTEGER);
return [$driver->formatParameterName('limit')];
}
return [$this->limit];
}
protected function processOffset(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
if ($this->offset === null) {
return;
}
if ($parameterContainer) {
$paramPrefix = $this->processInfo['paramPrefix'];
$parameterContainer->offsetSet($paramPrefix . 'offset', $this->offset, ParameterContainer::TYPE_INTEGER);
return [$driver->formatParameterName('offset')];
}
return [$this->offset];
}
/**
* {@inheritDoc}
*/
protected function processStatementEnd(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
) {
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/Platform/Sqlite/Sqlite.php | src/Sql/Platform/Sqlite/Sqlite.php | <?php
namespace Laminas\Db\Sql\Platform\Sqlite;
use Laminas\Db\Sql\Platform\AbstractPlatform;
use Laminas\Db\Sql\Select;
class Sqlite extends AbstractPlatform
{
/**
* Constructor
*
* Registers the type decorator.
*/
public function __construct()
{
$this->setTypeDecorator(Select::class, new SelectDecorator());
}
}
| 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/Platform/SqlServer/SelectDecorator.php | src/Sql/Platform/SqlServer/SelectDecorator.php | <?php
namespace Laminas\Db\Sql\Platform\SqlServer;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\Platform\PlatformDecoratorInterface;
use Laminas\Db\Sql\Select;
use function array_push;
use function array_shift;
use function array_unshift;
use function array_values;
use function current;
use function strpos;
class SelectDecorator extends Select implements PlatformDecoratorInterface
{
/** @var Select */
protected $subject;
/**
* @param Select $select
*/
public function setSubject($select)
{
$this->subject = $select;
}
protected function localizeVariables()
{
parent::localizeVariables();
// set specifications
unset($this->specifications[self::LIMIT]);
unset($this->specifications[self::OFFSET]);
$this->specifications['LIMITOFFSET'] = null;
}
/**
* @param string[] $sqls
* @param array<string, array> $parameters
* @return void
*/
protected function processLimitOffset(
PlatformInterface $platform,
?DriverInterface $driver,
?ParameterContainer $parameterContainer,
&$sqls,
&$parameters
) {
if ($this->limit === null && $this->offset === null) {
return;
}
$selectParameters = $parameters[self::SELECT];
/** if this is a DISTINCT query then real SELECT part goes to second element in array **/
$parameterIndex = 0;
if ($selectParameters[0] === 'DISTINCT') {
unset($selectParameters[0]);
$selectParameters = array_values($selectParameters);
$parameterIndex = 1;
}
$starSuffix = $platform->getIdentifierSeparator() . self::SQL_STAR;
foreach ($selectParameters[0] as $i => $columnParameters) {
if (
$columnParameters[0] === self::SQL_STAR
|| (isset($columnParameters[1]) && $columnParameters[1] === self::SQL_STAR)
|| strpos($columnParameters[0], $starSuffix)
) {
$selectParameters[0] = [[self::SQL_STAR]];
break;
}
if (isset($columnParameters[1])) {
array_shift($columnParameters);
$selectParameters[0][$i] = $columnParameters;
}
}
// first, produce column list without compound names (using the AS portion only)
array_unshift($sqls, $this->createSqlFromSpecificationAndParameters(
['SELECT %1$s FROM (' => current($this->specifications[self::SELECT])],
$selectParameters
));
// phpcs:disable Generic.Files.LineLength.TooLong
if ($parameterContainer) {
// create bottom part of query, with offset and limit using row_number
$limitParamName = $driver->formatParameterName('limit');
$offsetParamName = $driver->formatParameterName('offset');
$offsetForSumParamName = $driver->formatParameterName('offsetForSum');
array_push(
$sqls,
') AS [LAMINAS_SQL_SERVER_LIMIT_OFFSET_EMULATION] WHERE [LAMINAS_SQL_SERVER_LIMIT_OFFSET_EMULATION].[__LAMINAS_ROW_NUMBER] BETWEEN '
. $offsetParamName
. '+1 AND '
. $limitParamName
. '+'
. $offsetForSumParamName
);
$parameterContainer->offsetSet('offset', $this->offset);
$parameterContainer->offsetSet('limit', $this->limit);
$parameterContainer->offsetSetReference('offsetForSum', 'offset');
} else {
array_push(
$sqls,
') AS [LAMINAS_SQL_SERVER_LIMIT_OFFSET_EMULATION] WHERE [LAMINAS_SQL_SERVER_LIMIT_OFFSET_EMULATION].[__LAMINAS_ROW_NUMBER] BETWEEN '
. (int) $this->offset
. '+1 AND '
. (int) $this->limit
. '+'
. (int) $this->offset
);
}
// phpcs:enable Generic.Files.LineLength.TooLong
if (isset($sqls[self::ORDER])) {
$orderBy = $sqls[self::ORDER];
unset($sqls[self::ORDER]);
} else {
$orderBy = 'ORDER BY (SELECT 1)';
}
// add a column for row_number() using the order specification
$parameters[self::SELECT][$parameterIndex][] = [
'ROW_NUMBER() OVER (' . $orderBy . ')',
'[__LAMINAS_ROW_NUMBER]',
];
$sqls[self::SELECT] = $this->createSqlFromSpecificationAndParameters(
$this->specifications[self::SELECT],
$parameters[self::SELECT]
);
}
}
| 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/Platform/SqlServer/SqlServer.php | src/Sql/Platform/SqlServer/SqlServer.php | <?php
namespace Laminas\Db\Sql\Platform\SqlServer;
use Laminas\Db\Sql\Ddl\CreateTable;
use Laminas\Db\Sql\Platform\AbstractPlatform;
use Laminas\Db\Sql\Select;
class SqlServer extends AbstractPlatform
{
public function __construct(?SelectDecorator $selectDecorator = null)
{
$this->setTypeDecorator(Select::class, $selectDecorator ?: new SelectDecorator());
$this->setTypeDecorator(CreateTable::class, new Ddl\CreateTableDecorator());
}
}
| 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/Platform/SqlServer/Ddl/CreateTableDecorator.php | src/Sql/Platform/SqlServer/Ddl/CreateTableDecorator.php | <?php
namespace Laminas\Db\Sql\Platform\SqlServer\Ddl;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\Ddl\CreateTable;
use Laminas\Db\Sql\Platform\PlatformDecoratorInterface;
use function ltrim;
class CreateTableDecorator extends CreateTable implements PlatformDecoratorInterface
{
/** @var CreateTable */
protected $subject;
/**
* @param CreateTable $subject
* @return $this Provides a fluent interface
*/
public function setSubject($subject)
{
$this->subject = $subject;
return $this;
}
/**
* @return array
*/
protected function processTable(?PlatformInterface $adapterPlatform = null)
{
$table = ($this->isTemporary ? '#' : '') . ltrim($this->table, '#');
return [
'',
$adapterPlatform->quoteIdentifier($table),
];
}
}
| 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/Platform/Oracle/Oracle.php | src/Sql/Platform/Oracle/Oracle.php | <?php
namespace Laminas\Db\Sql\Platform\Oracle;
use Laminas\Db\Sql\Platform\AbstractPlatform;
use Laminas\Db\Sql\Select;
class Oracle extends AbstractPlatform
{
public function __construct(?SelectDecorator $selectDecorator = null)
{
$this->setTypeDecorator(Select::class, $selectDecorator ?: new SelectDecorator());
}
}
| 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/Platform/Oracle/SelectDecorator.php | src/Sql/Platform/Oracle/SelectDecorator.php | <?php
namespace Laminas\Db\Sql\Platform\Oracle;
use Laminas\Db\Adapter\Driver\DriverInterface;
use Laminas\Db\Adapter\ParameterContainer;
use Laminas\Db\Adapter\Platform\PlatformInterface;
use Laminas\Db\Sql\Platform\PlatformDecoratorInterface;
use Laminas\Db\Sql\Select;
use function array_push;
use function array_shift;
use function array_unshift;
use function current;
use function strpos;
class SelectDecorator extends Select implements PlatformDecoratorInterface
{
/** @var Select */
protected $subject;
/**
* @param Select $select
*/
public function setSubject($select)
{
$this->subject = $select;
}
/**
* @see \Laminas\Db\Sql\Select::renderTable
*
* @param string $table
* @param null|string $alias
* @return string
*/
protected function renderTable($table, $alias = null)
{
return $table . ($alias ? ' ' . $alias : '');
}
protected function localizeVariables()
{
parent::localizeVariables();
unset($this->specifications[self::LIMIT]);
unset($this->specifications[self::OFFSET]);
$this->specifications['LIMITOFFSET'] = null;
}
/**
* @param array $sqls
* @param array $parameters
* @return null
*/
protected function processLimitOffset(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null,
&$sqls = [],
&$parameters = []
) {
if ($this->limit === null && $this->offset === null) {
return;
}
$selectParameters = $parameters[self::SELECT];
$starSuffix = $platform->getIdentifierSeparator() . self::SQL_STAR;
foreach ($selectParameters[0] as $i => $columnParameters) {
if (
$columnParameters[0] === self::SQL_STAR
|| (isset($columnParameters[1]) && $columnParameters[1] === self::SQL_STAR)
|| strpos($columnParameters[0], $starSuffix)
) {
$selectParameters[0] = [[self::SQL_STAR]];
break;
}
if (isset($columnParameters[1])) {
array_shift($columnParameters);
$selectParameters[0][$i] = $columnParameters;
}
}
if ($this->offset === null) {
$this->offset = 0;
}
// first, produce column list without compound names (using the AS portion only)
array_unshift($sqls, $this->createSqlFromSpecificationAndParameters([
'SELECT %1$s FROM (SELECT b.%1$s, rownum b_rownum FROM (' => current($this->specifications[self::SELECT]),
], $selectParameters));
if ($parameterContainer) {
$number = $this->processInfo['subselectCount'] ? $this->processInfo['subselectCount'] : '';
if ($this->limit === null) {
array_push(
$sqls,
') b ) WHERE b_rownum > (:offset' . $number . ')'
);
$parameterContainer->offsetSet(
'offset' . $number,
$this->offset,
$parameterContainer::TYPE_INTEGER
);
} else {
// create bottom part of query, with offset and limit using row_number
array_push(
$sqls,
') b WHERE rownum <= (:offset'
. $number
. '+:limit'
. $number
. ')) WHERE b_rownum >= (:offset'
. $number
. ' + 1)'
);
$parameterContainer->offsetSet(
'offset' . $number,
$this->offset,
$parameterContainer::TYPE_INTEGER
);
$parameterContainer->offsetSet(
'limit' . $number,
$this->limit,
$parameterContainer::TYPE_INTEGER
);
}
$this->processInfo['subselectCount']++;
} else {
if ($this->limit === null) {
array_push($sqls, ') b ) WHERE b_rownum > (' . (int) $this->offset . ')');
} else {
array_push(
$sqls,
') b WHERE rownum <= ('
. (int) $this->offset
. '+'
. (int) $this->limit
. ')) WHERE b_rownum >= ('
. (int) $this->offset
. ' + 1)'
);
}
}
$sqls[self::SELECT] = $this->createSqlFromSpecificationAndParameters(
$this->specifications[self::SELECT],
$parameters[self::SELECT]
);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/IntegrationTestListener.php | test/integration/IntegrationTestListener.php | <?php
namespace LaminasIntegrationTest\Db;
use LaminasIntegrationTest\Db\Platform\FixtureLoader;
use LaminasIntegrationTest\Db\Platform\MysqlFixtureLoader;
use LaminasIntegrationTest\Db\Platform\PgsqlFixtureLoader;
use LaminasIntegrationTest\Db\Platform\SqlServerFixtureLoader;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestListenerDefaultImplementation;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Runner\TestHook;
use function getenv;
use function printf;
class IntegrationTestListener implements TestHook, TestListener
{
use TestListenerDefaultImplementation;
/** @var FixtureLoader[] */
private $fixtureLoaders = [];
public function startTestSuite(TestSuite $suite): void
{
if ($suite->getName() !== 'integration test') {
return;
}
if (getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL')) {
$this->fixtureLoaders[] = new MysqlFixtureLoader();
}
if (getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL')) {
$this->fixtureLoaders[] = new PgsqlFixtureLoader();
}
if (getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV')) {
$this->fixtureLoaders[] = new SqlServerFixtureLoader();
}
if (empty($this->fixtureLoaders)) {
return;
}
printf("\nIntegration test started.\n");
foreach ($this->fixtureLoaders as $fixtureLoader) {
$fixtureLoader->createDatabase();
}
}
public function endTestSuite(TestSuite $suite): void
{
if (
$suite->getName() !== 'integration test'
|| empty($this->fixtureLoaders)
) {
return;
}
printf("\nIntegration test ended.\n");
foreach ($this->fixtureLoaders as $fixtureLoader) {
$fixtureLoader->dropDatabase();
}
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Driver/Pdo/AbstractAdapterTest.php | test/integration/Adapter/Driver/Pdo/AbstractAdapterTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Driver\Pdo;
use Laminas\Db\Adapter\Adapter;
use PHPUnit\Framework\TestCase;
use function getmypid;
use function shell_exec;
/**
* @property Adapter $adapter
*/
abstract class AbstractAdapterTest extends TestCase
{
public const DB_SERVER_PORT = null;
/**
* @covers \Laminas\Db\Adapter\Adapter::__construct()
*/
public function testConnection()
{
$this->assertInstanceOf(Adapter::class, $this->adapter);
}
public function testDriverDisconnectAfterQuoteWithPlatform()
{
$isTcpConnection = $this->isTcpConnection();
$this->adapter->getDriver()->getConnection()->connect();
self::assertTrue($this->adapter->getDriver()->getConnection()->isConnected());
if ($isTcpConnection) {
self::assertTrue($this->isConnectedTcp());
}
$this->adapter->getDriver()->getConnection()->disconnect();
self::assertFalse($this->adapter->getDriver()->getConnection()->isConnected());
if ($isTcpConnection) {
self::assertFalse($this->isConnectedTcp());
}
$this->adapter->getDriver()->getConnection()->connect();
self::assertTrue($this->adapter->getDriver()->getConnection()->isConnected());
if ($isTcpConnection) {
self::assertTrue($this->isConnectedTcp());
}
$this->adapter->getPlatform()->quoteValue('test');
$this->adapter->getDriver()->getConnection()->disconnect();
self::assertFalse($this->adapter->getDriver()->getConnection()->isConnected());
if ($isTcpConnection) {
self::assertFalse($this->isConnectedTcp());
}
}
protected function isConnectedTcp(): bool
{
$mypid = getmypid();
$dbPort = static::DB_SERVER_PORT;
$lsof = shell_exec("lsof -i -P -n | grep $dbPort | grep $mypid");
return $lsof !== null;
}
protected function isTcpConnection(): bool
{
return $this->getHostname() !== 'localhost';
}
abstract protected function getHostname();
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Driver/Pdo/Mysql/TableGatewayTest.php | test/integration/Adapter/Driver/Pdo/Mysql/TableGatewayTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Driver\Pdo\Mysql;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\Sql\TableIdentifier;
use Laminas\Db\TableGateway\Feature\MetadataFeature;
use Laminas\Db\TableGateway\TableGateway;
use PHPUnit\Framework\TestCase;
use function count;
class TableGatewayTest extends TestCase
{
use AdapterTrait;
/** @var Adapter */
protected $adapter;
/**
* @covers \Laminas\Db\TableGateway\TableGateway::__construct
*/
public function testConstructor()
{
$tableGateway = new TableGateway('test', $this->adapter);
$this->assertInstanceOf(TableGateway::class, $tableGateway);
}
/**
* @covers \Laminas\Db\TableGateway\TableGateway::select
*/
public function testSelect()
{
$tableGateway = new TableGateway('test', $this->adapter);
$rowset = $tableGateway->select();
$this->assertTrue(count($rowset) > 0);
foreach ($rowset as $row) {
$this->assertTrue(isset($row->id));
$this->assertNotEmpty(isset($row->name));
$this->assertNotEmpty(isset($row->value));
}
}
/**
* @covers \Laminas\Db\TableGateway\TableGateway::insert
* @covers \Laminas\Db\TableGateway\TableGateway::select
*/
public function testInsert()
{
$tableGateway = new TableGateway('test', $this->adapter);
$rowset = $tableGateway->select();
$data = [
'name' => 'test_name',
'value' => 'test_value',
];
$affectedRows = $tableGateway->insert($data);
$this->assertEquals(1, $affectedRows);
$rowSet = $tableGateway->select(['id' => $tableGateway->getLastInsertValue()]);
$row = $rowSet->current();
foreach ($data as $key => $value) {
$this->assertEquals($row->$key, $value);
}
}
/**
* @see https://github.com/zendframework/zend-db/issues/35
* @see https://github.com/zendframework/zend-db/pull/178
*
* @return mixed
*/
public function testInsertWithExtendedCharsetFieldName()
{
$tableGateway = new TableGateway('test_charset', $this->adapter);
$affectedRows = $tableGateway->insert([
'field$' => 'test_value1',
'field_' => 'test_value2',
]);
$this->assertEquals(1, $affectedRows);
return $tableGateway->getLastInsertValue();
}
/**
* @depends testInsertWithExtendedCharsetFieldName
* @param mixed $id
*/
public function testUpdateWithExtendedCharsetFieldName($id)
{
$tableGateway = new TableGateway('test_charset', $this->adapter);
$data = [
'field$' => 'test_value3',
'field_' => 'test_value4',
];
$affectedRows = $tableGateway->update($data, ['id' => $id]);
$this->assertEquals(1, $affectedRows);
$rowSet = $tableGateway->select(['id' => $id]);
$row = $rowSet->current();
foreach ($data as $key => $value) {
$this->assertEquals($row->$key, $value);
}
}
/**
* @dataProvider tableProvider
* @param string|TableIdentifier|array $table
*/
public function testTableGatewayWithMetadataFeature($table)
{
$tableGateway = new TableGateway($table, $this->adapter, new MetadataFeature());
self::assertInstanceOf(TableGateway::class, $tableGateway);
self::assertSame($table, $tableGateway->getTable());
}
/** @psalm-return array<string, array{0: mixed}> */
public function tableProvider(): array
{
return [
'string' => ['test'],
'aliased string' => [['foo' => 'test']],
'TableIdentifier' => [new TableIdentifier('test')],
'aliased TableIdentifier' => [['foo' => new TableIdentifier('test')]],
];
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Driver/Pdo/Mysql/AdapterTest.php | test/integration/Adapter/Driver/Pdo/Mysql/AdapterTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Driver\Pdo\Mysql;
use Laminas\Db\Adapter\Adapter;
use LaminasIntegrationTest\Db\Adapter\Driver\Pdo\AbstractAdapterTest;
class AdapterTest extends AbstractAdapterTest
{
use AdapterTrait;
/** @var Adapter */
protected $adapter;
public const DB_SERVER_PORT = 3306;
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Driver/Pdo/Mysql/QueryTest.php | test/integration/Adapter/Driver/Pdo/Mysql/QueryTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Driver\Pdo\Mysql;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\Adapter\Driver\Pdo\Result as PdoResult;
use Laminas\Db\Adapter\Exception\RuntimeException;
use Laminas\Db\ResultSet\ResultSet;
use Laminas\Db\Sql\Sql;
use PHPUnit\Framework\TestCase;
class QueryTest extends TestCase
{
use AdapterTrait;
/** @var Adapter */
protected $adapter;
/**
* @psalm-return array<array-key, array{
* 0: string,
* 1: mixed[]|array<string, mixed>,
* 2: array<string, mixed>
* }>
*/
public function getQueriesWithRowResult(): array
{
return [
['SELECT * FROM test WHERE id = ?', [1], ['id' => 1, 'name' => 'foo', 'value' => 'bar']],
['SELECT * FROM test WHERE id = :id', [':id' => 1], ['id' => 1, 'name' => 'foo', 'value' => 'bar']],
['SELECT * FROM test WHERE id = :id', ['id' => 1], ['id' => 1, 'name' => 'foo', 'value' => 'bar']],
['SELECT * FROM test WHERE name = ?', ['123'], ['id' => '4', 'name' => '123', 'value' => 'bar']],
[
// name is string, but given parameter is int, can lead to unexpected result
'SELECT * FROM test WHERE name = ?',
[123],
['id' => '3', 'name' => '123a', 'value' => 'bar'],
],
];
}
/**
* @dataProvider getQueriesWithRowResult
* @covers \Laminas\Db\Adapter\Adapter::query
* @covers \Laminas\Db\ResultSet\ResultSet::current
*/
public function testQuery(string $query, array $params, array $expected)
{
$result = $this->adapter->query($query, $params);
$this->assertInstanceOf(ResultSet::class, $result);
$current = $result->current();
// test as array value
$this->assertEquals($expected, (array) $current);
// test as object value
foreach ($expected as $key => $value) {
$this->assertEquals($value, $current->$key);
}
}
/**
* @see https://github.com/zendframework/zend-db/issues/288
*/
public function testSetSessionTimeZone()
{
$result = $this->adapter->query('SET @@session.time_zone = :tz', [':tz' => 'SYSTEM']);
$this->assertInstanceOf(PdoResult::class, $result);
}
public function testSelectWithNotPermittedBindParamName()
{
$this->expectException(RuntimeException::class);
$this->adapter->query('SET @@session.time_zone = :tz$', [':tz$' => 'SYSTEM']);
}
/**
* @see https://github.com/laminas/laminas-db/issues/47
*/
public function testNamedParameters()
{
$sql = new Sql($this->adapter);
$insert = $sql->update('test');
$insert->set([
'name' => ':name',
'value' => ':value',
])->where(['id' => ':id']);
$stmt = $sql->prepareStatementForSqlObject($insert);
//positional parameters
$stmt->execute([
1,
'foo',
'bar',
]);
//"mapped" named parameters
$stmt->execute([
'c_0' => 1,
'c_1' => 'foo',
'where1' => 'bar',
]);
//real named parameters
$stmt->execute([
'id' => 1,
'name' => 'foo',
'value' => 'bar',
]);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Driver/Pdo/Mysql/AdapterTrait.php | test/integration/Adapter/Driver/Pdo/Mysql/AdapterTrait.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Driver\Pdo\Mysql;
use Laminas\Db\Adapter\Adapter;
use function getenv;
trait AdapterTrait
{
/** @var $adapter */
protected function setUp(): void
{
if (! getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL')) {
$this->markTestSkipped('pdo_mysql integration tests are not enabled!');
}
$this->adapter = new Adapter([
'driver' => 'pdo_mysql',
'database' => getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_DATABASE'),
'hostname' => getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_HOSTNAME'),
'username' => getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_USERNAME'),
'password' => getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_PASSWORD'),
]);
}
/** @return null|string */
protected function getHostname()
{
return getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_HOSTNAME');
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Driver/Pdo/Mysql/TableGatewayAndAdapterTest.php | test/integration/Adapter/Driver/Pdo/Mysql/TableGatewayAndAdapterTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Driver\Pdo\Mysql;
use Laminas\Db\TableGateway\TableGateway;
use PHPUnit\Framework\TestCase;
use function array_fill;
/**
* Usually mysql has 151 max connections by default.
* Set up a test where executed Laminas\Db\Adapter\Adapter::query and then using table gateway to fetch a row
* On tear down disconnected from the database and set the driver adapter on null
* Running many tests ended up in consuming all mysql connections and not releasing them
*/
class TableGatewayAndAdapterTest extends TestCase
{
use AdapterTrait;
/**
* @dataProvider connections
*/
public function testGetOutOfConnections(): void
{
$this->adapter->query('SELECT VERSION();');
$table = new TableGateway(
'test',
$this->adapter
);
$select = $table->getSql()->select()->where(['name' => 'foo']);
$result = $table->selectWith($select);
self::assertCount(3, $result->current());
}
protected function tearDown(): void
{
if ($this->adapter->getDriver()->getConnection()->isConnected()) {
$this->adapter->getDriver()->getConnection()->disconnect();
}
$this->adapter = null;
}
public function connections(): array
{
return array_fill(0, 200, []);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Driver/Pdo/Postgresql/TableGatewayTest.php | test/integration/Adapter/Driver/Pdo/Postgresql/TableGatewayTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Driver\Pdo\Postgresql;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\Sql\TableIdentifier;
use Laminas\Db\TableGateway\Feature\FeatureSet;
use Laminas\Db\TableGateway\Feature\SequenceFeature;
use Laminas\Db\TableGateway\TableGateway;
use PHPUnit\Framework\TestCase;
class TableGatewayTest extends TestCase
{
use AdapterTrait;
/** @var Adapter */
protected $adapter;
public function testLastInsertValue()
{
$table = new TableIdentifier('test_seq');
$featureSet = new FeatureSet();
$featureSet->addFeature(new SequenceFeature('id', 'test_seq_id_seq'));
$tableGateway = new TableGateway($table, $this->adapter, $featureSet);
$tableGateway->insert(['foo' => 'bar']);
self::assertSame(1, $tableGateway->getLastInsertValue());
$tableGateway->insert(['foo' => 'baz']);
self::assertSame(2, $tableGateway->getLastInsertValue());
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Driver/Pdo/Postgresql/AdapterTest.php | test/integration/Adapter/Driver/Pdo/Postgresql/AdapterTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Driver\Pdo\Postgresql;
use Laminas\Db\Adapter\Adapter;
use LaminasIntegrationTest\Db\Adapter\Driver\Pdo\AbstractAdapterTest;
class AdapterTest extends AbstractAdapterTest
{
use AdapterTrait;
/** @var Adapter */
protected $adapter;
public const DB_SERVER_PORT = 5432;
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Driver/Pdo/Postgresql/AdapterTrait.php | test/integration/Adapter/Driver/Pdo/Postgresql/AdapterTrait.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Driver\Pdo\Postgresql;
use Laminas\Db\Adapter\Adapter;
use function getenv;
trait AdapterTrait
{
protected function setUp(): void
{
if (! getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL')) {
$this->markTestSkipped('pdo_pgsql integration tests are not enabled!');
}
$this->adapter = new Adapter([
'driver' => 'pdo_pgsql',
'database' => getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_DATABASE'),
'hostname' => getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_HOSTNAME'),
'username' => getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_USERNAME'),
'password' => getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_PASSWORD'),
]);
}
/** @return null|string */
protected function getHostname()
{
return getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_HOSTNAME');
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Driver/Mysqli/TableGatewayTest.php | test/integration/Adapter/Driver/Mysqli/TableGatewayTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Driver\Mysqli;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\TableGateway\TableGateway;
use PHPUnit\Framework\TestCase;
class TableGatewayTest extends TestCase
{
use TraitSetup;
/**
* @see https://github.com/zendframework/zend-db/issues/330
*/
public function testSelectWithEmptyCurrentWithBufferResult()
{
$adapter = new Adapter([
'driver' => 'mysqli',
'database' => $this->variables['database'],
'hostname' => $this->variables['hostname'],
'username' => $this->variables['username'],
'password' => $this->variables['password'],
'options' => ['buffer_results' => true],
]);
$tableGateway = new TableGateway('test', $adapter);
$rowset = $tableGateway->select('id = 0');
$this->assertNull($rowset->current());
$adapter->getDriver()->getConnection()->disconnect();
}
/**
* @see https://github.com/zendframework/zend-db/issues/330
*/
public function testSelectWithEmptyCurrentWithoutBufferResult()
{
$adapter = new Adapter([
'driver' => 'mysqli',
'database' => $this->variables['database'],
'hostname' => $this->variables['hostname'],
'username' => $this->variables['username'],
'password' => $this->variables['password'],
'options' => ['buffer_results' => false],
]);
$tableGateway = new TableGateway('test', $adapter);
$rowset = $tableGateway->select('id = 0');
$this->assertNull($rowset->current());
$adapter->getDriver()->getConnection()->disconnect();
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Driver/Mysqli/ConnectionTest.php | test/integration/Adapter/Driver/Mysqli/ConnectionTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Driver\Mysqli;
use Laminas\Db\Adapter\Driver\Mysqli\Connection;
use PHPUnit\Framework\TestCase;
/**
* @group integration
* @group integration-mysqli
*/
class ConnectionTest extends TestCase
{
use TraitSetup;
public function testConnectionOk()
{
$connection = new Connection($this->variables);
$connection->connect();
self::assertTrue($connection->isConnected());
$connection->disconnect();
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Driver/Mysqli/TraitSetup.php | test/integration/Adapter/Driver/Mysqli/TraitSetup.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Driver\Mysqli;
use function extension_loaded;
use function getenv;
use function sprintf;
// phpcs:ignore WebimpressCodingStandard.NamingConventions.Trait.Suffix
trait TraitSetup
{
/** @var array<string, string> */
protected $variables = [
'hostname' => 'TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_HOSTNAME',
'username' => 'TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_USERNAME',
'password' => 'TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_PASSWORD',
'database' => 'TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_DATABASE',
];
/** @var array<string, string> */
protected $optional = [
'port' => 'TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_PORT',
];
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp(): void
{
if (! getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL')) {
$this->markTestSkipped('Mysqli integration test disabled');
}
if (! extension_loaded('mysqli')) {
$this->fail('The phpunit group integration-mysqli was enabled, but the extension is not loaded.');
}
foreach ($this->variables as $name => $value) {
if (! getenv($value)) {
$this->markTestSkipped(sprintf(
'Missing required variable %s from phpunit.xml for this integration test',
$value
));
}
$this->variables[$name] = getenv($value);
}
foreach ($this->optional as $name => $value) {
if (getenv($value)) {
$this->variables[$name] = getenv($value);
}
}
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Platform/SqliteTest.php | test/integration/Adapter/Platform/SqliteTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Platform;
use Laminas\Db\Adapter\Driver\Pdo;
use Laminas\Db\Adapter\Platform\Sqlite;
use PHPUnit\Framework\TestCase;
use function extension_loaded;
use function getenv;
/**
* @group integration
* @group integration-sqlite
*/
class SqliteTest extends TestCase
{
/** @var array<string, resource|\PDO> */
public $adapters = [];
protected function setUp(): void
{
if (! getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLITE_MEMORY')) {
$this->markTestSkipped(self::class . ' integration tests are not enabled!');
}
if (extension_loaded('pdo')) {
$this->adapters['pdo_sqlite'] = new \PDO(
'sqlite::memory:'
);
}
}
public function testQuoteValueWithPdoSqlite()
{
if (! $this->adapters['pdo_sqlite'] instanceof \PDO) {
$this->markTestSkipped('SQLite (PDO_SQLITE) not configured in unit test configuration file');
}
$sqlite = new Sqlite($this->adapters['pdo_sqlite']);
$value = $sqlite->quoteValue('value');
self::assertEquals('\'value\'', $value);
$sqlite = new Sqlite(new Pdo\Pdo(new Pdo\Connection($this->adapters['pdo_sqlite'])));
$value = $sqlite->quoteValue('value');
self::assertEquals('\'value\'', $value);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Platform/MysqlTest.php | test/integration/Adapter/Platform/MysqlTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Platform;
use Laminas\Db\Adapter\Driver\Mysqli;
use Laminas\Db\Adapter\Driver\Pdo;
use Laminas\Db\Adapter\Platform\Mysql;
use PHPUnit\Framework\TestCase;
use function extension_loaded;
use function getenv;
/**
* @group integration
* @group integration-mysql
*/
class MysqlTest extends TestCase
{
/** @var array<string, resource|\PDO> */
public $adapters = [];
protected function setUp(): void
{
if (! getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL')) {
$this->markTestSkipped(self::class . ' integration tests are not enabled!');
}
if (extension_loaded('mysqli')) {
$this->adapters['mysqli'] = new \mysqli(
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_HOSTNAME'),
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_USERNAME'),
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_PASSWORD'),
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_DATABASE')
);
}
if (extension_loaded('pdo')) {
$this->adapters['pdo_mysql'] = new \PDO(
'mysql:host=' . getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_HOSTNAME') . ';dbname='
. getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_DATABASE'),
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_USERNAME'),
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_PASSWORD')
);
}
}
public function testQuoteValueWithMysqli()
{
if (! $this->adapters['mysqli'] instanceof \Mysqli) {
$this->markTestSkipped('MySQL (Mysqli) not configured in unit test configuration file');
}
$mysql = new Mysql($this->adapters['mysqli']);
$value = $mysql->quoteValue('value');
self::assertEquals('\'value\'', $value);
$mysql = new Mysql(new Mysqli\Mysqli(new Mysqli\Connection($this->adapters['mysqli'])));
$value = $mysql->quoteValue('value');
self::assertEquals('\'value\'', $value);
}
public function testQuoteValueWithPdoMysql()
{
if (! $this->adapters['pdo_mysql'] instanceof \PDO) {
$this->markTestSkipped('MySQL (PDO_Mysql) not configured in unit test configuration file');
}
$mysql = new Mysql($this->adapters['pdo_mysql']);
$value = $mysql->quoteValue('value');
self::assertEquals('\'value\'', $value);
$mysql = new Mysql(new Pdo\Pdo(new Pdo\Connection($this->adapters['pdo_mysql'])));
$value = $mysql->quoteValue('value');
self::assertEquals('\'value\'', $value);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Platform/SqlServerTest.php | test/integration/Adapter/Platform/SqlServerTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Platform;
use Laminas\Db\Adapter\Platform\SqlServer;
use PDO;
use PHPUnit\Framework\TestCase;
use function extension_loaded;
use function getenv;
use function sqlsrv_connect;
use function sqlsrv_errors;
use function var_dump;
/**
* @group integration
* @group integration-sqlserver
*/
class SqlServerTest extends TestCase
{
/** @var array<string, resource> */
public $adapters = [];
protected function setUp(): void
{
if (! getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV')) {
$this->markTestSkipped(self::class . ' integration tests are not enabled!');
}
$database = getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_DATABASE');
$database = $database === false ? null : $database;
if (extension_loaded('sqlsrv')) {
$this->adapters['sqlsrv'] = sqlsrv_connect(
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_HOSTNAME'),
[
'UID' => getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_USERNAME'),
'PWD' => getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_PASSWORD'),
'Database' => $database,
'TrustServerCertificate' => 1,
]
);
if (! $this->adapters['sqlsrv']) {
var_dump(sqlsrv_errors());
exit;
}
}
if (extension_loaded('pdo') && extension_loaded('pdo_sqlsrv')) {
$this->adapters['pdo_sqlsrv'] = new PDO(
'sqlsrv:Server='
. getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_HOSTNAME')
. ';Database=' . ($database ?: '') . ';TrustServerCertificate=1',
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_USERNAME'),
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_PASSWORD')
);
}
}
public function testQuoteValueWithSqlServer()
{
if (! isset($this->adapters['pdo_sqlsrv'])) {
$this->markTestSkipped('SQLServer (pdo_sqlsrv) not configured in unit test configuration file');
}
$db = new SqlServer($this->adapters['pdo_sqlsrv']);
$value = $db->quoteValue('value');
self::assertEquals("'value'", $value);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Adapter/Platform/PostgresqlTest.php | test/integration/Adapter/Platform/PostgresqlTest.php | <?php
namespace LaminasIntegrationTest\Db\Adapter\Platform;
use Laminas\Db\Adapter\Driver\Pdo;
use Laminas\Db\Adapter\Driver\Pgsql;
use Laminas\Db\Adapter\Platform\Postgresql;
use PgSql\Connection as PgSqlConnection;
use PHPUnit\Framework\TestCase;
use function extension_loaded;
use function getenv;
use function is_resource;
use function pg_connect;
/**
* @group integration
* @group integration-postgres
*/
class PostgresqlTest extends TestCase
{
/** @var array<string, resource> */
public $adapters = [];
protected function setUp(): void
{
if (! getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL')) {
$this->markTestSkipped(self::class . ' integration tests are not enabled!');
}
if (extension_loaded('pgsql')) {
$this->adapters['pgsql'] = pg_connect(
'host=' . getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_HOSTNAME')
. ' dbname=' . getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_DATABASE')
. ' user=' . getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_USERNAME')
. ' password=' . getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_PASSWORD')
);
}
if (extension_loaded('pdo')) {
$this->adapters['pdo_pgsql'] = new \PDO(
'pgsql:host=' . getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_HOSTNAME') . ';dbname='
. getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_DATABASE'),
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_USERNAME'),
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_PASSWORD')
);
}
}
public function testQuoteValueWithPgsql()
{
if (
! isset($this->adapters['pgsql'])
|| (
! $this->adapters['pgsql'] instanceof PgSqlConnection
&& ! is_resource($this->adapters['pgsql'])
)
) {
$this->markTestSkipped('Postgres (pgsql) not configured in unit test configuration file');
}
$pgsql = new Postgresql($this->adapters['pgsql']);
$value = $pgsql->quoteValue('value');
self::assertEquals('\'value\'', $value);
$pgsql = new Postgresql(new Pgsql\Pgsql(new Pgsql\Connection($this->adapters['pgsql'])));
$value = $pgsql->quoteValue('value');
self::assertEquals('\'value\'', $value);
}
public function testQuoteValueWithPdoPgsql()
{
if (! isset($this->adapters['pdo_pgsql']) || ! $this->adapters['pdo_pgsql'] instanceof \PDO) {
$this->markTestSkipped('Postgres (PDO_PGSQL) not configured in unit test configuration file');
}
$pgsql = new Postgresql($this->adapters['pdo_pgsql']);
$value = $pgsql->quoteValue('value');
self::assertEquals('\'value\'', $value);
$pgsql = new Postgresql(new Pdo\Pdo(new Pdo\Connection($this->adapters['pdo_pgsql'])));
$value = $pgsql->quoteValue('value');
self::assertEquals('\'value\'', $value);
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Platform/MysqlFixtureLoader.php | test/integration/Platform/MysqlFixtureLoader.php | <?php
namespace LaminasIntegrationTest\Db\Platform;
use Exception;
use PDO;
use function file_get_contents;
use function getenv;
use function print_r;
use function sprintf;
class MysqlFixtureLoader implements FixtureLoader
{
/** @var string */
private $fixtureFile = __DIR__ . '/../TestFixtures/mysql.sql';
/** @var PDO */
private $pdo;
public function createDatabase()
{
$this->connect();
if (
false === $this->pdo->exec(sprintf(
"CREATE DATABASE IF NOT EXISTS %s",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_DATABASE')
))
) {
throw new Exception(sprintf(
"I cannot create the MySQL %s test database: %s",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_DATABASE'),
print_r($this->pdo->errorInfo(), true)
));
}
$this->pdo->exec('USE ' . getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_DATABASE'));
if (false === $this->pdo->exec(file_get_contents($this->fixtureFile))) {
throw new Exception(sprintf(
"I cannot create the table for %s database. Check the %s file. %s ",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_DATABASE'),
$this->fixtureFile,
print_r($this->pdo->errorInfo(), true)
));
}
$this->disconnect();
}
public function dropDatabase()
{
$this->connect();
$this->pdo->exec(sprintf(
"DROP DATABASE IF EXISTS %s",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_DATABASE')
));
$this->disconnect();
}
protected function connect()
{
$dsn = 'mysql:host=' . getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_HOSTNAME');
if (getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_PORT')) {
$dsn .= ';port=' . getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_PORT');
}
$this->pdo = new PDO(
$dsn,
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_USERNAME'),
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_MYSQL_PASSWORD')
);
}
protected function disconnect()
{
$this->pdo = null;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Platform/SqlServerFixtureLoader.php | test/integration/Platform/SqlServerFixtureLoader.php | <?php
namespace LaminasIntegrationTest\Db\Platform;
use Exception;
use function file_get_contents;
use function getenv;
use function print_r;
use function sprintf;
use function sqlsrv_connect;
use function sqlsrv_errors;
use function sqlsrv_query;
class SqlServerFixtureLoader implements FixtureLoader
{
/** @var string */
private $fixtureFilePrefix = __DIR__ . '/../TestFixtures/sqlsrv';
/** @var resource */
private $connection;
public function createDatabase(): void
{
$this->connect();
if (
false === sqlsrv_query($this->connection, sprintf(
<<<'SQL'
IF NOT EXISTS(SELECT * FROM sys.databases WHERE name = '%s')
BEGIN
CREATE DATABASE [%s]
END
SQL,
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_DATABASE'),
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_DATABASE')
))
) {
throw new Exception(sprintf(
"I cannot create the MSSQL %s database: %s",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_DATABASE'),
print_r(sqlsrv_errors(), true)
));
}
// phpcs:disable Squiz.PHP.NonExecutableCode.Unreachable
sqlsrv_query($this->connection, 'USE ' . getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_DATABASE'));
$fixtures = [
'tables' => $this->fixtureFilePrefix . '.sql',
'views' => $this->fixtureFilePrefix . '-views.sql',
'triggers' => $this->fixtureFilePrefix . '-triggers.sql',
];
foreach ($fixtures as $name => $fixtureFile) {
if (false === sqlsrv_query($this->connection, file_get_contents($fixtureFile))) {
throw new Exception(sprintf(
"I cannot create the %s for %s database. Check the %s file. %s ",
$name,
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_DATABASE'),
$fixtureFile,
print_r(sqlsrv_errors(), true)
));
}
}
$this->disconnect();
// phpcs:enable Squiz.PHP.NonExecutableCode.Unreachable
}
public function dropDatabase()
{
$this->connect();
sqlsrv_query($this->connection, "USE master");
sqlsrv_query($this->connection, sprintf(
"ALTER DATABASE %s SET SINGLE_USER WITH ROLLBACK IMMEDIATE",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_DATABASE')
));
if (
false === sqlsrv_query($this->connection, sprintf(
"DROP DATABASE %s",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_DATABASE')
))
) {
throw new Exception(sprintf(
"Unable to drop database %s. %s",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_DATABASE'),
print_r(sqlsrv_errors(), true)
));
}
$this->disconnect();
}
protected function connect()
{
$this->connection = sqlsrv_connect(
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_HOSTNAME'),
[
'UID' => getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_USERNAME'),
'PWD' => getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_PASSWORD'),
'TrustServerCertificate' => 1,
]
);
if (false === $this->connection) {
throw new Exception(sprintf(
"Unable to connect %s. %s",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_SQLSRV_DATABASE'),
print_r(sqlsrv_errors(), true)
));
}
}
protected function disconnect()
{
$this->connection = null;
}
}
| php | BSD-3-Clause | 1395efe76f7a20c322e78d1885efe103e5e291ff | 2026-01-05T05:03:07.882669Z | false |
laminas/laminas-db | https://github.com/laminas/laminas-db/blob/1395efe76f7a20c322e78d1885efe103e5e291ff/test/integration/Platform/PgsqlFixtureLoader.php | test/integration/Platform/PgsqlFixtureLoader.php | <?php
namespace LaminasIntegrationTest\Db\Platform;
use Exception;
use PDO;
use function file_get_contents;
use function getenv;
use function print_r;
use function sprintf;
class PgsqlFixtureLoader implements FixtureLoader
{
/** @var string */
private $fixtureFile = __DIR__ . '/../TestFixtures/pgsql.sql';
/** @var PDO */
private $pdo;
/** @var bool */
private $initialRun = true;
public function createDatabase()
{
$this->connect();
$this->dropDatabase(); // closes connection
$this->connect();
if (
false === $this->pdo->exec(sprintf(
"CREATE DATABASE %s",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_DATABASE')
))
) {
throw new Exception(sprintf(
"I cannot create the PostgreSQL %s test database: %s",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_DATABASE'),
print_r($this->pdo->errorInfo(), true)
));
}
// PostgreSQL cannot switch database on same connection.
$this->disconnect();
$this->connect(true);
if (false === $this->pdo->exec(file_get_contents($this->fixtureFile))) {
throw new Exception(sprintf(
"I cannot create the table for %s database. Check the %s file. %s ",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_DATABASE'),
$this->fixtureFile,
print_r($this->pdo->errorInfo(), true)
));
}
$this->disconnect();
}
public function dropDatabase()
{
if (! $this->initialRun) {
// Not possible to drop in PostgreSQL.
// Connection is locking the database and trying to close it with unset()
// does not trigger garbage collector on time to actually close it to free the lock.
return;
}
$this->initialRun = false;
$this->connect();
$this->pdo->exec(sprintf(
"DROP DATABASE IF EXISTS %s",
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_DATABASE')
));
$this->disconnect();
}
/**
* @param bool $useDb add dbname using in dsn
*/
protected function connect($useDb = false)
{
$dsn = 'pgsql:host=' . getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_HOSTNAME');
if ($useDb) {
$dsn .= ';dbname=' . getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_DATABASE');
}
$this->pdo = new PDO(
$dsn,
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_USERNAME'),
getenv('TESTS_LAMINAS_DB_ADAPTER_DRIVER_PGSQL_PASSWORD')
);
}
protected function disconnect()
{
$this->pdo = null;
}
}
| 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.