Db\Adapter\AbstractAdapter
AbstractSource on GitHubBase class for Phalcon\Db\Adapter adapters.
This class and its related classes provide a simple SQL database interface for Phalcon Framework. The Phalcon\Db is the basic class you use to connect your PHP application to an RDBMS. There is a different adapter class for each brand of RDBMS.
This component is intended to lower level database operations. If you want to interact with databases using higher level of abstraction use Phalcon\Mvc\Model.
Phalcon\Db\AbstractDb is an abstract class. You only can use it with a database adapter like Phalcon\Db\Adapter\Pdo
use Phalcon\Db;
use Phalcon\Db\Exception;
use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection;
try {
$connection = new MysqlConnection(
[
"host" => "192.168.0.11",
"username" => "sigma",
"password" => "secret",
"dbname" => "blog",
"port" => "3306",
]
);
$result = $connection->query(
"SELECT * FROM co_invoices LIMIT 5"
);
$result->setFetchMode(Enum::FETCH_NUM);
while ($invoice = $result->fetch()) {
print_r($invoice);
}
} catch (Exception $e) {
echo $e->getMessage(), PHP_EOL;
}Phalcon\Db\Adapter\AbstractAdapter- implementsPhalcon\Db\Adapter\AdapterInterface,Phalcon\Events\EventsAwareInterface
Uses Phalcon\Db\CheckInterface · Phalcon\Db\ColumnInterface · Phalcon\Db\DialectInterface · Phalcon\Db\Enum · Phalcon\Db\Exception · Phalcon\Db\Exceptions\CannotInsertWithoutData · Phalcon\Db\Exceptions\IncompleteBindTypes · Phalcon\Db\Exceptions\InvalidDialectClass · Phalcon\Db\Exceptions\InvalidWhereConditions · Phalcon\Db\Exceptions\NestedTransactionChangeBlocked · Phalcon\Db\Exceptions\SavepointsNotSupported · Phalcon\Db\Exceptions\TableMustHaveColumn · Phalcon\Db\Exceptions\UpdateFieldCountMismatch · Phalcon\Db\Index · Phalcon\Db\IndexInterface · Phalcon\Db\RawValue · Phalcon\Db\Reference · Phalcon\Db\ReferenceInterface · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface · Phalcon\Support\Settings
Method Summary
public__construct( array$descriptor )Phalcon\Db\Adapter constructorpublicbooladdCheck(string$tableName,string$schemaName,CheckInterface$check)Adds a CHECK constraint to a table. MySQL 8.0.16+ and PostgreSQLpublicbooladdColumn(string$tableName,string$schemaName,ColumnInterface$column)Adds a column to a tablepublicbooladdForeignKey(string$tableName,string$schemaName,ReferenceInterface$reference)Adds a foreign key to a tablepublicbooladdIndex(string$tableName,string$schemaName,IndexInterface$index)Adds an index to a tablepublicbooladdPrimaryKey(string$tableName,string$schemaName,IndexInterface$index)Adds a primary key to a tablepublicboolcreateMaterializedView(string$viewName,array$definition,string|null$schemaName = null)Creates a materialized view (PostgreSQL only - MySQL and SQLitepublicboolcreateSavepoint( string$name )Creates a new savepointpublicboolcreateTable(string$tableName,string$schemaName,array$definition)Creates a tablepublicboolcreateView(string$viewName,array$definition,string|null$schemaName = null)Creates a viewpublicbooldelete(mixed$table,string|null$whereCondition = null,array$placeholders = [],array$dataTypes = [])Deletes data from a table using custom RBDM SQL syntaxpublicIndexInterface[]describeIndexes(string$table,string|null$schema = null)Lists table indexespublicReferenceInterface[]describeReferences(string$table,string|null$schema = null)Lists table referencespublicbooldropCheck(string$tableName,string$schemaName,string$checkName)Drops a CHECK constraint from a table. SQLite throws.publicbooldropColumn(string$tableName,string$schemaName,string$columnName)Drops a column from a tablepublicbooldropForeignKey(string$tableName,string$schemaName,string$referenceName)Drops a foreign key from a tablepublicbooldropIndex(string$tableName,string$schemaName,mixed$indexName)Drop an index from a tablepublicbooldropMaterializedView(string$viewName,string|null$schemaName = null,bool$ifExists = true)Drops a materialized view (PostgreSQL only).publicbooldropPrimaryKey(string$tableName,string$schemaName)Drops a table's primary keypublicbooldropTable(string$tableName,string|null$schemaName = null,bool$ifExists = true)Drops a table from a schema/databasepublicbooldropView(string$viewName,string|null$schemaName = null,bool$ifExists = true)Drops a viewpublicstringescapeIdentifier( mixed$identifier )Escapes a column/table/schema namepublicarrayfetchAll(string$sqlQuery,int$fetchMode = Enum::FETCH_ASSOC,array$bindParams = [],array$bindTypes = [])Dumps the complete result of a query into an arraypublicstring|boolfetchColumn(string$sqlQuery,array$placeholders = [],mixed$column = 0)Returns the n'th field of first row in a SQL query resultpublicarrayfetchOne(string$sqlQuery,mixed$fetchMode = Enum::FETCH_ASSOC,array$bindParams = [],array$bindTypes = [])Returns the first row in a SQL query resultpublicstringforUpdate(string$sqlQuery,string$modifier = "")Returns a SQL modified with a FOR UPDATE clause. The optionalpublicstringgetColumnDefinition( ColumnInterface$column )Returns the SQL column definition from a columnpublicstringgetColumnList( mixed$columnList )Gets a list of columnspublicintgetConnectionId()Gets the active connection unique identifierpublicRawValuegetDefaultIdValue()Returns the default identity value to be inserted in an identity columnpublicRawValuegetDefaultValue()Returns the default value to make the RBDM use the default value declaredpublicarraygetDescriptor()Return descriptor used to connect to the active databasepublicDialectInterfacegetDialect()Returns internal dialect instancepublicstringgetDialectType()Name of the dialect usedpublicManagerInterface|nullgetEventsManager()Returns the internal event managerpublicstringgetNestedTransactionSavepointName()Returns the savepoint name to use for nested transactionspublicstringgetRealSQLStatement()Active SQL statement in the object without replace bound parameterspublicarraygetSQLBindTypes()Active SQL statement in the objectpublicstringgetSQLStatement()Active SQL statement in the objectpublicarraygetSQLVariables()Active SQL variables in the objectpublicstringgetType()Type of database system the adapter is used forpublicboolinsert(string$table,array$values,mixed$fields = null,mixed$dataTypes = null)Inserts data into a table using custom RDBMS SQL syntaxpublicboolinsertAsDict(string$table,mixed$data,mixed$dataTypes = null)Inserts data into a table using custom RBDM SQL syntaxpublicboolisNestedTransactionsWithSavepoints()Returns if nested transactions should use savepointspublicstringlimit(string$sqlQuery,mixed$number)Appends a LIMIT clause to $sqlQuery argumentpublicarraylistTables( string|null$schemaName = null )List all tables on a databasepublicarraylistViews( string|null$schemaName = null )List all views on a databasepublicboolmodifyColumn(string$tableName,string$schemaName,ColumnInterface$column,ColumnInterface|null$currentColumn = null)Modifies a table column based on a definitionpublicstringonConflictUpdate(string$sqlQuery,array$conflictColumns,array$updateColumns)Appends an ON CONFLICT (…) DO UPDATE SET col = excluded.colpublicboolrefreshMaterializedView(string$viewName,string|null$schemaName = null,bool$concurrent = false)Refreshes a materialized view (PostgreSQL only). PasspublicboolreleaseSavepoint( string$name )Releases given savepointpublicstringreturning(string$sqlQuery,array$columns)Appends a RETURNING clause to an INSERT/UPDATE/DELETE SQL statementpublicboolrollbackSavepoint( string$name )Rollbacks given savepointpublicsetDialect( DialectInterface$dialect )Sets the dialect used to produce the SQLpublicvoidsetEventsManager( ManagerInterface$eventsManager )Sets the event managerpublicAdapterInterfacesetNestedTransactionsWithSavepoints( bool$nestedTransactionsWithSavepoints )Set if nested transactions should use savepointspublicvoidsetup( array$options )Enables/disables options in the Database component.publicstringsharedLock(string$sqlQuery,string$modifier = "")Returns a SQL modified with a shared-lock clause. The optionalpublicboolsupportSequences()Check whether the database system requires a sequence to producepublicboolsupportsDefaultValue()Check whether the database system support the DEFAULTpublicbooltableExists(string$tableName,string|null$schemaName = null)Generates SQL checking for the existence of a schema.tablepublicarraytableOptions(string$tableName,string|null$schemaName = null)Gets creation options from a tablepublicboolupdate(string$table,mixed$fields,mixed$values,mixed$whereCondition = null,mixed$dataTypes = null)Updates data on a table using custom RBDM SQL syntaxpublicboolupdateAsDict(string$table,mixed$data,mixed$whereCondition = null,mixed$dataTypes = null)Updates data on a table using custom RBDM SQL syntaxpublicbooluseExplicitIdValue()Check whether the database system requires an explicit value for identitypublicboolviewExists(string$viewName,string|null$schemaName = null)Generates SQL checking for the existence of a schema.viewProperties
protectedint$connectionConsecutive = 0Connection IDprotectedint$connectionIdActive connection IDprotectedarray$descriptor = []Descriptor used to connect to a databaseprotectedDialectInterface$dialectDialect instanceprotectedstring$dialectTypeName of the dialect usedprotectedManagerInterface|null$eventsManager = nullEvent Managerprotectedstring$realSqlStatementThe real SQL statement - what was executedprotectedarray$sqlBindTypes = []Active SQL Bind Typesprotectedstring$sqlStatementActive SQL Statementprotectedarray$sqlVariables = []Active SQL bound parameter variablesprotectedint$transactionLevel = 0Current transaction levelprotectedbool$transactionsWithSavepoints = falseWhether the database supports transactions with save pointsprotectedstring$typeType of database system the adapter is used forMethods
__construct()
public function __construct( array $descriptor );Phalcon\Db\Adapter constructor
Note: the options key is forwarded to the static setup() method,
which writes process-global settings affecting every connection in the
process. See setup().
addCheck()
public function addCheck(
string $tableName,
string $schemaName,
CheckInterface $check
): bool;Adds a CHECK constraint to a table. MySQL 8.0.16+ and PostgreSQL
issue ALTER TABLE ... ADD CONSTRAINT ... CHECK (...); SQLite throws.
addColumn()
public function addColumn(
string $tableName,
string $schemaName,
ColumnInterface $column
): bool;Adds a column to a table
addForeignKey()
public function addForeignKey(
string $tableName,
string $schemaName,
ReferenceInterface $reference
): bool;Adds a foreign key to a table
addIndex()
public function addIndex(
string $tableName,
string $schemaName,
IndexInterface $index
): bool;Adds an index to a table
addPrimaryKey()
public function addPrimaryKey(
string $tableName,
string $schemaName,
IndexInterface $index
): bool;Adds a primary key to a table
createMaterializedView()
public function createMaterializedView(
string $viewName,
array $definition,
string|null $schemaName = null
): bool;Creates a materialized view (PostgreSQL only - MySQL and SQLite throw via the dialect).
createSavepoint()
public function createSavepoint( string $name ): bool;Creates a new savepoint
createTable()
public function createTable(
string $tableName,
string $schemaName,
array $definition
): bool;Creates a table
createView()
public function createView(
string $viewName,
array $definition,
string|null $schemaName = null
): bool;Creates a view
delete()
public function delete(
mixed $table,
string|null $whereCondition = null,
array $placeholders = [],
array $dataTypes = []
): bool;Deletes data from a table using custom RBDM SQL syntax
// Deleting existing invoice
$success = $connection->delete(
"co_invoices",
"inv_id = 101"
);
// Next SQL sentence is generated
DELETE FROM `co_invoices` WHERE `inv_id` = 101Warning! If $whereCondition is string it not escaped.
describeIndexes()
public function describeIndexes(
string $table,
string|null $schema = null
): IndexInterface[];Lists table indexes
print_r(
$connection->describeIndexes("co_orders_x_products")
);This base implementation consumes the dialect’s describeIndexes() SQL
as FETCH_NUM rows by position: column index 2 is the index key name and
column index 4 is the indexed column name. A custom dialect’s
describeIndexes() SQL must emit columns in that order, or a custom
adapter must override this method. All bundled adapters except PostgreSQL
override it.
describeReferences()
public function describeReferences(
string $table,
string|null $schema = null
): ReferenceInterface[];Lists table references
print_r(
$connection->describeReferences("co_orders_x_products")
);This base implementation consumes the dialect’s describeReferences()
SQL as FETCH_NUM rows by position: index 1 is the local column, index 2
the constraint name, index 3 the referenced schema, index 4 the
referenced table, and index 5 the referenced column. A custom dialect’s
describeReferences() SQL must emit columns in that order, or a custom
adapter must override this method. Every bundled adapter (MySQL,
PostgreSQL, SQLite) overrides it, so this base implementation has no
in-tree caller and effectively assumes the PostgreSQL row shape.
dropCheck()
public function dropCheck(
string $tableName,
string $schemaName,
string $checkName
): bool;Drops a CHECK constraint from a table. SQLite throws.
dropColumn()
public function dropColumn(
string $tableName,
string $schemaName,
string $columnName
): bool;Drops a column from a table
dropForeignKey()
public function dropForeignKey(
string $tableName,
string $schemaName,
string $referenceName
): bool;Drops a foreign key from a table
dropIndex()
public function dropIndex(
string $tableName,
string $schemaName,
mixed $indexName
): bool;Drop an index from a table
dropMaterializedView()
public function dropMaterializedView(
string $viewName,
string|null $schemaName = null,
bool $ifExists = true
): bool;Drops a materialized view (PostgreSQL only).
dropPrimaryKey()
public function dropPrimaryKey(
string $tableName,
string $schemaName
): bool;Drops a table’s primary key
dropTable()
public function dropTable(
string $tableName,
string|null $schemaName = null,
bool $ifExists = true
): bool;Drops a table from a schema/database
dropView()
public function dropView(
string $viewName,
string|null $schemaName = null,
bool $ifExists = true
): bool;Drops a view
escapeIdentifier()
public function escapeIdentifier( mixed $identifier ): string;Escapes a column/table/schema name
$escapedTable = $connection->escapeIdentifier(
"co_invoices"
);
$escapedTable = $connection->escapeIdentifier(
[
"store",
"co_invoices",
]
);fetchAll()
public function fetchAll(
string $sqlQuery,
int $fetchMode = Enum::FETCH_ASSOC,
array $bindParams = [],
array $bindTypes = []
): array;Dumps the complete result of a query into an array
// Getting all invoices with associative indexes only
$invoices = $connection->fetchAll(
"SELECT * FROM co_invoices",
\Phalcon\Db\Enum::FETCH_ASSOC
);
foreach ($invoices as $invoice) {
print_r($invoice);
}
// Getting all invoices whose title contains the word "Test"
$invoices = $connection->fetchAll(
"SELECT * FROM co_invoices WHERE inv_title LIKE :inv_title",
\Phalcon\Db\Enum::FETCH_ASSOC,
[
"inv_title" => "%Test%",
]
);
foreach($invoices as $invoice) {
print_r($invoice);
}fetchColumn()
public function fetchColumn(
string $sqlQuery,
array $placeholders = [],
mixed $column = 0
): string|bool;Returns the n’th field of first row in a SQL query result
// Getting count of invoices
$invoicesCount = $connection->fetchColumn("SELECT count(*) FROM co_invoices");
print_r($invoicesCount);
// Getting the title of the last created invoice
$invoice = $connection->fetchColumn(
"SELECT inv_id, inv_title FROM co_invoices ORDER BY inv_created_at DESC",
1
);
print_r($invoice);fetchOne()
public function fetchOne(
string $sqlQuery,
mixed $fetchMode = Enum::FETCH_ASSOC,
array $bindParams = [],
array $bindTypes = []
): array;Returns the first row in a SQL query result
// Getting first invoice
$invoice = $connection->fetchOne("SELECT * FROM co_invoices");
print_r($invoice);
// Getting first invoice with associative indexes only
$invoice = $connection->fetchOne(
"SELECT * FROM co_invoices",
\Phalcon\Db\Enum::FETCH_ASSOC
);
print_r($invoice);forUpdate()
public function forUpdate(
string $sqlQuery,
string $modifier = ""
): string;Returns a SQL modified with a FOR UPDATE clause. The optional
modifier is passed straight to the dialect (use Dialect::LOCK_NOWAIT
/ Dialect::LOCK_SKIP_LOCKED / Dialect::LOCK_NONE).
getColumnDefinition()
public function getColumnDefinition( ColumnInterface $column ): string;Returns the SQL column definition from a column
getColumnList()
public function getColumnList( mixed $columnList ): string;Gets a list of columns
getConnectionId()
public function getConnectionId(): int;Gets the active connection unique identifier
getDefaultIdValue()
public function getDefaultIdValue(): RawValue;Returns the default identity value to be inserted in an identity column
// Inserting a new invoice with a valid default value for the column 'inv_id'
$success = $connection->insert(
"co_invoices",
[
$connection->getDefaultIdValue(),
"Test Invoice",
100,
],
[
"inv_id",
"inv_title",
"inv_total",
]
);getDefaultValue()
public function getDefaultValue(): RawValue;Returns the default value to make the RBDM use the default value declared in the table definition
// Inserting a new invoice with a valid default value for the column 'inv_total'
$success = $connection->insert(
"co_invoices",
[
"Test Invoice",
$connection->getDefaultValue()
],
[
"inv_title",
"inv_total",
]
);@todo Return NULL if this is not supported by the adapter
getDescriptor()
public function getDescriptor(): array;Return descriptor used to connect to the active database
getDialect()
public function getDialect(): DialectInterface;Returns internal dialect instance
getDialectType()
public function getDialectType(): string;Name of the dialect used
getEventsManager()
public function getEventsManager(): ManagerInterface|null;Returns the internal event manager
getNestedTransactionSavepointName()
public function getNestedTransactionSavepointName(): string;Returns the savepoint name to use for nested transactions
getRealSQLStatement()
public function getRealSQLStatement(): string;Active SQL statement in the object without replace bound parameters
getSQLBindTypes()
public function getSQLBindTypes(): array;Active SQL statement in the object
getSQLStatement()
public function getSQLStatement(): string;Active SQL statement in the object
getSQLVariables()
public function getSQLVariables(): array;Active SQL variables in the object
getType()
public function getType(): string;Type of database system the adapter is used for
insert()
public function insert(
string $table,
array $values,
mixed $fields = null,
mixed $dataTypes = null
): bool;Inserts data into a table using custom RDBMS SQL syntax
// Inserting a new invoice
$success = $connection->insert(
"co_invoices",
["Test Invoice", 100],
["inv_title", "inv_total"]
);
// Next SQL sentence is sent to the database system
INSERT INTO `co_invoices` (`inv_title`, `inv_total`) VALUES ("Test Invoice", 100);insertAsDict()
public function insertAsDict(
string $table,
mixed $data,
mixed $dataTypes = null
): bool;Inserts data into a table using custom RBDM SQL syntax
// Inserting a new invoice
$success = $connection->insertAsDict(
"co_invoices",
[
"inv_title" => "Test Invoice",
"inv_total" => 100,
]
);
// Next SQL sentence is sent to the database system
INSERT INTO `co_invoices` (`inv_title`, `inv_total`) VALUES ("Test Invoice", 100);isNestedTransactionsWithSavepoints()
public function isNestedTransactionsWithSavepoints(): bool;Returns if nested transactions should use savepoints
limit()
public function limit(
string $sqlQuery,
mixed $number
): string;Appends a LIMIT clause to $sqlQuery argument
echo $connection->limit("SELECT * FROM co_invoices", 5);listTables()
public function listTables( string|null $schemaName = null ): array;List all tables on a database
print_r(
$connection->listTables("blog")
);listViews()
public function listViews( string|null $schemaName = null ): array;List all views on a database
print_r(
$connection->listViews("blog")
);modifyColumn()
public function modifyColumn(
string $tableName,
string $schemaName,
ColumnInterface $column,
ColumnInterface|null $currentColumn = null
): bool;Modifies a table column based on a definition
onConflictUpdate()
public function onConflictUpdate(
string $sqlQuery,
array $conflictColumns,
array $updateColumns
): string;Appends an ON CONFLICT (...) DO UPDATE SET col = excluded.col
upsert clause to the supplied INSERT statement. Supported by
PostgreSQL and SQLite 3.24+; MySQL throws.
refreshMaterializedView()
public function refreshMaterializedView(
string $viewName,
string|null $schemaName = null,
bool $concurrent = false
): bool;Refreshes a materialized view (PostgreSQL only). Pass
concurrent = true for non-blocking refresh.
releaseSavepoint()
public function releaseSavepoint( string $name ): bool;Releases given savepoint
returning()
public function returning(
string $sqlQuery,
array $columns
): string;Appends a RETURNING clause to an INSERT/UPDATE/DELETE SQL statement
and returns the modified SQL. Supported by PostgreSQL and SQLite 3.35+;
MySQL throws (no RETURNING construct). Pass ["*"] for RETURNING *.
rollbackSavepoint()
public function rollbackSavepoint( string $name ): bool;Rollbacks given savepoint
setDialect()
public function setDialect( DialectInterface $dialect );Sets the dialect used to produce the SQL
setEventsManager()
public function setEventsManager( ManagerInterface $eventsManager ): void;Sets the event manager
setNestedTransactionsWithSavepoints()
public function setNestedTransactionsWithSavepoints( bool $nestedTransactionsWithSavepoints ): AdapterInterface;Set if nested transactions should use savepoints
setup()
public static function setup( array $options ): void;Enables/disables options in the Database component.
The flags are stored as process-global Phalcon\Support\Settings
(db.escape_identifiers, db.force_casting) and therefore affect every
connection in the process at once, last-writer-wins. Call this once at
bootstrap; it is not per-connection configuration. Because the
constructor calls setup() whenever a descriptor carries an options
key, constructing one adapter with options can change the SQL another,
already-configured connection generates.
sharedLock()
public function sharedLock(
string $sqlQuery,
string $modifier = ""
): string;Returns a SQL modified with a shared-lock clause. The optional
modifier is passed straight to the dialect (use
Dialect::LOCK_NOWAIT / Dialect::LOCK_SKIP_LOCKED for PostgreSQL).
supportSequences()
public function supportSequences(): bool;Check whether the database system requires a sequence to produce auto-numeric values
supportsDefaultValue()
public function supportsDefaultValue(): bool;Check whether the database system support the DEFAULT keyword (SQLite does not support it)
tableExists()
public function tableExists(
string $tableName,
string|null $schemaName = null
): bool;Generates SQL checking for the existence of a schema.table
var_dump(
$connection->tableExists("blog", "posts")
);tableOptions()
public function tableOptions(
string $tableName,
string|null $schemaName = null
): array;Gets creation options from a table
print_r(
$connection->tableOptions("co_invoices")
);update()
public function update(
string $table,
mixed $fields,
mixed $values,
mixed $whereCondition = null,
mixed $dataTypes = null
): bool;Updates data on a table using custom RBDM SQL syntax
// Updating existing invoice
$success = $connection->update(
"co_invoices",
["inv_title"],
["New Test Invoice"],
"inv_id = 101"
);
// Next SQL sentence is sent to the database system
UPDATE `co_invoices` SET `inv_title` = "New Test Invoice" WHERE inv_id = 101
// Updating existing invoice with array condition and $dataTypes
$success = $connection->update(
"co_invoices",
["inv_title"],
["New Test Invoice"],
[
"conditions" => "inv_id = ?",
"bind" => [$some_unsafe_id],
"bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param
],
[
PDO::PARAM_STR
]
);Warning! If $whereCondition is string it not escaped.
updateAsDict()
public function updateAsDict(
string $table,
mixed $data,
mixed $whereCondition = null,
mixed $dataTypes = null
): bool;Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax
// Updating existing invoice
$success = $connection->updateAsDict(
"co_invoices",
[
"inv_title" => "New Test Invoice",
],
"inv_id = 101"
);
// Next SQL sentence is sent to the database system
UPDATE `co_invoices` SET `inv_title` = "New Test Invoice" WHERE inv_id = 101useExplicitIdValue()
public function useExplicitIdValue(): bool;Check whether the database system requires an explicit value for identity columns
viewExists()
public function viewExists(
string $viewName,
string|null $schemaName = null
): bool;Generates SQL checking for the existence of a schema.view
var_dump(
$connection->viewExists("active_users", "posts")
);Db\Adapter\AdapterInterface
InterfaceSource on GitHubPhalcon\Db\Adapter\AdapterInterface
Phalcon\Contracts\Db\Adapter\AdapterPhalcon\Db\Adapter\AdapterInterface
Uses Phalcon\Contracts\Db\Adapter\Adapter
Db\Adapter\PdoFactory
ClassSource on GitHubPhalcon\Factory\AbstractConfigFactoryPhalcon\Factory\AbstractFactoryPhalcon\Db\Adapter\PdoFactory
Uses Phalcon\Db\Adapter\Pdo\Mysql · Phalcon\Db\Adapter\Pdo\Postgresql · Phalcon\Db\Adapter\Pdo\Sqlite · Phalcon\Db\Exception · Phalcon\Factory\AbstractFactory · Phalcon\Traits\Support\Helper\Arr\GetTrait
Method Summary
public__construct( array$services = [] )ConstructorpublicAdapterInterfaceload( mixed$config )Factory to create an instance from a Config objectpublicAdapterInterfacenewInstance(string$name,array$options = [])Create a new instance of the adapterprotectedstringgetExceptionClass()protectedarraygetServices()Returns the available adaptersMethods
__construct()
public function __construct( array $services = [] );Constructor
load()
public function load( mixed $config ): AdapterInterface;Factory to create an instance from a Config object
newInstance()
public function newInstance(
string $name,
array $options = []
): AdapterInterface;Create a new instance of the adapter
getExceptionClass()
protected function getExceptionClass(): string;getServices()
protected function getServices(): array;Returns the available adapters
Db\Adapter\Pdo\AbstractPdo
AbstractSource on GitHubPhalcon\Db\Adapter\Pdo is the Phalcon\Db that internally uses PDO to connect to a database
use Phalcon\Db\Adapter\Pdo\Mysql;
$config = [
"host" => "localhost",
"dbname" => "blog",
"port" => 3306,
"username" => "sigma",
"password" => "secret",
];
$connection = new Mysql($config);Phalcon\Db\Adapter\AbstractAdapterPhalcon\Db\Adapter\Pdo\AbstractPdo
Uses Phalcon\Db\Adapter\AbstractAdapter · Phalcon\Db\Column · Phalcon\Db\Exception · Phalcon\Db\Exceptions\CannotPrepareStatement · Phalcon\Db\Exceptions\InvalidBindParameter · Phalcon\Db\Exceptions\MatchedParameterNotFound · Phalcon\Db\Exceptions\NoActiveTransaction · Phalcon\Db\ResultInterface · Phalcon\Db\Result\PdoResult · Phalcon\Events\ManagerInterface · Phalcon\Support\Settings
Method Summary
public__construct( array$descriptor )Constructor for Phalcon\Db\Adapter\PdopublicintaffectedRows()Returns the number of affected rows by the latest INSERT/UPDATE/DELETEpublicboolbegin( bool$nesting = true )Starts a transaction in the connectionpublicvoidclose()Closes the active connection returning success. Phalcon automaticallypublicboolcommit( bool$nesting = true )Commits the active transaction in the connectionpublicvoidconnect( array$descriptor = [] )This method is automatically called in \Phalcon\Db\Adapter\PdopublicarrayconvertBoundParams(string$sql,array$params = [])Converts bound parameters such as :name: or ?1 into PDO bind params ?publicvoidensureConnection()Ensures the connection is alive, reconnecting in place if it is not.publicstringescapeString( string$str )Escapes a value to avoid SQL injections according to the active charsetpublicboolexecute(string$sqlStatement,array$bindParams = [],array$bindTypes = [])Sends SQL statements to the database server returning the success state.public\PDOStatementexecutePrepared(\PDOStatement$statement,array$placeholders,array$dataTypes = [])Executes a prepared statement binding. This function uses integer indexespublicboolgetAutoReconnect()Returns whether transparent auto-reconnect is enabled.publicarraygetErrorInfo()Return the error info, if anypublicmixedgetInternalHandler()Return internal PDO handlerpublicintgetTransactionLevel()Returns the current transaction nesting levelpublicboolisUnderTransaction()Checks whether the connection is under a transactionpublicstring|boollastInsertId( string|null$name = null )Returns the insert id for the auto_increment/serial column inserted inpublicboolping()Checks whether the underlying connection is still alive by issuing apublic\PDOStatementprepare( string$sqlStatement )Returns a PDO prepared statement to be executed with 'executePrepared'publicResultInterface|boolquery(string$sqlStatement,array$bindParams = [],array$bindTypes = [])Sends SQL statements to the database server returning the success state.publicboolrollback( bool$nesting = true )Rollbacks the active transaction in the connectionpublicstaticsetAutoReconnect( bool$autoReconnect )Enables or disables transparent auto-reconnect on a lost connection.protectedarraygetDsnDefaults()Returns PDO adapter DSN defaults as a key-value map.protectedboolisConnectionError( \Throwable$exception )Recognizes whether an exception represents a lost ("gone away")protectedvoidprepareRealSql(string$statement,array$parameters)Constructs the SQL statement (with parameters)Constants
stringBIND_PATTERN = "/\?([0-9]+)|:([a-zA-Z0-9_]+):/"Properties
protectedint$affectedRows = 0Last affected rowsprotectedbool$autoReconnect = falseWhether to transparently reconnect and retry once when a query fails because the connection was lost. Opt-in; off by default.protected\PDO$pdoPDO HandlerMethods
__construct()
public function __construct( array $descriptor );Constructor for Phalcon\Db\Adapter\Pdo
affectedRows()
public function affectedRows(): int;Returns the number of affected rows by the latest INSERT/UPDATE/DELETE executed in the database system
$connection->execute(
"DELETE FROM co_invoices"
);
echo $connection->affectedRows(), " were deleted";begin()
public function begin( bool $nesting = true ): bool;Starts a transaction in the connection
close()
public function close(): void;Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends
commit()
public function commit( bool $nesting = true ): bool;Commits the active transaction in the connection
connect()
public function connect( array $descriptor = [] ): void;This method is automatically called in \Phalcon\Db\Adapter\Pdo constructor.
Call it when you need to restore a database connection.
use Phalcon\Db\Adapter\Pdo\Mysql;
// Make a connection
$connection = new Mysql(
[
"host" => "localhost",
"username" => "sigma",
"password" => "secret",
"dbname" => "blog",
"port" => 3306,
]
);
// Reconnect
$connection->connect();convertBoundParams()
public function convertBoundParams(
string $sql,
array $params = []
): array;Converts bound parameters such as :name: or ?1 into PDO bind params ?
print_r(
$connection->convertBoundParams(
"SELECT * FROM co_invoices WHERE inv_title = :inv_title:",
[
"Test Invoice",
]
)
);ensureConnection()
public function ensureConnection(): void;Ensures the connection is alive, reconnecting in place if it is not.
escapeString()
public function escapeString( string $str ): string;Escapes a value to avoid SQL injections according to the active charset in the connection
$escapedStr = $connection->escapeString("some dangerous value");execute()
public function execute(
string $sqlStatement,
array $bindParams = [],
array $bindTypes = []
): bool;Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server does not return any rows
// Inserting data
$success = $connection->execute(
"INSERT INTO co_invoices VALUES (1, 'Test Invoice')"
);
$success = $connection->execute(
"INSERT INTO co_invoices VALUES (?, ?)",
[
1,
"Test Invoice",
]
);executePrepared()
public function executePrepared(
\PDOStatement $statement,
array $placeholders,
array $dataTypes = []
): \PDOStatement;Executes a prepared statement binding. This function uses integer indexes starting from zero
use Phalcon\Db\Column;
$statement = $db->prepare(
"SELECT * FROM co_invoices WHERE inv_title = :inv_title"
);
$result = $connection->executePrepared(
$statement,
[
"inv_title" => "Test Invoice",
],
[
"inv_title" => Column::BIND_PARAM_STR,
]
);getAutoReconnect()
public function getAutoReconnect(): bool;Returns whether transparent auto-reconnect is enabled.
getErrorInfo()
public function getErrorInfo(): array;Return the error info, if any
getInternalHandler()
public function getInternalHandler(): mixed;Return internal PDO handler
getTransactionLevel()
public function getTransactionLevel(): int;Returns the current transaction nesting level
isUnderTransaction()
public function isUnderTransaction(): bool;Checks whether the connection is under a transaction
$connection->begin();
// true
var_dump(
$connection->isUnderTransaction()
);lastInsertId()
public function lastInsertId( string|null $name = null ): string|bool;Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement
// Inserting a new invoice
$success = $connection->insert(
"co_invoices",
[
"Test Invoice",
100,
],
[
"inv_title",
"inv_total",
]
);
// Getting the generated id
$id = $connection->lastInsertId();ping()
public function ping(): bool;Checks whether the underlying connection is still alive by issuing a trivial query. Returns false if there is no handle or the probe fails.
prepare()
public function prepare( string $sqlStatement ): \PDOStatement;Returns a PDO prepared statement to be executed with ‘executePrepared’
use Phalcon\Db\Column;
$statement = $db->prepare(
"SELECT * FROM co_invoices WHERE inv_title = :inv_title"
);
$result = $connection->executePrepared(
$statement,
[
"inv_title" => "Test Invoice",
],
[
"inv_title" => Column::BIND_PARAM_INT,
]
);query()
public function query(
string $sqlStatement,
array $bindParams = [],
array $bindTypes = []
): ResultInterface|bool;Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows
// Querying data
$resultset = $connection->query(
"SELECT * FROM co_invoices WHERE inv_status_flag = 1"
);
$resultset = $connection->query(
"SELECT * FROM co_invoices WHERE inv_status_flag = ?",
[
1,
]
);rollback()
public function rollback( bool $nesting = true ): bool;Rollbacks the active transaction in the connection
setAutoReconnect()
public function setAutoReconnect( bool $autoReconnect ): static;Enables or disables transparent auto-reconnect on a lost connection.
getDsnDefaults()
abstract protected function getDsnDefaults(): array;Returns PDO adapter DSN defaults as a key-value map.
isConnectionError()
protected function isConnectionError( \Throwable $exception ): bool;Recognizes whether an exception represents a lost (“gone away”) connection. The base adapter cannot know driver specifics, so it returns false; concrete adapters override this.
prepareRealSql()
protected function prepareRealSql(
string $statement,
array $parameters
): void;Constructs the SQL statement (with parameters)
@see https://stackoverflow.com/a/8403150
Db\Adapter\Pdo\Mysql
ClassSource on GitHubSpecific functions for the MySQL database system
use Phalcon\Db\Adapter\Pdo\Mysql;
$config = [
"host" => "localhost",
"dbname" => "blog",
"port" => 3306,
"username" => "sigma",
"password" => "secret",
];
$connection = new Mysql($config);Phalcon\Db\Adapter\AbstractAdapterPhalcon\Db\Adapter\Pdo\AbstractPdoPhalcon\Db\Adapter\Pdo\Mysql
Uses Phalcon\Db\Adapter\Pdo\AbstractPdo · Phalcon\Db\Column · Phalcon\Db\ColumnInterface · Phalcon\Db\Enum · Phalcon\Db\Exception · Phalcon\Db\Exceptions\MissingForeignKeyChecks · Phalcon\Db\Index · Phalcon\Db\IndexInterface · Phalcon\Db\Reference · Phalcon\Db\ReferenceInterface
Method Summary
publicbooladdForeignKey(string$tableName,string$schemaName,ReferenceInterface$reference)Adds a foreign key to a tablepublicColumnInterface[]describeColumns(string$table,string|null$schema = null)Returns an array of Phalcon\Db\Column objects describing a tablepublicIndexInterface[]describeIndexes(string$table,string|null$schema = null)Lists table indexespublicReferenceInterface[]describeReferences(string$table,string|null$schema = null)Lists table referencesprotectedarraygetDsnDefaults()Returns PDO adapter DSN defaults as a key-value map.protectedboolisConnectionError( \Throwable$exception )Recognizes a MySQL "server has gone away" / "Lost connection" failureProperties
protectedstring$dialectType = "mysql"protectedstring$type = "mysql"Methods
addForeignKey()
public function addForeignKey(
string $tableName,
string $schemaName,
ReferenceInterface $reference
): bool;Adds a foreign key to a table
describeColumns()
public function describeColumns(
string $table,
string|null $schema = null
): ColumnInterface[];Returns an array of Phalcon\Db\Column objects describing a table
print_r(
$connection->describeColumns("posts")
);describeIndexes()
public function describeIndexes(
string $table,
string|null $schema = null
): IndexInterface[];Lists table indexes
print_r(
$connection->describeIndexes("co_orders_x_products")
);describeReferences()
public function describeReferences(
string $table,
string|null $schema = null
): ReferenceInterface[];Lists table references
print_r(
$connection->describeReferences("co_orders_x_products")
);getDsnDefaults()
protected function getDsnDefaults(): array;Returns PDO adapter DSN defaults as a key-value map.
isConnectionError()
protected function isConnectionError( \Throwable $exception ): bool;Recognizes a MySQL “server has gone away” / “Lost connection” failure by the driver error code (2006 / 2013) with a message fallback.
Db\Adapter\Pdo\Postgresql
ClassSource on GitHubSpecific functions for the PostgreSQL database system
use Phalcon\Db\Adapter\Pdo\Postgresql;
$config = [
"host" => "localhost",
"dbname" => "blog",
"port" => 5432,
"username" => "postgres",
"password" => "secret",
];
$connection = new Postgresql($config);Phalcon\Db\Adapter\AbstractAdapterPhalcon\Db\Adapter\Pdo\AbstractPdoPhalcon\Db\Adapter\Pdo\Postgresql
Uses Phalcon\Db\Adapter\Pdo\AbstractPdo · Phalcon\Db\Column · Phalcon\Db\ColumnInterface · Phalcon\Db\Enum · Phalcon\Db\Exception · Phalcon\Db\Exceptions\TableMustHaveColumn · Phalcon\Db\RawValue · Phalcon\Db\Reference · Phalcon\Db\ReferenceInterface · Throwable
Method Summary
public__construct( array$descriptor )Constructor for Phalcon\Db\Adapter\Pdo\Postgresqlpublicvoidconnect( array$descriptor = [] )This method is automatically called in Phalcon\Db\Adapter\PdopublicboolcreateTable(string$tableName,string$schemaName,array$definition)Creates a tablepublicColumnInterface[]describeColumns(string$table,string|null$schema = null)Returns an array of Phalcon\Db\Column objects describing a tablepublicReferenceInterface[]describeReferences(string$table,string|null$schema = null)Lists table referencespublicRawValuegetDefaultIdValue()Returns the default identity value to be inserted in an identity columnpublicboolmodifyColumn(string$tableName,string$schemaName,ColumnInterface$column,ColumnInterface|null$currentColumn = null)Modifies a table column based on a definitionpublicboolsupportSequences()Check whether the database system requires a sequence to producepublicbooluseExplicitIdValue()Check whether the database system requires an explicit value for identityprotectedarraygetDsnDefaults()Returns PDO adapter DSN defaults as a key-value map.protectedboolisConnectionError( \Throwable$exception )Recognizes a PostgreSQL connection-loss failure by SQLSTATEProperties
protectedstring$dialectType = "postgresql"protectedstring$type = "pgsql"Methods
__construct()
public function __construct( array $descriptor );Constructor for Phalcon\Db\Adapter\Pdo\Postgresql
connect()
public function connect( array $descriptor = [] ): void;This method is automatically called in Phalcon\Db\Adapter\Pdo constructor. Call it when you need to restore a database connection.
createTable()
public function createTable(
string $tableName,
string $schemaName,
array $definition
): bool;Creates a table
describeColumns()
public function describeColumns(
string $table,
string|null $schema = null
): ColumnInterface[];Returns an array of Phalcon\Db\Column objects describing a table
print_r(
$connection->describeColumns("posts")
);describeReferences()
public function describeReferences(
string $table,
string|null $schema = null
): ReferenceInterface[];Lists table references
print_r(
$connection->describeReferences("co_orders_x_products")
);getDefaultIdValue()
public function getDefaultIdValue(): RawValue;Returns the default identity value to be inserted in an identity column
// Inserting a new invoice with a valid default value for the column 'inv_id'
$success = $connection->insert(
"co_invoices",
[
$connection->getDefaultIdValue(),
"Test Invoice",
100,
],
[
"inv_id",
"inv_title",
"inv_total",
]
);modifyColumn()
public function modifyColumn(
string $tableName,
string $schemaName,
ColumnInterface $column,
ColumnInterface|null $currentColumn = null
): bool;Modifies a table column based on a definition
supportSequences()
public function supportSequences(): bool;Check whether the database system requires a sequence to produce auto-numeric values
useExplicitIdValue()
public function useExplicitIdValue(): bool;Check whether the database system requires an explicit value for identity columns
getDsnDefaults()
protected function getDsnDefaults(): array;Returns PDO adapter DSN defaults as a key-value map.
isConnectionError()
protected function isConnectionError( \Throwable $exception ): bool;Recognizes a PostgreSQL connection-loss failure by SQLSTATE (connection exception class 08, or admin/crash shutdown 57P0x) with a message fallback.
Db\Adapter\Pdo\Sqlite
ClassSource on GitHubSpecific functions for the SQLite database system
use Phalcon\Db\Adapter\Pdo\Sqlite;
$connection = new Sqlite(
[
"dbname" => "/tmp/test.sqlite",
]
);Phalcon\Db\Adapter\AbstractAdapterPhalcon\Db\Adapter\Pdo\AbstractPdoPhalcon\Db\Adapter\Pdo\Sqlite
Uses Phalcon\Db\Adapter\Pdo\AbstractPdo · Phalcon\Db\Column · Phalcon\Db\ColumnInterface · Phalcon\Db\Enum · Phalcon\Db\Exception · Phalcon\Db\Exceptions\MissingSqliteDatabase · Phalcon\Db\Index · Phalcon\Db\IndexInterface · Phalcon\Db\RawValue · Phalcon\Db\Reference · Phalcon\Db\ReferenceInterface
Method Summary
public__construct( array$descriptor )Constructor for Phalcon\Db\Adapter\Pdo\Sqlitepublicvoidconnect( array$descriptor = [] )This method is automatically called in Phalcon\Db\Adapter\PdopublicColumnInterface[]describeColumns(string$table,string|null$schema = null)Returns an array of Phalcon\Db\Column objects describing a tablepublicIndexInterface[]describeIndexes(string$table,string|null$schema = null)Lists table indexespublicReferenceInterface[]describeReferences(string$table,string|null$schema = null)Lists table referencespublicRawValuegetDefaultValue()Returns the default value to make the RBDM use the default value declaredpublicboolsupportsDefaultValue()SQLite does not support the DEFAULT keywordpublicbooluseExplicitIdValue()Check whether the database system requires an explicit value for identityprotectedarraygetDsnDefaults()Returns PDO adapter DSN defaults as a key-value map.Properties
protectedstring$dialectType = "sqlite"protectedstring$type = "sqlite"Methods
__construct()
public function __construct( array $descriptor );Constructor for Phalcon\Db\Adapter\Pdo\Sqlite
connect()
public function connect( array $descriptor = [] ): void;This method is automatically called in Phalcon\Db\Adapter\Pdo constructor. Call it when you need to restore a database connection.
describeColumns()
public function describeColumns(
string $table,
string|null $schema = null
): ColumnInterface[];Returns an array of Phalcon\Db\Column objects describing a table
print_r(
$connection->describeColumns("posts")
);describeIndexes()
public function describeIndexes(
string $table,
string|null $schema = null
): IndexInterface[];Lists table indexes
print_r(
$connection->describeIndexes("co_orders_x_products")
);describeReferences()
public function describeReferences(
string $table,
string|null $schema = null
): ReferenceInterface[];Lists table references
getDefaultValue()
public function getDefaultValue(): RawValue;Returns the default value to make the RBDM use the default value declared in the table definition
// Inserting a new invoice with a valid default value for the column 'inv_total'
$success = $connection->insert(
"co_invoices",
[
"Test Invoice",
$connection->getDefaultValue(),
],
[
"inv_title",
"inv_total",
]
);supportsDefaultValue()
public function supportsDefaultValue(): bool;SQLite does not support the DEFAULT keyword
useExplicitIdValue()
public function useExplicitIdValue(): bool;Check whether the database system requires an explicit value for identity columns
getDsnDefaults()
protected function getDsnDefaults(): array;Returns PDO adapter DSN defaults as a key-value map.
Db\Check
ClassSource on GitHubAllows to define CHECK constraints on tables. CHECK constraints enforce
a boolean SQL predicate on each row of the table; rows that fail the
predicate are rejected at INSERT/UPDATE time.
use Phalcon\Db\Check;
$positivePrice = new Check(
"chk_price_positive",
[
"expression" => "price > 0",
]
);
// Used inside a createTable() definition
$connection->createTable(
"products",
null,
[
"columns" => [ ... ],
"checks" => [$positivePrice],
]
);
// Or added to an existing table (MySQL 8.0.16+ and PostgreSQL).
// SQLite cannot add CHECK constraints to existing tables.
$connection->addCheck("products", null, $positivePrice);Phalcon\Db\Check- implementsPhalcon\Db\CheckInterface
Uses Phalcon\Db\Exceptions\CheckExpressionRequired · Phalcon\Db\Exceptions\InvalidCheckExpression
Method Summary
public__construct(string$name,array$definition)Phalcon\Db\Check constructorpublicstringgetExpression()Returns the CHECK expressionpublicstringgetName()Returns the constraint name (may be an empty string for unnamed)Properties
protectedstring$expressionThe boolean SQL predicate this constraint enforces.protectedstring$nameThe CHECK constraint name. An empty string indicates an unnamed constraint - the dialect will emit the clause without a CONSTRAINT prefix in that case.Methods
__construct()
public function __construct(
string $name,
array $definition
);Phalcon\Db\Check constructor
getExpression()
public function getExpression(): string;Returns the CHECK expression
getName()
public function getName(): string;Returns the constraint name (may be an empty string for unnamed)
Db\CheckInterface
InterfaceSource on GitHubPhalcon\Db\CheckInterface
Phalcon\Contracts\Db\CheckPhalcon\Db\CheckInterface
Uses Phalcon\Contracts\Db\Check
Db\Column
ClassSource on GitHubAllows to define columns to be used on create or alter table operations
use Phalcon\Db\Column as Column;
// Column definition
$column = new Column(
"id",
[
"type" => Column::TYPE_INTEGER,
"size" => 10,
"unsigned" => true,
"notNull" => true,
"autoIncrement" => true,
"first" => true,
"comment" => "",
]
);
// Add column to existing table
$connection->addColumn("co_invoices", null, $column);Phalcon\Db\Column- implementsPhalcon\Db\ColumnInterface
Uses Phalcon\Db\Exceptions\ColumnTypeRejectsAutoIncrement · Phalcon\Db\Exceptions\ColumnTypeRejectsScale · Phalcon\Db\Exceptions\ColumnTypeRequired · Phalcon\Db\Exceptions\GeneratedAutoIncrementConflict · Phalcon\Db\Exceptions\GeneratedDefaultConflict · Phalcon\Db\Exceptions\InvalidGenerationExpression
Method Summary
public__construct(string$name,array$definition)Phalcon\Db\Column constructorpublicstring|nullgetAfterPosition()Check whether field absolute to position in tablepublicintgetBindType()Returns the type of bind handlingpublicstring|nullgetComment()Column's commentpublicmixedgetDefault()Default column valuepublicstring|nullgetGenerationExpression()Returns the generation expression for a generated/computed column.publicstringgetName()Column's namepublicintgetScale()Integer column number scalepublicint|stringgetSize()Integer column sizepublicint|stringgetType()Column data typepublicintgetTypeReference()Column data type referencepublicarray|stringgetTypeValues()Column data type valuespublicboolhasDefault()Check whether column has default valuepublicboolisArray()Whether the column is an array of its base type. Recognized by thepublicboolisAutoIncrement()Auto-IncrementpublicboolisFirst()Check whether column have first position in tablepublicboolisGenerated()Whether the column is a generated/computed column.publicboolisGenerationStored()Whether a generated column is STORED. false means VIRTUAL.publicboolisInvisible()Whether the column is declared INVISIBLE (MySQL 8.0.23+). InvisiblepublicboolisNotNull()Not nullpublicboolisNumeric()Check whether column have an numeric typepublicboolisPrimary()Column is part of the primary key?publicboolisUnsigned()Returns true if number column is unsignedConstants
intBIND_PARAM_BLOB = 3Bind Type BlobintBIND_PARAM_BOOL = 5Bind Type BoolintBIND_PARAM_DECIMAL = 32Bind Type DecimalintBIND_PARAM_INT = 1Bind Type IntegerintBIND_PARAM_NULL = 0Bind Type NullintBIND_PARAM_STR = 2Bind Type StringintBIND_SKIP = 1024Skip binding by typeintTYPE_BIGINTEGER = 14Big integer abstract data typeintTYPE_BINARY = 27Binary abstract data typeintTYPE_BIT = 19Bit abstract data typeintTYPE_BLOB = 11Blob abstract data typeintTYPE_BOOLEAN = 8Bool abstract data typeintTYPE_BYTEA = 30PostgreSQL BYTEA binary typeintTYPE_CHAR = 5Char abstract data typeintTYPE_CIDR = 32PostgreSQL CIDR network-address typeintTYPE_DATE = 1Date abstract data typeintTYPE_DATERANGE = 39PostgreSQL DATERANGE range-of-date typeintTYPE_DATETIME = 4Datetime abstract data typeintTYPE_DECIMAL = 3Decimal abstract data typeintTYPE_DOUBLE = 9Double abstract data typeintTYPE_ENUM = 18Enum abstract data typeintTYPE_FLOAT = 7Float abstract data typeintTYPE_GEOMETRY = 40Spatial GEOMETRY base type (MySQL 5.7+; PostgreSQL + PostGIS)intTYPE_GEOMETRYCOLLECTION = 47Spatial GEOMETRYCOLLECTION type (MySQL; PostgreSQL + PostGIS)intTYPE_INET = 31PostgreSQL INET IPv4/IPv6 address typeintTYPE_INT4RANGE = 34PostgreSQL INT4RANGE range-of-integer typeintTYPE_INT8RANGE = 35PostgreSQL INT8RANGE range-of-bigint typeintTYPE_INTEGER = 0Int abstract data typeintTYPE_JSON = 15Json abstract data typeintTYPE_JSONB = 16Jsonb abstract data typeintTYPE_LINESTRING = 42Spatial LINESTRING type (MySQL; PostgreSQL + PostGIS)intTYPE_LONGBLOB = 13Longblob abstract data typeintTYPE_LONGTEXT = 24Longtext abstract data typeintTYPE_MACADDR = 33PostgreSQL MACADDR MAC-address typeintTYPE_MEDIUMBLOB = 12Mediumblob abstract data typeintTYPE_MEDIUMINTEGER = 21Mediumintegerr abstract data typeintTYPE_MEDIUMTEXT = 23Mediumtext abstract data typeintTYPE_MULTILINESTRING = 45Spatial MULTILINESTRING type (MySQL; PostgreSQL + PostGIS)intTYPE_MULTIPOINT = 44Spatial MULTIPOINT type (MySQL; PostgreSQL + PostGIS)intTYPE_MULTIPOLYGON = 46Spatial MULTIPOLYGON type (MySQL; PostgreSQL + PostGIS)intTYPE_NUMRANGE = 36PostgreSQL NUMRANGE range-of-numeric typeintTYPE_POINT = 41Spatial POINT type (MySQL; PostgreSQL + PostGIS)intTYPE_POLYGON = 43Spatial POLYGON type (MySQL; PostgreSQL + PostGIS)intTYPE_SMALLINTEGER = 22Smallint abstract data typeintTYPE_TEXT = 6Text abstract data typeintTYPE_TIME = 20Time abstract data typeintTYPE_TIMESTAMP = 17Timestamp abstract data typeintTYPE_TINYBLOB = 10Tinyblob abstract data typeintTYPE_TINYINTEGER = 26Tinyint abstract data typeintTYPE_TINYTEXT = 25Tinytext abstract data typeintTYPE_TSRANGE = 37PostgreSQL TSRANGE range-of-timestamp (without time zone) typeintTYPE_TSTZRANGE = 38PostgreSQL TSTZRANGE range-of-timestamp (with time zone) typeintTYPE_UUID = 29UUID abstract data typeintTYPE_VARBINARY = 28Varbinary abstract data typeintTYPE_VARCHAR = 2Varchar abstract data typeProperties
protectedstring|null$after = nullColumn Positionprotectedbool$autoIncrement = falseColumn is autoIncrement?protectedint$bindType = 2Bind Typeprotectedstring|null$comment = nullColumn's commentprotectedmixed|null$defaultValue = nullDefault column valueprotectedbool$first = falsePosition is firstprotectedstring|null$generated = nullGeneration expression for GENERATED ALWAYS AS (…). Null when the column is not a generated/computed column.protectedbool$generationStored = falseWhether a generated column is STORED (true) or VIRTUAL (false). Ignored when the column is not generated. PostgreSQL only supports STORED and emits it regardless of this flag.protectedbool$invisible = falseWhether the column is INVISIBLE (MySQL 8.0.23+). Invisible columns are excluded from SELECT * expansion but can still be referenced explicitly.protectedbool$isArray = falseWhether the column is an array of its base type. Recognized by the PostgreSQL dialect (e.g. INTEGER[], TEXT[]). MySQL and SQLite ignore the flag.protectedbool$isNumeric = falseThe column have some numeric type?protectedstring$nameColumn's nameprotectedbool$notNull = trueColumn not nullable? Default SQL definition is NOT NULL.protectedbool$primary = falseColumn is part of the primary key?protectedint$scale = 0Integer column number scaleprotectedint|string$size = 0Integer column sizeprotectedint$typeColumn data typeprotectedint$typeReference = -1Column data type referenceprotectedarray|string$typeValues = []Column data type valuesprotectedbool$unsigned = falseInteger column unsigned?Methods
__construct()
public function __construct(
string $name,
array $definition
);Phalcon\Db\Column constructor
getAfterPosition()
public function getAfterPosition(): string|null;Check whether field absolute to position in table
getBindType()
public function getBindType(): int;Returns the type of bind handling
getComment()
public function getComment(): string|null;Column’s comment
getDefault()
public function getDefault(): mixed;Default column value
getGenerationExpression()
public function getGenerationExpression(): string|null;Returns the generation expression for a generated/computed column.
Returns null when the column is not generated.
getName()
public function getName(): string;Column’s name
getScale()
public function getScale(): int;Integer column number scale
getSize()
public function getSize(): int|string;Integer column size
getType()
public function getType(): int|string;Column data type
getTypeReference()
public function getTypeReference(): int;Column data type reference
getTypeValues()
public function getTypeValues(): array|string;Column data type values
hasDefault()
public function hasDefault(): bool;Check whether column has default value
isArray()
public function isArray(): bool;Whether the column is an array of its base type. Recognized by the
PostgreSQL dialect (e.g. INTEGER[], TEXT[]); MySQL and SQLite
ignore the flag.
isAutoIncrement()
public function isAutoIncrement(): bool;Auto-Increment
isFirst()
public function isFirst(): bool;Check whether column have first position in table
isGenerated()
public function isGenerated(): bool;Whether the column is a generated/computed column.
isGenerationStored()
public function isGenerationStored(): bool;Whether a generated column is STORED. false means VIRTUAL.
Always meaningful only when isGenerated() is true.
isInvisible()
public function isInvisible(): bool;Whether the column is declared INVISIBLE (MySQL 8.0.23+). Invisible
columns are excluded from SELECT * expansion but can still be
referenced explicitly. PostgreSQL and SQLite have no equivalent and
dialects targeting them ignore the flag.
isNotNull()
public function isNotNull(): bool;Not null
isNumeric()
public function isNumeric(): bool;Check whether column have an numeric type
isPrimary()
public function isPrimary(): bool;Column is part of the primary key?
isUnsigned()
public function isUnsigned(): bool;Returns true if number column is unsigned
Db\ColumnInterface
InterfaceSource on GitHubPhalcon\Db\ColumnInterface
Phalcon\Contracts\Db\ColumnPhalcon\Db\ColumnInterface
Uses Phalcon\Contracts\Db\Column
Db\Dialect
AbstractSource on GitHubThis is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax
Phalcon\Db\Dialect- implementsPhalcon\Db\DialectInterface
Uses Phalcon\Db\Exceptions\ConflictTargetColumnRequired · Phalcon\Db\Exceptions\ConflictUpdateColumnRequired · Phalcon\Db\Exceptions\InvalidGroupByExpression · Phalcon\Db\Exceptions\InvalidListExpression · Phalcon\Db\Exceptions\InvalidOrderByExpression · Phalcon\Db\Exceptions\InvalidSqlExpression · Phalcon\Db\Exceptions\InvalidSqlExpressionType · Phalcon\Db\Exceptions\InvalidUnaryExpression · Phalcon\Db\Exceptions\MaterializedViewsNotSupported · Phalcon\Db\Exceptions\MissingDefinitionKey · Phalcon\Db\Exceptions\ReturningNotSupported · Phalcon\Db\Exceptions\UnsupportedOperator · Phalcon\Support\Settings
Method Summary
publicstringcreateMaterializedView(string$viewName,array$definition,string|null$schemaName = null)Generates SQL to create a materialized view. Supported by PostgreSQLpublicstringcreateSavepoint( string$name )Generate SQL to create a new savepointpublicstringdropMaterializedView(string$viewName,string|null$schemaName = null,bool$ifExists = true)Generates SQL to drop a materialized view. Supported by PostgreSQL.publicstringescape(string$str,string|null$escapeChar = null)Escape identifierspublicstringescapeSchema(string$str,string|null$escapeChar = null)Escape SchemapublicstringforUpdate(string$sqlQuery,string$modifier = "")Returns a SQL modified with a FOR UPDATE clause. The optional modifierpublicstringgetColumnList(array$columnList,string|null$escapeChar = null,array$bindCounts = [])Gets a list of columns with escaped identifierspublicarraygetCustomFunctions()Returns registered functionspublicstringgetSqlColumn(mixed$column,string|null$escapeChar = null,array$bindCounts = [])Resolve Column expressionspublicstringgetSqlExpression(array$expression,string|null$escapeChar = null,array$bindCounts = [])Transforms an intermediate representation for an expression into a database system valid expressionpublicstringgetSqlTable(mixed$table,string|null$escapeChar = null)Transform an intermediate representation of a schema/table into apublicstringlimit(string$sqlQuery,mixed$number)Generates the SQL for LIMIT clausepublicstringonConflictUpdate(string$sqlQuery,array$conflictColumns,array$updateColumns)Appends an ON CONFLICT (col, …) DO UPDATE SET col = excluded.colpublicstringrefreshMaterializedView(string$viewName,string|null$schemaName = null,bool$concurrent = false)Generates SQL to refresh a materialized view. Supported bypublicstaticregisterCustomFunction(string$name,callable$customFunction)Registers custom SQL functionspublicstringreleaseSavepoint( string$name )Generate SQL to release a savepointpublicstringreturning(string$sqlQuery,array$columns)Returns a SQL statement extended with a RETURNING clause so thepublicstringrollbackSavepoint( string$name )Generate SQL to rollback a savepointpublicstringselect( array$definition )Builds a SELECT statementpublicboolsupportsAlterTable()Checks whether the platform supports the full ALTER TABLE matrix:publicboolsupportsMaterializedViews()Checks whether the platform supports materialized views. Only PostgreSQLpublicboolsupportsOnConflictUpdate()Checks whether the platform supports the ON CONFLICT (…) DO UPDATEpublicboolsupportsReleaseSavepoints()Checks whether the platform supports releasing savepoints.publicboolsupportsReturning()Checks whether the platform supports the RETURNING clause. MySQLpublicboolsupportsSavepoints()Checks whether the platform supports savepointsprotectedstringcheckColumnType( ColumnInterface$column )Checks the column type and if not string it returns the type referenceprotectedstringcheckColumnTypeSql( ColumnInterface$column )Checks the column type and returns the updated SQL statementprotectedstringgetCheckClause(CheckInterface$check,string$escapeChar = "`")Builds a CHECK constraint clause from a CheckInterface, using theprotectedstringgetColumnSize( ColumnInterface$column )Returns the size of the column enclosed in parenthesesprotectedstringgetColumnSizeAndScale( ColumnInterface$column )Returns the column size and scale enclosed in parenthesesprotectedstringgetGeneratedClause(ColumnInterface$column,bool$forceStored = false)Builds the GENERATED ALWAYS AS (<expr>) VIRTUAL|STORED clause for aprotectedstringgetIndexColumnList(IndexInterface$index,bool$wrapExpressions = true)Builds the per-index parenthesized column list, honoring per-columnprotectedstringgetSqlExpressionAll(array$expression,string|null$escapeChar = null)Resolve *protectedstringgetSqlExpressionBinaryOperations(array$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve binary operations expressionsprotectedstringgetSqlExpressionCase(array$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve CASE expressionsprotectedstringgetSqlExpressionCastValue(array$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve CAST of valuesprotectedstringgetSqlExpressionConvertValue(array$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve CONVERT of values encodingsprotectedstringgetSqlExpressionFrom(mixed$expression,string|null$escapeChar = null)Resolve a FROM clauseprotectedstringgetSqlExpressionFunctionCall(array$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve function callsprotectedstringgetSqlExpressionGroupBy(mixed$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve a GROUP BY clauseprotectedstringgetSqlExpressionHaving(array$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve a HAVING clauseprotectedstringgetSqlExpressionJoins(mixed$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve a JOINs clauseprotectedstringgetSqlExpressionLimit(mixed$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve a LIMIT clauseprotectedstringgetSqlExpressionList(array$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve ListsprotectedstringgetSqlExpressionObject(array$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve object expressionsprotectedstringgetSqlExpressionOrderBy(mixed$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve an ORDER BY clauseprotectedstringgetSqlExpressionQualified(array$expression,string|null$escapeChar = null)Resolve qualified expressionsprotectedstringgetSqlExpressionScalar(array$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve Column expressionsprotectedstringgetSqlExpressionUnaryOperations(array$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve unary operations expressionsprotectedstringgetSqlExpressionWhere(mixed$expression,string|null$escapeChar = null,array$bindCounts = [])Resolve a WHERE clauseprotectedstringprepareColumnAlias(string$qualified,string|null$alias = null,string|null$escapeChar = null)Prepares column for this RDBMSprotectedstringprepareQualified(string$column,string|null$domain = null,string|null$escapeChar = null)Prepares qualified for this RDBMSprotectedstringprepareTable(string$table,string|null$schema = null,string|null$alias = null,string|null$escapeChar = null)Prepares table for this RDBMSProperties
protectedarray$customFunctions = []protectedstring$escapeCharprotectedarray$guardedOperators = […]Dialect-specific operators that a concrete dialect must opt into via supportedOperators; using one elsewhere throws.protectedarray$supportedOperators = []Subset of guardedOperators that this dialect emits. Overridden per dialect.Methods
createMaterializedView()
public function createMaterializedView(
string $viewName,
array $definition,
string|null $schemaName = null
): string;Generates SQL to create a materialized view. Supported by PostgreSQL
(CREATE MATERIALIZED VIEW name AS <sql>). Other dialects inherit
this throw - MySQL and SQLite have no materialized-view concept.
createSavepoint()
public function createSavepoint( string $name ): string;Generate SQL to create a new savepoint
dropMaterializedView()
public function dropMaterializedView(
string $viewName,
string|null $schemaName = null,
bool $ifExists = true
): string;Generates SQL to drop a materialized view. Supported by PostgreSQL.
escape()
final public function escape(
string $str,
string|null $escapeChar = null
): string;Escape identifiers
escapeSchema()
final public function escapeSchema(
string $str,
string|null $escapeChar = null
): string;Escape Schema
forUpdate()
public function forUpdate(
string $sqlQuery,
string $modifier = ""
): string;Returns a SQL modified with a FOR UPDATE clause. The optional modifier
appends a row-lock disposition keyword.
$sql = $dialect->forUpdate("SELECT * FROM co_invoices");
echo $sql; // SELECT * FROM co_invoices FOR UPDATE
$sql = $dialect->forUpdate(
"SELECT * FROM co_invoices",
Dialect::LOCK_NOWAIT
);
echo $sql; // SELECT * FROM co_invoices FOR UPDATE NOWAIT
$sql = $dialect->forUpdate(
"SELECT * FROM co_invoices",
Dialect::LOCK_SKIP_LOCKED
);
echo $sql; // SELECT * FROM co_invoices FOR UPDATE SKIP LOCKEDgetColumnList()
final public function getColumnList(
array $columnList,
string|null $escapeChar = null,
array $bindCounts = []
): string;Gets a list of columns with escaped identifiers
echo $dialect->getColumnList(
[
"column1",
"column",
]
);getCustomFunctions()
public function getCustomFunctions(): array;Returns registered functions
getSqlColumn()
final public function getSqlColumn(
mixed $column,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve Column expressions
getSqlExpression()
public function getSqlExpression(
array $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Transforms an intermediate representation for an expression into a database system valid expression
getSqlTable()
final public function getSqlTable(
mixed $table,
string|null $escapeChar = null
): string;Transform an intermediate representation of a schema/table into a database system valid expression
limit()
public function limit(
string $sqlQuery,
mixed $number
): string;Generates the SQL for LIMIT clause
// SELECT * FROM co_invoices LIMIT 10
echo $dialect->limit(
"SELECT * FROM co_invoices",
10
);
// SELECT * FROM co_invoices LIMIT 10 OFFSET 50
echo $dialect->limit(
"SELECT * FROM co_invoices",
[10, 50]
);onConflictUpdate()
public function onConflictUpdate(
string $sqlQuery,
array $conflictColumns,
array $updateColumns
): string;Appends an ON CONFLICT (col, ...) DO UPDATE SET col = excluded.col
upsert clause to the supplied INSERT statement. The syntax is the
SQL standard form recognized by PostgreSQL (9.5+) and SQLite (3.24+).
MySQL overrides this method to throw because its ON DUPLICATE KEY UPDATE has a different shape (deferred to parser item #23).
refreshMaterializedView()
public function refreshMaterializedView(
string $viewName,
string|null $schemaName = null,
bool $concurrent = false
): string;Generates SQL to refresh a materialized view. Supported by
PostgreSQL. Pass concurrent = true for REFRESH MATERIALIZED VIEW CONCURRENTLY ..., which avoids blocking concurrent SELECTs (requires
the view to have a unique index).
registerCustomFunction()
public function registerCustomFunction(
string $name,
callable $customFunction
): static;Registers custom SQL functions
releaseSavepoint()
public function releaseSavepoint( string $name ): string;Generate SQL to release a savepoint
returning()
public function returning(
string $sqlQuery,
array $columns
): string;Returns a SQL statement extended with a RETURNING clause so the
INSERT/UPDATE/DELETE returns rows. Supported by PostgreSQL and
SQLite 3.35+. Pass ["*"] for RETURNING *, or a list of column
names. The base implementation throws - MySQL inherits it because
MySQL has no RETURNING construct.
rollbackSavepoint()
public function rollbackSavepoint( string $name ): string;Generate SQL to rollback a savepoint
select()
public function select( array $definition ): string;Builds a SELECT statement
supportsAlterTable()
public function supportsAlterTable(): bool;Checks whether the platform supports the full ALTER TABLE matrix:
modifying existing columns and adding or dropping foreign keys, primary
keys, and check constraints. SQLite returns false - those operations
throw a dedicated Sqlite*NotSupported exception there (basic
ADD COLUMN remains available).
supportsMaterializedViews()
public function supportsMaterializedViews(): bool;Checks whether the platform supports materialized views. Only PostgreSQL
returns true; createMaterializedView() throws on the other dialects.
supportsOnConflictUpdate()
public function supportsOnConflictUpdate(): bool;Checks whether the platform supports the ON CONFLICT (...) DO UPDATE
upsert clause. MySQL returns false; onConflictUpdate() throws there.
supportsReleaseSavepoints()
public function supportsReleaseSavepoints(): bool;Checks whether the platform supports releasing savepoints.
supportsReturning()
public function supportsReturning(): bool;Checks whether the platform supports the RETURNING clause. MySQL
returns false; returning() throws there.
supportsSavepoints()
public function supportsSavepoints(): bool;Checks whether the platform supports savepoints
checkColumnType()
protected function checkColumnType( ColumnInterface $column ): string;Checks the column type and if not string it returns the type reference
checkColumnTypeSql()
protected function checkColumnTypeSql( ColumnInterface $column ): string;Checks the column type and returns the updated SQL statement
getCheckClause()
protected function getCheckClause(
CheckInterface $check,
string $escapeChar = "`"
): string;Builds a CHECK constraint clause from a CheckInterface, using the
provided escape character for the constraint name (so each dialect
gets its native quoting). Returns the clause body - the dialect’s
createTable() / addCheck() is expected to prefix ADD or place
the result on its own line as appropriate.
getColumnSize()
protected function getColumnSize( ColumnInterface $column ): string;Returns the size of the column enclosed in parentheses
getColumnSizeAndScale()
protected function getColumnSizeAndScale( ColumnInterface $column ): string;Returns the column size and scale enclosed in parentheses
getGeneratedClause()
protected function getGeneratedClause(
ColumnInterface $column,
bool $forceStored = false
): string;Builds the GENERATED ALWAYS AS (<expr>) VIRTUAL|STORED clause for a
generated/computed column. Returns an empty string when the column is
not generated. When forceStored is true the clause is always emitted
as STORED regardless of the column’s isGenerationStored() flag -
PostgreSQL uses this since it only supports stored generated columns.
getIndexColumnList()
protected function getIndexColumnList(
IndexInterface $index,
bool $wrapExpressions = true
): string;Builds the per-index parenthesized column list, honoring per-column
sort directions when the index declares any. Returns the bare
comma-separated getColumnList() output when no directions are set,
preserving the legacy rendering exactly. When directions are set,
each column is followed by ASC or DESC; trailing positions
absent from the directions array default to ASC.
getSqlExpressionAll()
final protected function getSqlExpressionAll(
array $expression,
string|null $escapeChar = null
): string;Resolve *
getSqlExpressionBinaryOperations()
final protected function getSqlExpressionBinaryOperations(
array $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve binary operations expressions
getSqlExpressionCase()
final protected function getSqlExpressionCase(
array $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve CASE expressions
getSqlExpressionCastValue()
final protected function getSqlExpressionCastValue(
array $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve CAST of values
getSqlExpressionConvertValue()
final protected function getSqlExpressionConvertValue(
array $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve CONVERT of values encodings
getSqlExpressionFrom()
final protected function getSqlExpressionFrom(
mixed $expression,
string|null $escapeChar = null
): string;Resolve a FROM clause
getSqlExpressionFunctionCall()
final protected function getSqlExpressionFunctionCall(
array $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve function calls
getSqlExpressionGroupBy()
final protected function getSqlExpressionGroupBy(
mixed $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve a GROUP BY clause
getSqlExpressionHaving()
final protected function getSqlExpressionHaving(
array $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve a HAVING clause
getSqlExpressionJoins()
final protected function getSqlExpressionJoins(
mixed $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve a JOINs clause
getSqlExpressionLimit()
final protected function getSqlExpressionLimit(
mixed $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve a LIMIT clause
getSqlExpressionList()
final protected function getSqlExpressionList(
array $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve Lists
getSqlExpressionObject()
final protected function getSqlExpressionObject(
array $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve object expressions
getSqlExpressionOrderBy()
final protected function getSqlExpressionOrderBy(
mixed $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve an ORDER BY clause
getSqlExpressionQualified()
final protected function getSqlExpressionQualified(
array $expression,
string|null $escapeChar = null
): string;Resolve qualified expressions
getSqlExpressionScalar()
final protected function getSqlExpressionScalar(
array $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve Column expressions
getSqlExpressionUnaryOperations()
final protected function getSqlExpressionUnaryOperations(
array $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve unary operations expressions
getSqlExpressionWhere()
final protected function getSqlExpressionWhere(
mixed $expression,
string|null $escapeChar = null,
array $bindCounts = []
): string;Resolve a WHERE clause
prepareColumnAlias()
protected function prepareColumnAlias(
string $qualified,
string|null $alias = null,
string|null $escapeChar = null
): string;Prepares column for this RDBMS
prepareQualified()
protected function prepareQualified(
string $column,
string|null $domain = null,
string|null $escapeChar = null
): string;Prepares qualified for this RDBMS
prepareTable()
protected function prepareTable(
string $table,
string|null $schema = null,
string|null $alias = null,
string|null $escapeChar = null
): string;Prepares table for this RDBMS
Db\DialectInterface
InterfaceSource on GitHubPhalcon\Db\DialectInterface
Phalcon\Contracts\Db\DialectPhalcon\Db\DialectInterface
Uses Phalcon\Contracts\Db\Dialect
Db\Dialect\Mysql
ClassSource on GitHubGenerates database specific SQL for the MySQL RDBMS
Phalcon\Db\DialectPhalcon\Db\Dialect\Mysql
Uses Phalcon\Db\CheckInterface · Phalcon\Db\Column · Phalcon\Db\ColumnInterface · Phalcon\Db\Dialect · Phalcon\Db\DialectInterface · Phalcon\Db\Exception · Phalcon\Db\Exceptions\MissingDefinitionKey · Phalcon\Db\Exceptions\MysqlOnConflictNotSupported · Phalcon\Db\Exceptions\UnrecognizedDataType · Phalcon\Db\IndexInterface · Phalcon\Db\RawValue · Phalcon\Db\ReferenceInterface
Method Summary
publicstringaddCheck(string$tableName,string$schemaName,CheckInterface$check)Generates SQL to add a CHECK constraint to an existing table.publicstringaddColumn(string$tableName,string$schemaName,ColumnInterface$column)Generates SQL to add a column to a tablepublicstringaddForeignKey(string$tableName,string$schemaName,ReferenceInterface$reference)Generates SQL to add an index to a tablepublicstringaddIndex(string$tableName,string$schemaName,IndexInterface$index)Generates SQL to add an index to a tablepublicstringaddPrimaryKey(string$tableName,string$schemaName,IndexInterface$index)Generates SQL to add the primary key to a tablepublicstringcreateTable(string$tableName,string$schemaName,array$definition)Generates SQL to create a tablepublicstringcreateView(string$viewName,array$definition,string|null$schemaName = null)Generates SQL to create a viewpublicstringdescribeColumns(string$table,string|null$schema = null)Generates SQL describing a tablepublicstringdescribeIndexes(string$table,string|null$schema = null)Generates SQL to query indexes on a tablepublicstringdescribeReferences(string$table,string|null$schema = null)Generates SQL to query foreign keys on a tablepublicstringdropCheck(string$tableName,string$schemaName,string$checkName)Generates SQL to delete a CHECK constraint from a tablepublicstringdropColumn(string$tableName,string$schemaName,string$columnName)Generates SQL to delete a column from a tablepublicstringdropForeignKey(string$tableName,string$schemaName,string$referenceName)Generates SQL to delete a foreign key from a tablepublicstringdropIndex(string$tableName,string$schemaName,string$indexName)Generates SQL to delete an index from a tablepublicstringdropPrimaryKey(string$tableName,string$schemaName)Generates SQL to delete primary key from a tablepublicstringdropTable(string$tableName,string|null$schemaName = null,bool$ifExists = true)Generates SQL to drop a tablepublicstringdropView(string$viewName,string|null$schemaName = null,bool$ifExists = true)Generates SQL to drop a viewpublicstringgetColumnDefinition( ColumnInterface$column )Gets the column name in MySQLpublicstringgetForeignKeyChecks()Generates SQL to check DB parameter FOREIGN_KEY_CHECKS.publicstringlistTables( string|null$schemaName = null )List all tables in databasepublicstringlistViews( string|null$schemaName = null )Generates the SQL to list all views of a schema or userpublicstringmodifyColumn(string$tableName,string$schemaName,ColumnInterface$column,ColumnInterface|null$currentColumn = null)Generates SQL to modify a column in a tablepublicstringonConflictUpdate(string$sqlQuery,array$conflictColumns,array$updateColumns)MySQL does not support the SQL-standard ON CONFLICT DO UPDATEpublicstringsharedLock(string$sqlQuery,string$modifier = "")Returns a SQL modified with a LOCK IN SHARE MODE clause. The modifierpublicboolsupportsOnConflictUpdate()MySQL does not support the SQL-standard ON CONFLICT (…) DO UPDATEpublicstringtableExists(string$tableName,string|null$schemaName = null)Generates SQL checking for the existence of a schema.tablepublicstringtableOptions(string$table,string|null$schema = null)Generates the SQL to describe the table creation optionspublicstringtruncateTable(string$tableName,string$schemaName)Generates SQL to truncate a tablepublicstringviewExists(string$viewName,string|null$schemaName = null)Generates SQL checking for the existence of a schema.viewprotectedstringgetTableOptions( array$definition )Generates SQL to add the table creation optionsProperties
protectedstring$escapeChar = "`"protectedarray$supportedOperators = […]Methods
addCheck()
public function addCheck(
string $tableName,
string $schemaName,
CheckInterface $check
): string;Generates SQL to add a CHECK constraint to an existing table. Enforced by MySQL 8.0.16+.
addColumn()
public function addColumn(
string $tableName,
string $schemaName,
ColumnInterface $column
): string;Generates SQL to add a column to a table
addForeignKey()
public function addForeignKey(
string $tableName,
string $schemaName,
ReferenceInterface $reference
): string;Generates SQL to add an index to a table
addIndex()
public function addIndex(
string $tableName,
string $schemaName,
IndexInterface $index
): string;Generates SQL to add an index to a table
addPrimaryKey()
public function addPrimaryKey(
string $tableName,
string $schemaName,
IndexInterface $index
): string;Generates SQL to add the primary key to a table
createTable()
public function createTable(
string $tableName,
string $schemaName,
array $definition
): string;Generates SQL to create a table
createView()
public function createView(
string $viewName,
array $definition,
string|null $schemaName = null
): string;Generates SQL to create a view
describeColumns()
public function describeColumns(
string $table,
string|null $schema = null
): string;Generates SQL describing a table
print_r(
$dialect->describeColumns("posts")
);describeIndexes()
public function describeIndexes(
string $table,
string|null $schema = null
): string;Generates SQL to query indexes on a table
describeReferences()
public function describeReferences(
string $table,
string|null $schema = null
): string;Generates SQL to query foreign keys on a table
dropCheck()
public function dropCheck(
string $tableName,
string $schemaName,
string $checkName
): string;Generates SQL to delete a CHECK constraint from a table
dropColumn()
public function dropColumn(
string $tableName,
string $schemaName,
string $columnName
): string;Generates SQL to delete a column from a table
dropForeignKey()
public function dropForeignKey(
string $tableName,
string $schemaName,
string $referenceName
): string;Generates SQL to delete a foreign key from a table
dropIndex()
public function dropIndex(
string $tableName,
string $schemaName,
string $indexName
): string;Generates SQL to delete an index from a table
dropPrimaryKey()
public function dropPrimaryKey(
string $tableName,
string $schemaName
): string;Generates SQL to delete primary key from a table
dropTable()
public function dropTable(
string $tableName,
string|null $schemaName = null,
bool $ifExists = true
): string;Generates SQL to drop a table
dropView()
public function dropView(
string $viewName,
string|null $schemaName = null,
bool $ifExists = true
): string;Generates SQL to drop a view
getColumnDefinition()
public function getColumnDefinition( ColumnInterface $column ): string;Gets the column name in MySQL
getForeignKeyChecks()
public function getForeignKeyChecks(): string;Generates SQL to check DB parameter FOREIGN_KEY_CHECKS.
listTables()
public function listTables( string|null $schemaName = null ): string;List all tables in database
print_r(
$dialect->listTables("blog")
);listViews()
public function listViews( string|null $schemaName = null ): string;Generates the SQL to list all views of a schema or user
modifyColumn()
public function modifyColumn(
string $tableName,
string $schemaName,
ColumnInterface $column,
ColumnInterface|null $currentColumn = null
): string;Generates SQL to modify a column in a table
onConflictUpdate()
public function onConflictUpdate(
string $sqlQuery,
array $conflictColumns,
array $updateColumns
): string;MySQL does not support the SQL-standard ON CONFLICT DO UPDATE
upsert syntax - it has its own INSERT ... ON DUPLICATE KEY UPDATE
which requires PHQL grammar work (deferred). The base helper is
overridden here to throw, preventing accidental emission of invalid
SQL on MySQL connections.
sharedLock()
public function sharedLock(
string $sqlQuery,
string $modifier = ""
): string;Returns a SQL modified with a LOCK IN SHARE MODE clause. The modifier
argument is accepted for signature parity with the contract but is
silently ignored on MySQL - its legacy LOCK IN SHARE MODE syntax has
no NOWAIT / SKIP LOCKED variant. Callers needing those modifiers
should target PostgreSQL or stay on forUpdate().
$sql = $dialect->sharedLock("SELECT * FROM co_invoices");
echo $sql; // SELECT * FROM co_invoices LOCK IN SHARE MODEsupportsOnConflictUpdate()
public function supportsOnConflictUpdate(): bool;MySQL does not support the SQL-standard ON CONFLICT (...) DO UPDATE
upsert clause; onConflictUpdate() throws.
tableExists()
public function tableExists(
string $tableName,
string|null $schemaName = null
): string;Generates SQL checking for the existence of a schema.table
echo $dialect->tableExists("posts", "blog");
echo $dialect->tableExists("posts");tableOptions()
public function tableOptions(
string $table,
string|null $schema = null
): string;Generates the SQL to describe the table creation options
truncateTable()
public function truncateTable(
string $tableName,
string $schemaName
): string;Generates SQL to truncate a table
viewExists()
public function viewExists(
string $viewName,
string|null $schemaName = null
): string;Generates SQL checking for the existence of a schema.view
getTableOptions()
protected function getTableOptions( array $definition ): string;Generates SQL to add the table creation options
Db\Dialect\Postgresql
ClassSource on GitHubGenerates database specific SQL for the PostgreSQL RDBMS
Phalcon\Db\DialectPhalcon\Db\Dialect\Postgresql
Uses Phalcon\Db\CheckInterface · Phalcon\Db\Column · Phalcon\Db\ColumnInterface · Phalcon\Db\Dialect · Phalcon\Db\DialectInterface · Phalcon\Db\Exception · Phalcon\Db\Exceptions\MissingDefinitionKey · Phalcon\Db\Exceptions\ReturningRequiresColumn · Phalcon\Db\Exceptions\UnrecognizedDataType · Phalcon\Db\IndexInterface · Phalcon\Db\RawValue · Phalcon\Db\ReferenceInterface
Method Summary
publicstringaddCheck(string$tableName,string$schemaName,CheckInterface$check)Generates SQL to add a CHECK constraint to an existing table.publicstringaddColumn(string$tableName,string$schemaName,ColumnInterface$column)Generates SQL to add a column to a tablepublicstringaddForeignKey(string$tableName,string$schemaName,ReferenceInterface$reference)Generates SQL to add an index to a tablepublicstringaddIndex(string$tableName,string$schemaName,IndexInterface$index)Generates SQL to add an index to a tablepublicstringaddPrimaryKey(string$tableName,string$schemaName,IndexInterface$index)Generates SQL to add the primary key to a tablepublicstringcreateMaterializedView(string$viewName,array$definition,string|null$schemaName = null)Generates SQL to create a materialized view.publicstringcreateTable(string$tableName,string$schemaName,array$definition)Generates SQL to create a tablepublicstringcreateView(string$viewName,array$definition,string|null$schemaName = null)Generates SQL to create a viewpublicstringdescribeColumns(string$table,string|null$schema = null)Generates SQL describing a tablepublicstringdescribeIndexes(string$table,string|null$schema = null)Generates SQL to query indexes on a tablepublicstringdescribeReferences(string$table,string|null$schema = null)Generates SQL to query foreign keys on a tablepublicstringdropCheck(string$tableName,string$schemaName,string$checkName)Generates SQL to delete a CHECK constraint from a tablepublicstringdropColumn(string$tableName,string$schemaName,string$columnName)Generates SQL to delete a column from a tablepublicstringdropForeignKey(string$tableName,string$schemaName,string$referenceName)Generates SQL to delete a foreign key from a tablepublicstringdropIndex(string$tableName,string$schemaName,string$indexName)Generates SQL to delete an index from a tablepublicstringdropMaterializedView(string$viewName,string|null$schemaName = null,bool$ifExists = true)Generates SQL to drop a materialized view.publicstringdropPrimaryKey(string$tableName,string$schemaName)Generates SQL to delete primary key from a tablepublicstringdropTable(string$tableName,string|null$schemaName = null,bool$ifExists = true)Generates SQL to drop a tablepublicstringdropView(string$viewName,string|null$schemaName = null,bool$ifExists = true)Generates SQL to drop a viewpublicstringgetColumnDefinition( ColumnInterface$column )Gets the column name in PostgreSQLpublicstringlistTables( string|null$schemaName = null )List all tables in databasepublicstringlistViews( string|null$schemaName = null )Generates the SQL to list all views of a schema or userpublicstringmodifyColumn(string$tableName,string$schemaName,ColumnInterface$column,ColumnInterface|null$currentColumn = null)Generates SQL to modify a column in a tablepublicstringrefreshMaterializedView(string$viewName,string|null$schemaName = null,bool$concurrent = false)Generates SQL to refresh a materialized view. When concurrent ispublicstringreturning(string$sqlQuery,array$columns)Appends a RETURNING clause to the supplied INSERT/UPDATE/DELETEpublicstringsharedLock(string$sqlQuery,string$modifier = "")Returns a SQL modified with a FOR SHARE clause - PostgreSQL'spublicboolsupportsMaterializedViews()PostgreSQL supports materialized views (CREATE MATERIALIZED VIEW).publicboolsupportsReturning()PostgreSQL supports the RETURNING clause.publicstringtableExists(string$tableName,string|null$schemaName = null)Generates SQL checking for the existence of a schema.tablepublicstringtableOptions(string$table,string|null$schema = null)Generates the SQL to describe the table creation optionspublicstringtruncateTable(string$tableName,string$schemaName)Generates SQL to truncate a tablepublicstringviewExists(string$viewName,string|null$schemaName = null)Generates SQL checking for the existence of a schema.viewprotectedstringcastDefault( ColumnInterface$column )protectedstringgetTableOptions( array$definition )Properties
protectedstring$escapeChar = """protectedarray$supportedOperators = […]Methods
addCheck()
public function addCheck(
string $tableName,
string $schemaName,
CheckInterface $check
): string;Generates SQL to add a CHECK constraint to an existing table.
addColumn()
public function addColumn(
string $tableName,
string $schemaName,
ColumnInterface $column
): string;Generates SQL to add a column to a table
addForeignKey()
public function addForeignKey(
string $tableName,
string $schemaName,
ReferenceInterface $reference
): string;Generates SQL to add an index to a table
addIndex()
public function addIndex(
string $tableName,
string $schemaName,
IndexInterface $index
): string;Generates SQL to add an index to a table
addPrimaryKey()
public function addPrimaryKey(
string $tableName,
string $schemaName,
IndexInterface $index
): string;Generates SQL to add the primary key to a table
createMaterializedView()
public function createMaterializedView(
string $viewName,
array $definition,
string|null $schemaName = null
): string;Generates SQL to create a materialized view.
createTable()
public function createTable(
string $tableName,
string $schemaName,
array $definition
): string;Generates SQL to create a table
createView()
public function createView(
string $viewName,
array $definition,
string|null $schemaName = null
): string;Generates SQL to create a view
describeColumns()
public function describeColumns(
string $table,
string|null $schema = null
): string;Generates SQL describing a table
print_r(
$dialect->describeColumns("posts")
);describeIndexes()
public function describeIndexes(
string $table,
string|null $schema = null
): string;Generates SQL to query indexes on a table
describeReferences()
public function describeReferences(
string $table,
string|null $schema = null
): string;Generates SQL to query foreign keys on a table
dropCheck()
public function dropCheck(
string $tableName,
string $schemaName,
string $checkName
): string;Generates SQL to delete a CHECK constraint from a table
dropColumn()
public function dropColumn(
string $tableName,
string $schemaName,
string $columnName
): string;Generates SQL to delete a column from a table
dropForeignKey()
public function dropForeignKey(
string $tableName,
string $schemaName,
string $referenceName
): string;Generates SQL to delete a foreign key from a table
dropIndex()
public function dropIndex(
string $tableName,
string $schemaName,
string $indexName
): string;Generates SQL to delete an index from a table
dropMaterializedView()
public function dropMaterializedView(
string $viewName,
string|null $schemaName = null,
bool $ifExists = true
): string;Generates SQL to drop a materialized view.
dropPrimaryKey()
public function dropPrimaryKey(
string $tableName,
string $schemaName
): string;Generates SQL to delete primary key from a table
dropTable()
public function dropTable(
string $tableName,
string|null $schemaName = null,
bool $ifExists = true
): string;Generates SQL to drop a table
dropView()
public function dropView(
string $viewName,
string|null $schemaName = null,
bool $ifExists = true
): string;Generates SQL to drop a view
getColumnDefinition()
public function getColumnDefinition( ColumnInterface $column ): string;Gets the column name in PostgreSQL
listTables()
public function listTables( string|null $schemaName = null ): string;List all tables in database
print_r(
$dialect->listTables("blog")
);listViews()
public function listViews( string|null $schemaName = null ): string;Generates the SQL to list all views of a schema or user
modifyColumn()
public function modifyColumn(
string $tableName,
string $schemaName,
ColumnInterface $column,
ColumnInterface|null $currentColumn = null
): string;Generates SQL to modify a column in a table
refreshMaterializedView()
public function refreshMaterializedView(
string $viewName,
string|null $schemaName = null,
bool $concurrent = false
): string;Generates SQL to refresh a materialized view. When concurrent is
true, emits REFRESH MATERIALIZED VIEW CONCURRENTLY ... (avoids
blocking concurrent SELECTs; requires a unique index on the view).
returning()
public function returning(
string $sqlQuery,
array $columns
): string;Appends a RETURNING clause to the supplied INSERT/UPDATE/DELETE
statement. Pass ["*"] for RETURNING *, or a list of column names.
sharedLock()
public function sharedLock(
string $sqlQuery,
string $modifier = ""
): string;Returns a SQL modified with a FOR SHARE clause - PostgreSQL’s
equivalent of MySQL’s LOCK IN SHARE MODE. The optional modifier
appends a row-lock disposition keyword (pass Dialect::LOCK_NOWAIT
or Dialect::LOCK_SKIP_LOCKED).
echo $dialect->sharedLock("SELECT * FROM co_invoices");
// SELECT * FROM co_invoices FOR SHARE
echo $dialect->sharedLock(
"SELECT * FROM co_invoices",
Dialect::LOCK_NOWAIT
);
// SELECT * FROM co_invoices FOR SHARE NOWAITsupportsMaterializedViews()
public function supportsMaterializedViews(): bool;PostgreSQL supports materialized views (CREATE MATERIALIZED VIEW).
supportsReturning()
public function supportsReturning(): bool;PostgreSQL supports the RETURNING clause.
tableExists()
public function tableExists(
string $tableName,
string|null $schemaName = null
): string;Generates SQL checking for the existence of a schema.table
echo $dialect->tableExists("posts", "blog");
echo $dialect->tableExists("posts");tableOptions()
public function tableOptions(
string $table,
string|null $schema = null
): string;Generates the SQL to describe the table creation options
truncateTable()
public function truncateTable(
string $tableName,
string $schemaName
): string;Generates SQL to truncate a table
viewExists()
public function viewExists(
string $viewName,
string|null $schemaName = null
): string;Generates SQL checking for the existence of a schema.view
castDefault()
protected function castDefault( ColumnInterface $column ): string;getTableOptions()
protected function getTableOptions( array $definition ): string;Db\Dialect\Sqlite
ClassSource on GitHubGenerates database specific SQL for the SQLite RDBMS
Phalcon\Db\DialectPhalcon\Db\Dialect\Sqlite
Uses Phalcon\Db\CheckInterface · Phalcon\Db\Column · Phalcon\Db\ColumnInterface · Phalcon\Db\Dialect · Phalcon\Db\DialectInterface · Phalcon\Db\Exception · Phalcon\Db\Exceptions\MissingDefinitionKey · Phalcon\Db\Exceptions\ReturningRequiresColumn · Phalcon\Db\Exceptions\SqliteAlterCheckNotSupported · Phalcon\Db\Exceptions\SqliteAlterColumnNotSupported · Phalcon\Db\Exceptions\SqliteAlterForeignKeyNotSupported · Phalcon\Db\Exceptions\SqliteAlterPrimaryKeyNotSupported · Phalcon\Db\Exceptions\SqliteDropCheckNotSupported · Phalcon\Db\Exceptions\SqliteDropForeignKeyNotSupported · Phalcon\Db\Exceptions\SqliteDropPrimaryKeyNotSupported · Phalcon\Db\Exceptions\UnrecognizedDataType · Phalcon\Db\IndexInterface · Phalcon\Db\RawValue · Phalcon\Db\ReferenceInterface
Method Summary
publicstringaddCheck(string$tableName,string$schemaName,CheckInterface$check)SQLite cannot ALTER an existing table to add a CHECK constraint;publicstringaddColumn(string$tableName,string$schemaName,ColumnInterface$column)Generates SQL to add a column to a tablepublicstringaddForeignKey(string$tableName,string$schemaName,ReferenceInterface$reference)Generates SQL to add an index to a tablepublicstringaddIndex(string$tableName,string$schemaName,IndexInterface$index)Generates SQL to add an index to a tablepublicstringaddPrimaryKey(string$tableName,string$schemaName,IndexInterface$index)Generates SQL to add the primary key to a tablepublicstringcreateTable(string$tableName,string$schemaName,array$definition)Generates SQL to create a tablepublicstringcreateView(string$viewName,array$definition,string|null$schemaName = null)Generates SQL to create a viewpublicstringdescribeColumns(string$table,string|null$schema = null)Generates SQL describing a tablepublicstringdescribeIndex( string$index )Generates SQL to query indexes detail on a tablepublicstringdescribeIndexes(string$table,string|null$schema = null)Generates SQL to query indexes on a tablepublicstringdescribeReferences(string$table,string|null$schema = null)Generates SQL to query foreign keys on a tablepublicstringdropCheck(string$tableName,string$schemaName,string$checkName)SQLite cannot DROP a CHECK constraint from an existing table.publicstringdropColumn(string$tableName,string$schemaName,string$columnName)Generates SQL to delete a column from a table.publicstringdropForeignKey(string$tableName,string$schemaName,string$referenceName)Generates SQL to delete a foreign key from a tablepublicstringdropIndex(string$tableName,string$schemaName,string$indexName)Generates SQL to delete an index from a tablepublicstringdropPrimaryKey(string$tableName,string$schemaName)Generates SQL to delete primary key from a tablepublicstringdropTable(string$tableName,string|null$schemaName = null,bool$ifExists = true)Generates SQL to drop a tablepublicstringdropView(string$viewName,string|null$schemaName = null,bool$ifExists = true)Generates SQL to drop a viewpublicstringforUpdate(string$sqlQuery,string$modifier = "")Returns a SQL modified with a FOR UPDATE clause. SQLite has nopublicstringgetColumnDefinition( ColumnInterface$column )Gets the column name in SQLitepublicstringlistIndexesSql(string$table,string|null$schema = null,string|null$keyName = null)Generates the SQL to get query list of indexespublicstringlistTables( string|null$schemaName = null )List all tables in databasepublicstringlistViews( string|null$schemaName = null )Generates the SQL to list all views of a schema or userpublicstringmodifyColumn(string$tableName,string$schemaName,ColumnInterface$column,ColumnInterface|null$currentColumn = null)Generates SQL to modify a column in a tablepublicstringreturning(string$sqlQuery,array$columns)Appends a RETURNING clause to the supplied INSERT/UPDATE/DELETEpublicstringsharedLock(string$sqlQuery,string$modifier = "")SQLite has no row-level shared-lock construct, so the original querypublicboolsupportsAlterTable()SQLite cannot modify existing columns or add/drop foreign keys, primarypublicboolsupportsReturning()SQLite (3.35+) supports the RETURNING clause.publicstringtableExists(string$tableName,string|null$schemaName = null)Generates SQL checking for the existence of a schema.tablepublicstringtableOptions(string$table,string|null$schema = null)Generates the SQL to describe the table creation optionspublicstringtruncateTable(string$tableName,string$schemaName)Generates SQL to truncate a tablepublicstringviewExists(string$viewName,string|null$schemaName = null)Generates SQL checking for the existence of a schema.viewProperties
protectedstring$escapeChar = """protectedarray$supportedOperators = […]Methods
addCheck()
public function addCheck(
string $tableName,
string $schemaName,
CheckInterface $check
): string;SQLite cannot ALTER an existing table to add a CHECK constraint; the constraint must be declared at CREATE TABLE time.
addColumn()
public function addColumn(
string $tableName,
string $schemaName,
ColumnInterface $column
): string;Generates SQL to add a column to a table
addForeignKey()
public function addForeignKey(
string $tableName,
string $schemaName,
ReferenceInterface $reference
): string;Generates SQL to add an index to a table
addIndex()
public function addIndex(
string $tableName,
string $schemaName,
IndexInterface $index
): string;Generates SQL to add an index to a table
addPrimaryKey()
public function addPrimaryKey(
string $tableName,
string $schemaName,
IndexInterface $index
): string;Generates SQL to add the primary key to a table
createTable()
public function createTable(
string $tableName,
string $schemaName,
array $definition
): string;Generates SQL to create a table
createView()
public function createView(
string $viewName,
array $definition,
string|null $schemaName = null
): string;Generates SQL to create a view
describeColumns()
public function describeColumns(
string $table,
string|null $schema = null
): string;Generates SQL describing a table
print_r(
$dialect->describeColumns("posts")
);describeIndex()
public function describeIndex( string $index ): string;Generates SQL to query indexes detail on a table
describeIndexes()
public function describeIndexes(
string $table,
string|null $schema = null
): string;Generates SQL to query indexes on a table
describeReferences()
public function describeReferences(
string $table,
string|null $schema = null
): string;Generates SQL to query foreign keys on a table
dropCheck()
public function dropCheck(
string $tableName,
string $schemaName,
string $checkName
): string;SQLite cannot DROP a CHECK constraint from an existing table.
dropColumn()
public function dropColumn(
string $tableName,
string $schemaName,
string $columnName
): string;Generates SQL to delete a column from a table.
SQLite 3.35+ supports ALTER TABLE ... DROP COLUMN ... directly. On
older versions the server rejects the statement at execution time;
cphalcon no longer pre-empts that rejection at the dialect level so
callers on 3.35+ can use the feature.
dropForeignKey()
public function dropForeignKey(
string $tableName,
string $schemaName,
string $referenceName
): string;Generates SQL to delete a foreign key from a table
dropIndex()
public function dropIndex(
string $tableName,
string $schemaName,
string $indexName
): string;Generates SQL to delete an index from a table
dropPrimaryKey()
public function dropPrimaryKey(
string $tableName,
string $schemaName
): string;Generates SQL to delete primary key from a table
dropTable()
public function dropTable(
string $tableName,
string|null $schemaName = null,
bool $ifExists = true
): string;Generates SQL to drop a table
dropView()
public function dropView(
string $viewName,
string|null $schemaName = null,
bool $ifExists = true
): string;Generates SQL to drop a view
forUpdate()
public function forUpdate(
string $sqlQuery,
string $modifier = ""
): string;Returns a SQL modified with a FOR UPDATE clause. SQLite has no
row-level locking, so the original query is returned unchanged
regardless of the modifier argument (NOWAIT / SKIP LOCKED are
silently ignored).
getColumnDefinition()
public function getColumnDefinition( ColumnInterface $column ): string;Gets the column name in SQLite
listIndexesSql()
public function listIndexesSql(
string $table,
string|null $schema = null,
string|null $keyName = null
): string;Generates the SQL to get query list of indexes
print_r(
$dialect->listIndexesSql("blog")
);listTables()
public function listTables( string|null $schemaName = null ): string;List all tables in database
print_r(
$dialect->listTables("blog")
);listViews()
public function listViews( string|null $schemaName = null ): string;Generates the SQL to list all views of a schema or user
modifyColumn()
public function modifyColumn(
string $tableName,
string $schemaName,
ColumnInterface $column,
ColumnInterface|null $currentColumn = null
): string;Generates SQL to modify a column in a table
returning()
public function returning(
string $sqlQuery,
array $columns
): string;Appends a RETURNING clause to the supplied INSERT/UPDATE/DELETE
statement. Supported by SQLite 3.35+. Pass ["*"] for RETURNING *,
or a list of column names.
sharedLock()
public function sharedLock(
string $sqlQuery,
string $modifier = ""
): string;SQLite has no row-level shared-lock construct, so the original query
is returned unchanged regardless of the modifier argument.
supportsAlterTable()
public function supportsAlterTable(): bool;SQLite cannot modify existing columns or add/drop foreign keys, primary
keys, or check constraints through ALTER TABLE; those operations throw
a dedicated Sqlite*NotSupported exception.
supportsReturning()
public function supportsReturning(): bool;SQLite (3.35+) supports the RETURNING clause.
tableExists()
public function tableExists(
string $tableName,
string|null $schemaName = null
): string;Generates SQL checking for the existence of a schema.table
echo $dialect->tableExists("posts", "blog");
echo $dialect->tableExists("posts");tableOptions()
public function tableOptions(
string $table,
string|null $schema = null
): string;Generates the SQL to describe the table creation options
truncateTable()
public function truncateTable(
string $tableName,
string $schemaName
): string;Generates SQL to truncate a table
viewExists()
public function viewExists(
string $viewName,
string|null $schemaName = null
): string;Generates SQL checking for the existence of a schema.view
Db\Enum
ClassSource on GitHubConstants for Phalcon\Db
Phalcon\Db\Enum
Constants
intFETCH_ASSOC = \PDO::FETCH_ASSOCintFETCH_BOTH = \PDO::FETCH_BOTHintFETCH_BOUND = \PDO::FETCH_BOUNDintFETCH_CLASS = \PDO::FETCH_CLASSintFETCH_CLASSTYPE = \PDO::FETCH_CLASSTYPEintFETCH_COLUMN = \PDO::FETCH_COLUMNintFETCH_DEFAULT = \PDO::FETCH_DEFAULTintFETCH_FUNC = \PDO::FETCH_FUNCintFETCH_GROUP = \PDO::FETCH_GROUPintFETCH_INTO = \PDO::FETCH_INTOintFETCH_KEY_PAIR = \PDO::FETCH_KEY_PAIRintFETCH_LAZY = \PDO::FETCH_LAZYintFETCH_NAMED = \PDO::FETCH_NAMEDintFETCH_NUM = \PDO::FETCH_NUMintFETCH_OBJ = \PDO::FETCH_OBJintFETCH_ORI_NEXT = \PDO::FETCH_ORI_NEXTintFETCH_PROPS_LATE = \PDO::FETCH_PROPS_LATEintFETCH_SERIALIZE = \PDO::FETCH_SERIALIZEintFETCH_UNIQUE = \PDO::FETCH_UNIQUEDb\Exception
ClassSource on GitHubExceptions thrown in Phalcon\Db will use this class
\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\CannotInsertWithoutDataPhalcon\Db\Exceptions\CannotPrepareStatementPhalcon\Db\Exceptions\CheckExpressionRequiredPhalcon\Db\Exceptions\ColumnTypeRejectsAutoIncrementPhalcon\Db\Exceptions\ColumnTypeRejectsScalePhalcon\Db\Exceptions\ColumnTypeRequiredPhalcon\Db\Exceptions\ConflictTargetColumnRequiredPhalcon\Db\Exceptions\ConflictUpdateColumnRequiredPhalcon\Db\Exceptions\ForeignKeyColumnsRequiredPhalcon\Db\Exceptions\GeneratedAutoIncrementConflictPhalcon\Db\Exceptions\GeneratedDefaultConflictPhalcon\Db\Exceptions\IncompleteBindTypesPhalcon\Db\Exceptions\InvalidBindParameterPhalcon\Db\Exceptions\InvalidCheckExpressionPhalcon\Db\Exceptions\InvalidDialectClassPhalcon\Db\Exceptions\InvalidGenerationExpressionPhalcon\Db\Exceptions\InvalidGroupByExpressionPhalcon\Db\Exceptions\InvalidIndexColumnsPhalcon\Db\Exceptions\InvalidIndexDirectionsPhalcon\Db\Exceptions\InvalidIndexWherePhalcon\Db\Exceptions\InvalidListExpressionPhalcon\Db\Exceptions\InvalidOrderByExpressionPhalcon\Db\Exceptions\InvalidSqlExpressionPhalcon\Db\Exceptions\InvalidSqlExpressionTypePhalcon\Db\Exceptions\InvalidUnaryExpressionPhalcon\Db\Exceptions\InvalidWhereConditionsPhalcon\Db\Exceptions\InvalidWkbPhalcon\Db\Exceptions\MatchedParameterNotFoundPhalcon\Db\Exceptions\MaterializedViewsNotSupportedPhalcon\Db\Exceptions\MissingDefinitionKeyPhalcon\Db\Exceptions\MissingForeignKeyChecksPhalcon\Db\Exceptions\MissingSqliteDatabasePhalcon\Db\Exceptions\MysqlOnConflictNotSupportedPhalcon\Db\Exceptions\NestedTransactionChangeBlockedPhalcon\Db\Exceptions\NoActiveTransactionPhalcon\Db\Exceptions\ReferencedColumnCountMismatchPhalcon\Db\Exceptions\ReferencedColumnsRequiredPhalcon\Db\Exceptions\ReferencedTableRequiredPhalcon\Db\Exceptions\ReturningNotSupportedPhalcon\Db\Exceptions\ReturningRequiresColumnPhalcon\Db\Exceptions\SavepointsNotSupportedPhalcon\Db\Exceptions\SqliteAlterCheckNotSupportedPhalcon\Db\Exceptions\SqliteAlterColumnNotSupportedPhalcon\Db\Exceptions\SqliteAlterForeignKeyNotSupportedPhalcon\Db\Exceptions\SqliteAlterPrimaryKeyNotSupportedPhalcon\Db\Exceptions\SqliteDropCheckNotSupportedPhalcon\Db\Exceptions\SqliteDropForeignKeyNotSupportedPhalcon\Db\Exceptions\SqliteDropPrimaryKeyNotSupportedPhalcon\Db\Exceptions\TableMustHaveColumnPhalcon\Db\Exceptions\UnrecognizedDataTypePhalcon\Db\Exceptions\UnsupportedOperatorPhalcon\Db\Exceptions\UpdateFieldCountMismatch
Db\Exceptions\CannotInsertWithoutData
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\CannotInsertWithoutData
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct( string $table );Db\Exceptions\CannotPrepareStatement
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\CannotPrepareStatement
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\CheckExpressionRequired
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\CheckExpressionRequired
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\ColumnTypeRejectsAutoIncrement
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\ColumnTypeRejectsAutoIncrement
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\ColumnTypeRejectsScale
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\ColumnTypeRejectsScale
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\ColumnTypeRequired
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\ColumnTypeRequired
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\ConflictTargetColumnRequired
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\ConflictTargetColumnRequired
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\ConflictUpdateColumnRequired
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\ConflictUpdateColumnRequired
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\ForeignKeyColumnsRequired
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\ForeignKeyColumnsRequired
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\GeneratedAutoIncrementConflict
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\GeneratedAutoIncrementConflict
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\GeneratedDefaultConflict
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\GeneratedDefaultConflict
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\IncompleteBindTypes
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\IncompleteBindTypes
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidBindParameter
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidBindParameter
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidCheckExpression
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidCheckExpression
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidDialectClass
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidDialectClass
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct( string $className );Db\Exceptions\InvalidGenerationExpression
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidGenerationExpression
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidGroupByExpression
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidGroupByExpression
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidIndexColumns
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidIndexColumns
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidIndexDirections
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidIndexDirections
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidIndexWhere
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidIndexWhere
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidListExpression
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidListExpression
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidOrderByExpression
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidOrderByExpression
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidSqlExpression
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidSqlExpression
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidSqlExpressionType
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidSqlExpressionType
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct( string $type );Db\Exceptions\InvalidUnaryExpression
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidUnaryExpression
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidWhereConditions
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidWhereConditions
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\InvalidWkb
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\InvalidWkb
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct( string $reason );Db\Exceptions\MatchedParameterNotFound
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\MatchedParameterNotFound
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\MaterializedViewsNotSupported
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\MaterializedViewsNotSupported
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\MissingDefinitionKey
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\MissingDefinitionKey
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct( string $key );Db\Exceptions\MissingForeignKeyChecks
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\MissingForeignKeyChecks
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\MissingSqliteDatabase
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\MissingSqliteDatabase
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\MysqlOnConflictNotSupported
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\MysqlOnConflictNotSupported
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\NestedTransactionChangeBlocked
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\NestedTransactionChangeBlocked
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\NoActiveTransaction
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\NoActiveTransaction
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\ReferencedColumnCountMismatch
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\ReferencedColumnCountMismatch
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\ReferencedColumnsRequired
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\ReferencedColumnsRequired
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\ReferencedTableRequired
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\ReferencedTableRequired
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\ReturningNotSupported
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\ReturningNotSupported
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\ReturningRequiresColumn
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\ReturningRequiresColumn
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\SavepointsNotSupported
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\SavepointsNotSupported
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\SqliteAlterCheckNotSupported
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\SqliteAlterCheckNotSupported
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\SqliteAlterColumnNotSupported
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\SqliteAlterColumnNotSupported
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\SqliteAlterForeignKeyNotSupported
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\SqliteAlterForeignKeyNotSupported
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\SqliteAlterPrimaryKeyNotSupported
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\SqliteAlterPrimaryKeyNotSupported
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\SqliteDropCheckNotSupported
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\SqliteDropCheckNotSupported
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\SqliteDropForeignKeyNotSupported
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\SqliteDropForeignKeyNotSupported
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\SqliteDropPrimaryKeyNotSupported
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\SqliteDropPrimaryKeyNotSupported
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\TableMustHaveColumn
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\TableMustHaveColumn
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Exceptions\UnrecognizedDataType
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\UnrecognizedDataType
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct(
string $dialect,
string $column
);Db\Exceptions\UnsupportedOperator
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\UnsupportedOperator
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct( string $operator );Db\Exceptions\UpdateFieldCountMismatch
ClassSource on GitHub\ExceptionPhalcon\Db\ExceptionPhalcon\Db\Exceptions\UpdateFieldCountMismatch
Uses Phalcon\Db\Exception
Method Summary
Methods
__construct()
public function __construct();Db\Geometry\AbstractGeometry
AbstractSource on GitHubPhalcon\Db\Geometry\AbstractGeometry- implementsPhalcon\Db\Geometry\GeometryInterface
Method Summary
Properties
protectedint$srid = 0Methods
__toString()
public function __toString(): string;getSrid()
public function getSrid(): int;getType()
abstract public function getType(): int;toWkt()
abstract public function toWkt(): string;Db\Geometry\GeometryCollection
ClassSource on GitHubPhalcon\Db\Geometry\AbstractGeometryPhalcon\Db\Geometry\GeometryCollection
Uses Phalcon\Db\Column
Method Summary
public__construct(array$geometries,int$srid = 0)publicarraygetGeometries()publicintgetType()publicstringtoWkt()Properties
protectedarray$geometriesMethods
__construct()
public function __construct(
array $geometries,
int $srid = 0
);getGeometries()
public function getGeometries(): array;getType()
public function getType(): int;toWkt()
public function toWkt(): string;Db\Geometry\GeometryInterface
InterfaceSource on GitHubPhalcon\Db\Geometry\GeometryInterface
Phalcon\Contracts\Db\Geometry\GeometryPhalcon\Db\Geometry\GeometryInterface
Uses Phalcon\Contracts\Db\Geometry\Geometry
Db\Geometry\LineString
ClassSource on GitHubPhalcon\Db\Geometry\AbstractGeometryPhalcon\Db\Geometry\LineString
Uses Phalcon\Db\Column
Method Summary
public__construct(array$points,int$srid = 0)publicarraygetPoints()publicintgetType()publicstringpointsWkt()publicstringtoWkt()Properties
protectedarray$pointsMethods
__construct()
public function __construct(
array $points,
int $srid = 0
);getPoints()
public function getPoints(): array;getType()
public function getType(): int;pointsWkt()
public function pointsWkt(): string;toWkt()
public function toWkt(): string;Db\Geometry\MultiLineString
ClassSource on GitHubPhalcon\Db\Geometry\AbstractGeometryPhalcon\Db\Geometry\MultiLineString
Uses Phalcon\Db\Column
Method Summary
public__construct(array$lineStrings,int$srid = 0)publicarraygetLineStrings()publicintgetType()publicstringtoWkt()Properties
protectedarray$lineStringsMethods
__construct()
public function __construct(
array $lineStrings,
int $srid = 0
);getLineStrings()
public function getLineStrings(): array;getType()
public function getType(): int;toWkt()
public function toWkt(): string;Db\Geometry\MultiPoint
ClassSource on GitHubPhalcon\Db\Geometry\AbstractGeometryPhalcon\Db\Geometry\MultiPoint
Uses Phalcon\Db\Column
Method Summary
public__construct(array$points,int$srid = 0)publicarraygetPoints()publicintgetType()publicstringtoWkt()Properties
protectedarray$pointsMethods
__construct()
public function __construct(
array $points,
int $srid = 0
);getPoints()
public function getPoints(): array;getType()
public function getType(): int;toWkt()
public function toWkt(): string;Db\Geometry\MultiPolygon
ClassSource on GitHubPhalcon\Db\Geometry\AbstractGeometryPhalcon\Db\Geometry\MultiPolygon
Uses Phalcon\Db\Column
Method Summary
public__construct(array$polygons,int$srid = 0)publicarraygetPolygons()publicintgetType()publicstringtoWkt()Properties
protectedarray$polygonsMethods
__construct()
public function __construct(
array $polygons,
int $srid = 0
);getPolygons()
public function getPolygons(): array;getType()
public function getType(): int;toWkt()
public function toWkt(): string;Db\Geometry\Point
ClassSource on GitHubPhalcon\Db\Geometry\AbstractGeometryPhalcon\Db\Geometry\Point
Uses Phalcon\Db\Column
Method Summary
public__construct(float$x,float$y,int$srid = 0)publicstringcoordsWkt()publicintgetType()publicfloatgetX()publicfloatgetY()publicstringtoWkt()Properties
protectedfloat$xprotectedfloat$yMethods
__construct()
public function __construct(
float $x,
float $y,
int $srid = 0
);coordsWkt()
public function coordsWkt(): string;getType()
public function getType(): int;getX()
public function getX(): float;getY()
public function getY(): float;toWkt()
public function toWkt(): string;Db\Geometry\Polygon
ClassSource on GitHubPhalcon\Db\Geometry\AbstractGeometryPhalcon\Db\Geometry\Polygon
Uses Phalcon\Db\Column
Method Summary
public__construct(array$rings,int$srid = 0)publicarraygetRings()publicintgetType()publicstringringsWkt()publicstringtoWkt()Properties
protectedarray$ringsMethods
__construct()
public function __construct(
array $rings,
int $srid = 0
);getRings()
public function getRings(): array;getType()
public function getType(): int;ringsWkt()
public function ringsWkt(): string;toWkt()
public function toWkt(): string;Db\Geometry\WkbParser
ClassSource on GitHubDecodes a spatial column value into a geometry value object.
Handles MySQL’s internal format (4-byte little-endian SRID prefix followed by standard OGC WKB) and PostGIS EWKB returned as a hex string. 2D only: any Z/M ordinates are read past and discarded.
Phalcon\Db\Geometry\WkbParser
Uses Phalcon\Db\Exceptions\InvalidWkb
Method Summary
publicGeometryInterfaceparse( string$raw )protectedintreadByte()protectedfloatreadDouble( bool$little )protectedGeometryInterfacereadGeometry( int$outerSrid )protectedPointreadPoint(bool$little,bool$hasZ,bool$hasM,int$srid)protectedarrayreadPointList(bool$little,bool$hasZ,bool$hasM)protectedarrayreadRingList(bool$little,bool$hasZ,bool$hasM)protectedintreadUint32( bool$little )protectedvoidskipExtraOrdinates(bool$little,bool$hasZ,bool$hasM)Properties
protectedstring$buffer = ""protectedint$length = 0protectedint$position = 0Methods
parse()
public function parse( string $raw ): GeometryInterface;readByte()
protected function readByte(): int;readDouble()
protected function readDouble( bool $little ): float;readGeometry()
protected function readGeometry( int $outerSrid ): GeometryInterface;readPoint()
protected function readPoint(
bool $little,
bool $hasZ,
bool $hasM,
int $srid
): Point;readPointList()
protected function readPointList(
bool $little,
bool $hasZ,
bool $hasM
): array;readRingList()
protected function readRingList(
bool $little,
bool $hasZ,
bool $hasM
): array;readUint32()
protected function readUint32( bool $little ): int;skipExtraOrdinates()
protected function skipExtraOrdinates(
bool $little,
bool $hasZ,
bool $hasM
): void;Db\Index
ClassSource on GitHubAllows to define indexes to be used on tables. Indexes are a common way to enhance database performance. An index allows the database server to find and retrieve specific rows much faster than it could do without an index.
The constructor accepts either the legacy positional form (a plain array
of column names) or a definition-array form (an associative array with a
columns key); the latter is the path used by features such as
invisible (MySQL 8.0+) and is the form that future per-index modifiers
will extend.
// Legacy positional form
$unique = new \Phalcon\Db\Index(
'column_UNIQUE',
[
'column',
],
'UNIQUE'
);
$primary = new \Phalcon\Db\Index(
'PRIMARY',
[
'column',
]
);
// Definition-array form (MySQL 8.0+ invisible index)
$hidden = new \Phalcon\Db\Index(
'idx_hidden',
[
'columns' => ['col1'],
'type' => '',
'invisible' => true,
]
);
$connection->addIndex("co_invoices", null, $unique);
$connection->addIndex("co_invoices", null, $primary);
$connection->addIndex("co_invoices", null, $hidden);Phalcon\Db\Index- implementsPhalcon\Db\IndexInterface
Uses Phalcon\Db\Exceptions\InvalidIndexColumns · Phalcon\Db\Exceptions\InvalidIndexDirections · Phalcon\Db\Exceptions\InvalidIndexWhere
Method Summary
public__construct(string$name,array$columnsOrDefinition,string$type = "")Phalcon\Db\Index constructor.publicarraygetColumns()Index columnspublicarraygetDirections()Returns the per-column sort directions array (ASC / DESC).publicstringgetName()Index namepublicstringgetType()Index typepublicstringgetWhere()Returns the partial-index WHERE predicate, or an empty string whenpublicboolisConcurrent()Whether the index is built CONCURRENTLY (PostgreSQL only). MySQLpublicboolisInvisible()Whether the index is declared INVISIBLE (MySQL 8.0+). InvisibleProperties
protectedarray$columnsIndex columnsprotectedbool$concurrent = falseWhether to build the index without taking a strong lock that blocks writes - emits CONCURRENTLY between INDEX and the index name on PostgreSQL (CREATE INDEX CONCURRENTLY name ON …). MySQL and SQLite have no equivalent and ignore the flag.protectedarray$directions = []Per-column sort directions (ASC / DESC). Empty array means "emit no per-column direction" - preserves the legacy plain (col1, col2) rendering. When populated, entries shorter than the columns list default to ASC for the missing positions.protectedbool$invisible = falseWhether the index is declared INVISIBLE (MySQL 8.0+). Invisible indexes are ignored by the optimizer - useful for testing what happens when an index is removed before actually dropping it. PostgreSQL and SQLite have no equivalent and ignore the flag.protectedstring$nameIndex nameprotectedstring$type = ""Index typeprotectedstring$where = ""Optional partial-index WHERE predicate. Supported by PostgreSQL and SQLite (CREATE INDEX … WHERE <expr>); MySQL has no partial-index concept and its dialect ignores this value. Empty string means no predicate.Methods
__construct()
public function __construct(
string $name,
array $columnsOrDefinition,
string $type = ""
);Phalcon\Db\Index constructor.
Accepts either the legacy positional form (name, columns, type) or a
definition-array form (name, ["columns" => [...], "type" => "...", "invisible" => true, ...]). Detection is based on the presence of a
columns key in the second argument; when present, the third
positional type argument is ignored in favor of the definition.
getColumns()
public function getColumns(): array;Index columns
getDirections()
public function getDirections(): array;Returns the per-column sort directions array (ASC / DESC).
Empty array means the index was declared without explicit per-column
directions and dialects emit the columns plainly. When populated,
entries are aligned with getColumns(); missing trailing positions
default to ASC at emission time.
getName()
public function getName(): string;Index name
getType()
public function getType(): string;Index type
getWhere()
public function getWhere(): string;Returns the partial-index WHERE predicate, or an empty string when
the index has none. Supported by PostgreSQL and SQLite; ignored by
the MySQL dialect (MySQL has no partial-index feature).
isConcurrent()
public function isConcurrent(): bool;Whether the index is built CONCURRENTLY (PostgreSQL only). MySQL
and SQLite have no equivalent and ignore the flag.
isInvisible()
public function isInvisible(): bool;Whether the index is declared INVISIBLE (MySQL 8.0+). Invisible
indexes are ignored by the optimizer but still maintained, so they
can be flipped back to visible without a rebuild.
Db\IndexInterface
InterfaceSource on GitHubPhalcon\Db\IndexInterface
Phalcon\Contracts\Db\IndexPhalcon\Db\IndexInterface
Uses Phalcon\Contracts\Db\Index
Db\Profiler
ClassSource on GitHubInstances of Phalcon\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications.
use Phalcon\Db\Profiler;
use Phalcon\Events\Event;
use Phalcon\Events\Manager;
$profiler = new Profiler();
$eventsManager = new Manager();
$eventsManager->attach(
"db",
function (Event $event, $connection) use ($profiler) {
if ($event->getType() === "beforeQuery") {
$sql = $connection->getSQLStatement();
// Start a profile with the active connection
$profiler->startProfile($sql);
}
if ($event->getType() === "afterQuery") {
// Stop the active profile
$profiler->stopProfile();
}
}
);
// Set the event manager on the connection
$connection->setEventsManager($eventsManager);
$sql = "SELECT buyer_name, quantity, product_name
FROM buyers LEFT JOIN products ON
buyers.pid=products.id";
// Execute a SQL statement
$connection->query($sql);
// Get the last profile in the profiler
$profile = $profiler->getLastProfile();
echo "SQL Statement: ", $profile->getSQLStatement(), "\n";
echo "Start Time: ", $profile->getInitialTime(), "\n";
echo "Final Time: ", $profile->getFinalTime(), "\n";
echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n";Phalcon\Db\Profiler
Uses Phalcon\Db\Profiler\Item · Phalcon\Db\Traits\ElapsedTimeTrait
Method Summary
publicItemgetLastProfile()Returns the last profile executed in the profilerpublicintgetMaxProfiles()Returns the configured maximum number of retained profilespublicintgetNumberTotalStatements()Returns the total number of SQL statements processedpublicItem[]getProfiles()Returns all the processed profilespublicfloatgetTotalElapsedNanoseconds()Returns the total time in nanoseconds spent by the profilespublicstaticreset()Resets the profiler, cleaning up all the profilespublicstaticsetMaxProfiles( int$maxProfiles )Sets the maximum number of retained profiles. 0 disables the cappublicstaticstartProfile(string$sqlStatement,array$sqlVariables = [],array$sqlBindTypes = [])Starts the profile of a SQL sentencepublicstaticstopProfile()Stops the active profileProperties
protectedItem$activeProfileActive ItemprotectedItem[]$allProfilesAll the Items in the active profileprotectedint$maxProfiles = 0Maximum number of profiles to retain. 0 (default) keeps the original unbounded behavior; a positive value drops the oldest profile FIFO before a new one is appended.protectedfloat$totalNanoseconds = 0Total time spent by all profiles to complete in nanosecondsMethods
getLastProfile()
public function getLastProfile(): Item;Returns the last profile executed in the profiler
getMaxProfiles()
public function getMaxProfiles(): int;Returns the configured maximum number of retained profiles (0 = unlimited)
getNumberTotalStatements()
public function getNumberTotalStatements(): int;Returns the total number of SQL statements processed
getProfiles()
public function getProfiles(): Item[];Returns all the processed profiles
getTotalElapsedNanoseconds()
public function getTotalElapsedNanoseconds(): float;Returns the total time in nanoseconds spent by the profiles
reset()
public function reset(): static;Resets the profiler, cleaning up all the profiles
setMaxProfiles()
public function setMaxProfiles( int $maxProfiles ): static;Sets the maximum number of retained profiles. 0 disables the cap (the default; preserves the original unbounded behavior).
startProfile()
public function startProfile(
string $sqlStatement,
array $sqlVariables = [],
array $sqlBindTypes = []
): static;Starts the profile of a SQL sentence
stopProfile()
public function stopProfile(): static;Stops the active profile
Db\Profiler\Item
ClassSource on GitHubThis class identifies each profile in a Phalcon\Db\Profiler
Phalcon\Db\Profiler\Item
Uses Phalcon\Db\Traits\ElapsedTimeTrait
Method Summary
publicfloatgetFinalTime()Return the timestamp when the profile endedpublicfloatgetInitialTime()Return the timestamp when the profile startedpublicarraygetSqlBindTypes()Return the SQL bind types related to the profilepublicstringgetSqlStatement()Return the SQL statement related to the profilepublicarraygetSqlVariables()Return the SQL variables related to the profilepublicfloatgetTotalElapsedNanoseconds()Returns the total time in nanoseconds spent by the profilepublicstaticsetFinalTime( float$finalTime )Return the timestamp when the profile endedpublicstaticsetInitialTime( float$initialTime )Return the timestamp when the profile startedpublicstaticsetSqlBindTypes( array$sqlBindTypes )Return the SQL bind types related to the profilepublicstaticsetSqlStatement( string$sqlStatement )Return the SQL statement related to the profilepublicstaticsetSqlVariables( array$sqlVariables )Return the SQL variables related to the profileProperties
protecteddouble$finalTimeTimestamp when the profile endedprotecteddouble$initialTimeTimestamp when the profile startedprotectedarray$sqlBindTypesSQL bind types related to the profileprotectedstring$sqlStatementSQL statement related to the profileprotectedarray$sqlVariablesSQL variables related to the profileMethods
getFinalTime()
public function getFinalTime(): float;Return the timestamp when the profile ended
getInitialTime()
public function getInitialTime(): float;Return the timestamp when the profile started
getSqlBindTypes()
public function getSqlBindTypes(): array;Return the SQL bind types related to the profile
getSqlStatement()
public function getSqlStatement(): string;Return the SQL statement related to the profile
getSqlVariables()
public function getSqlVariables(): array;Return the SQL variables related to the profile
getTotalElapsedNanoseconds()
public function getTotalElapsedNanoseconds(): float;Returns the total time in nanoseconds spent by the profile
setFinalTime()
public function setFinalTime( float $finalTime ): static;Return the timestamp when the profile ended
setInitialTime()
public function setInitialTime( float $initialTime ): static;Return the timestamp when the profile started
setSqlBindTypes()
public function setSqlBindTypes( array $sqlBindTypes ): static;Return the SQL bind types related to the profile
setSqlStatement()
public function setSqlStatement( string $sqlStatement ): static;Return the SQL statement related to the profile
setSqlVariables()
public function setSqlVariables( array $sqlVariables ): static;Return the SQL variables related to the profile
Db\RawValue
ClassSource on GitHubThis class allows to insert/update raw data without quoting or formatting.
The next example shows how to use the MySQL now() function as a field value.
$subscriber = new Subscribers();
$subscriber->email = "[email protected]";
$subscriber->createdAt = new \Phalcon\Db\RawValue("now()");
$subscriber->save();Phalcon\Db\RawValue
Method Summary
public__construct( mixed$value )Phalcon\Db\RawValue constructorpublicstring__toString()publicstringgetValue()Properties
protectedstring$valueRaw value without quoting or formattingMethods
__construct()
public function __construct( mixed $value );Phalcon\Db\RawValue constructor
__toString()
public function __toString(): string;getValue()
public function getValue(): string;Db\Reference
ClassSource on GitHubAllows to define reference constraints on tables
$reference = new \Phalcon\Db\Reference(
"field_fk",
[
"referencedSchema" => "invoicing",
"referencedTable" => "products",
"columns" => [
"producttype",
"product_code",
],
"referencedColumns" => [
"type",
"code",
],
]
);Phalcon\Db\Reference- implementsPhalcon\Db\ReferenceInterface
Uses Phalcon\Db\Exceptions\ForeignKeyColumnsRequired · Phalcon\Db\Exceptions\ReferencedColumnCountMismatch · Phalcon\Db\Exceptions\ReferencedColumnsRequired · Phalcon\Db\Exceptions\ReferencedTableRequired
Method Summary
public__construct(string$name,array$definition)Phalcon\Db\Reference constructorpublicarraygetColumns()Local reference columnspublicstringgetName()Constraint namepublicstring|nullgetOnDelete()ON DELETEpublicstring|nullgetOnUpdate()ON UPDATEpublicarraygetReferencedColumns()Referenced Columnspublicstring|nullgetReferencedSchema()Referenced SchemapublicstringgetReferencedTable()Referenced Tablepublicstring|nullgetSchemaName()Schema nameProperties
protectedarray$columnsLocal reference columnsprotectedstring$nameConstraint nameprotectedstring$onDeleteON DELETEprotectedstring$onUpdateON UPDATEprotectedarray$referencedColumnsReferenced Columnsprotectedstring$referencedSchemaReferenced Schemaprotectedstring$referencedTableReferenced Tableprotectedstring$schemaNameSchema nameMethods
__construct()
public function __construct(
string $name,
array $definition
);Phalcon\Db\Reference constructor
getColumns()
public function getColumns(): array;Local reference columns
getName()
public function getName(): string;Constraint name
getOnDelete()
public function getOnDelete(): string|null;ON DELETE
getOnUpdate()
public function getOnUpdate(): string|null;ON UPDATE
getReferencedColumns()
public function getReferencedColumns(): array;Referenced Columns
getReferencedSchema()
public function getReferencedSchema(): string|null;Referenced Schema
getReferencedTable()
public function getReferencedTable(): string;Referenced Table
getSchemaName()
public function getSchemaName(): string|null;Schema name
Db\ReferenceInterface
InterfaceSource on GitHubPhalcon\Db\ReferenceInterface
Phalcon\Contracts\Db\ReferencePhalcon\Db\ReferenceInterface
Uses Phalcon\Contracts\Db\Reference
Db\ResultInterface
InterfaceSource on GitHubPhalcon\Db\ResultInterface
Phalcon\Contracts\Db\ResultPhalcon\Db\ResultInterface
Uses Phalcon\Contracts\Db\Result
Db\Result\PdoResult
ClassSource on GitHubEncapsulates the resultset internals
$result = $connection->query("SELECT * FROM co_invoices ORDER BY inv_title");
$result->setFetchMode(
\Phalcon\Db\Enum::FETCH_NUM
);
while ($invoice = $result->fetchArray()) {
print_r($invoice);
}Phalcon\Db\Result\PdoResult- implementsPhalcon\Db\ResultInterface
Uses Phalcon\Db\Adapter\AdapterInterface · Phalcon\Db\Enum · Phalcon\Db\ResultInterface
Method Summary
public__construct(AdapterInterface$connection,\PDOStatement$result,mixed$sqlStatement = null,mixed$bindParams = null,mixed$bindTypes = null)Phalcon\Db\Result\Pdo constructorpublicvoiddataSeek( int$number )Moves internal resultset cursor to another position letting us to fetch apublicboolexecute()Allows to execute the statement again. Some database systems don'tpublicfetch(int|null$fetchStyle = null,int$cursorOrientation = Enum::FETCH_ORI_NEXT,int$cursorOffset = 0)Fetches an array/object of strings that corresponds to the fetched row,publicarrayfetchAll(int$mode = Enum::FETCH_DEFAULT,mixed$fetchArgument = Enum::FETCH_ORI_NEXT,mixed$constructorArgs = null)Returns an array of arrays containing all the records in the resultpublicfetchArray()Returns an array of strings that corresponds to the fetched row, or FALSEpublic\PDOStatementgetInternalResult()Gets the internal PDO result objectpublicintnumRows()Gets number of rows returned by a resultsetpublicboolsetFetchMode(int$fetchMode,mixed$colNoOrClassNameOrObject = null,mixed$ctorargs = null)Changes the fetching mode affecting Phalcon\Db\Result\Pdo::fetch()Properties
protectedarray$bindParams = []protectedarray$bindTypes = []protectedAdapterInterface$connectionprotectedint$fetchMode = Enum::FETCH_DEFAULTActive fetch modeprotected\PDOStatement$pdoStatementInternal resultsetprotectedmixed$resultprotectedint|null$rowCount = nullprotectedstring|null$sqlStatement = nullMethods
__construct()
public function __construct(
AdapterInterface $connection,
\PDOStatement $result,
mixed $sqlStatement = null,
mixed $bindParams = null,
mixed $bindTypes = null
);Phalcon\Db\Result\Pdo constructor
dataSeek()
public function dataSeek( int $number ): void;Moves internal resultset cursor to another position letting us to fetch a certain row
$result = $connection->query(
"SELECT * FROM co_invoices ORDER BY inv_title"
);
// Move to third row on result
$result->dataSeek(2);
// Fetch third row
$row = $result->fetch();execute()
public function execute(): bool;Allows to execute the statement again. Some database systems don’t support scrollable cursors. So, as cursors are forward only, we need to execute the cursor again to fetch rows from the beginning
fetch()
public function fetch(
int|null $fetchStyle = null,
int $cursorOrientation = Enum::FETCH_ORI_NEXT,
int $cursorOffset = 0
);Fetches an array/object of strings that corresponds to the fetched row,
or FALSE if there are no more rows. This method is affected by the active
fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode()
$result = $connection->query("SELECT * FROM co_invoices ORDER BY inv_title");
$result->setFetchMode(
\Phalcon\Enum::FETCH_OBJ
);
while ($invoice = $result->fetch()) {
echo $invoice->inv_title;
}fetchAll()
public function fetchAll(
int $mode = Enum::FETCH_DEFAULT,
mixed $fetchArgument = Enum::FETCH_ORI_NEXT,
mixed $constructorArgs = null
): array;Returns an array of arrays containing all the records in the result
This method is affected by the active fetch flag set using
Phalcon\Db\Result\Pdo::setFetchMode()
$result = $connection->query(
"SELECT * FROM co_invoices ORDER BY inv_title"
);
$invoices = $result->fetchAll();fetchArray()
public function fetchArray();Returns an array of strings that corresponds to the fetched row, or FALSE
if there are no more rows. This method is affected by the active fetch
flag set using Phalcon\Db\Result\Pdo::setFetchMode()
$result = $connection->query("SELECT * FROM co_invoices ORDER BY inv_title");
$result->setFetchMode(
\Phalcon\Enum::FETCH_NUM
);
while ($invoice = result->fetchArray()) {
print_r($invoice);
}getInternalResult()
public function getInternalResult(): \PDOStatement;Gets the internal PDO result object
numRows()
public function numRows(): int;Gets number of rows returned by a resultset
$result = $connection->query(
"SELECT * FROM co_invoices ORDER BY inv_title"
);
echo "There are ", $result->numRows(), " rows in the resultset";setFetchMode()
public function setFetchMode(
int $fetchMode,
mixed $colNoOrClassNameOrObject = null,
mixed $ctorargs = null
): bool;Changes the fetching mode affecting Phalcon\Db\Result\Pdo::fetch()
// Return array with integer indexes
$result->setFetchMode(
\Phalcon\Enum::FETCH_NUM
);
// Return associative array without integer indexes
$result->setFetchMode(
\Phalcon\Enum::FETCH_ASSOC
);
// Return associative array together with integer indexes
$result->setFetchMode(
\Phalcon\Enum::FETCH_BOTH
);
// Return an object
$result->setFetchMode(
\Phalcon\Enum::FETCH_OBJ
);Db\Traits\ElapsedTimeTrait
TraitSource on GitHubDerives elapsed milliseconds and seconds from the nanosecond total that the using class exposes through getTotalElapsedNanoseconds().
Phalcon\Db\Traits\ElapsedTimeTrait
Used by Phalcon\Db\Profiler · Phalcon\Db\Profiler\Item
Method Summary
publicfloatgetTotalElapsedMilliseconds()Returns the total time in milliseconds spent by the profilespublicfloatgetTotalElapsedNanoseconds()Returns the total time in nanoseconds spent by the profiles. ImplementedpublicfloatgetTotalElapsedSeconds()Returns the total time in seconds spent by the profilesMethods
getTotalElapsedMilliseconds()
public function getTotalElapsedMilliseconds(): float;Returns the total time in milliseconds spent by the profiles
getTotalElapsedNanoseconds()
abstract public function getTotalElapsedNanoseconds(): float;Returns the total time in nanoseconds spent by the profiles. Implemented by the using class.
getTotalElapsedSeconds()
public function getTotalElapsedSeconds(): float;Returns the total time in seconds spent by the profiles