Skip to content

Phalcon Db

Updated View as Markdown

Db\AbstractDb

AbstractSource on GitHub

Phalcon\Db 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\AbstractDb

Uses Phalcon\Support\Settings

Method Summary

Methods

Public · 1

setup()

public static function setup( array $options ): void;

Enables/disables options in the Database component

Db\Adapter\AbstractAdapter

AbstractSource on GitHub

Base class for Phalcon\Db\Adapter adapters

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\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\Traits\EventsAwareTrait

Method Summary

public__construct(array $descriptor)

Phalcon\Db\Adapter constructor

publicbooladdCheck(string $tableName,string $schemaName,CheckInterface $check)

Adds a CHECK constraint to a table.

publicbooladdColumn(string $tableName,string $schemaName,ColumnInterface $column)

Adds a column to a table

publicbooladdForeignKey(string $tableName,string $schemaName,ReferenceInterface $reference)

Adds a foreign key to a table

publicbooladdIndex(string $tableName,string $schemaName,IndexInterface $index)

Adds an index to a table

publicbooladdPrimaryKey(string $tableName,string $schemaName,IndexInterface $index)

Adds a primary key to a table

publicboolcreateMaterializedView(string $viewName,array $definition,string|null $schemaName = null)

Creates a materialized view (PostgreSQL only).

publicboolcreateSavepoint(string $name)

Creates a new savepoint

publicboolcreateTable(string $tableName,string $schemaName,array $definition)

Creates a table

publicboolcreateView(string $viewName,array $definition,string|null $schemaName = null)

Creates a view

publicbooldelete(array|string $tableName,string|null $whereCondition = null,array $placeholders = [],array $dataTypes = [])

Deletes data from a table using custom RBDM SQL syntax

publicarraydescribeIndexes(string $tableName,string|null $schemaName = null)

Lists table indexes

publicarraydescribeReferences(string $tableName,string|null $schemaName = null)

Lists table references

publicbooldropCheck(string $tableName,string $schemaName,string $checkName)

Drops a CHECK constraint from a table.

publicbooldropColumn(string $tableName,string $schemaName,string $columnName)

Drops a column from a table

publicbooldropForeignKey(string $tableName,string $schemaName,string $referenceName)

Drops a foreign key from a table

publicbooldropIndex(string $tableName,string $schemaName,string $indexName)

Drop an index from a table

publicbooldropMaterializedView(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 key

publicbooldropTable(string $tableName,string|null $schemaName = null,bool $ifExists = true)

Drops a table from a schema/database

publicbooldropView(string $viewName,string|null $schemaName = null,bool $ifExists = true)

Drops a view

publicstringescapeIdentifier(array|float|int|string $identifier)

Escapes a column/table/schema name

publicarrayfetchAll(string $sqlQuery,int $fetchMode = Enum::FETCH_ASSOC,array $bindParams = [],array $bindTypes = [])

Dumps the complete result of a query into an array

publicmixedfetchColumn(string $sqlQuery,array $placeholders = [],int|string $column = 0)

Returns the n’th field of first row in a SQL query result

publicarray|boolfetchOne(string $sqlQuery,int $fetchMode = Enum::FETCH_ASSOC,array $bindParams = [],array $bindTypes = [])

Returns the first row in a SQL query result

publicstringforUpdate(string $sqlQuery,string $modifier = "")

Returns a SQL modified with a FOR UPDATE clause

publicstringgetColumnDefinition(ColumnInterface $column)

Returns the SQL column definition from a column

publicstringgetColumnList(array $columnList)

Gets a list of columns

publicintgetConnectionId()

Gets the active connection unique identifier

publicRawValuegetDefaultIdValue()

Returns the default identity value to be inserted in an identity column

publicRawValuegetDefaultValue()

Returns the default value to make the RBDM use the default value declared

publicarraygetDescriptor()

Return descriptor used to connect to the active database

publicDialectInterfacegetDialect()

Returns internal dialect instance

publicstringgetDialectType()

Name of the dialect used

publicstringgetNestedTransactionSavepointName()

Returns the savepoint name to use for nested transactions

publicstringgetRealSQLStatement()

Active SQL statement in the object without replace bound parameters

publicarraygetSQLBindTypes()

Active SQL statement in the object

publicstringgetSQLStatement()

Active SQL statement in the object

publicarraygetSQLVariables()

Active SQL variables in the object

publicstringgetType()

Type of database system the adapter is used for

publicboolinsert(string $tableName,array $values,array|null $fields = null,array $dataTypes = [])

Inserts data into a table using custom RDBMS SQL syntax

publicboolinsertAsDict(string $tableName,array $data,array $dataTypes = [])

Inserts data into a table using custom RBDM SQL syntax

publicboolisNestedTransactionsWithSavepoints()

Returns if nested transactions should use savepoints

publicstringlimit(string $sqlQuery,mixed $number)

Appends a LIMIT clause to $sqlQuery argument

publicarraylistTables(string|null $schemaName = null)

List all tables on a database

publicarraylistViews(string|null $schemaName = null)

List all views on a database

publicboolmodifyColumn(string $tableName,string $schemaName,ColumnInterface $column,ColumnInterface|null $currentColumn = null)

Modifies a table column based on a definition

publicstringonConflictUpdate(string $sqlQuery,array $conflictColumns,array $updateColumns)

Appends an ON CONFLICT (…) DO UPDATE SET col = excluded.col upsert

publicboolrefreshMaterializedView(string $viewName,string|null $schemaName = null,bool $concurrent = false)

Refreshes a materialized view (PostgreSQL only).

publicboolreleaseSavepoint(string $name)

Releases given savepoint

publicstringreturning(string $sqlQuery,array $columns)

Appends a RETURNING clause to an INSERT/UPDATE/DELETE statement.

publicboolrollbackSavepoint(string $name)

Rollbacks given savepoint

publicvoidsetDialect(DialectInterface $dialect)

Sets the dialect used to produce the SQL

publicAdapterInterfacesetNestedTransactionsWithSavepoints(bool $flag)

Set if nested transactions should use savepoints

publicvoidsetup(array $options)

Enables/disables options in the Database component.

publicstringsharedLock(string $sqlQuery,string $modifier = "")

Returns a SQL modified with a LOCK IN SHARE MODE clause

publicboolsupportSequences()

Check whether the database system requires a sequence to produce

publicboolsupportsDefaultValue()

Check whether the database system support the DEFAULT

publicbooltableExists(string $tableName,string|null $schemaName = null)

Generates SQL checking for the existence of a schema.table

publicarraytableOptions(string $tableName,string|null $schemaName = null)

Gets creation options from a table

publicboolupdate(string $tableName,array $fields,array $values,array|string $whereCondition = [],array $dataTypes = [])

Updates data on a table using custom RBDM SQL syntax

publicboolupdateAsDict(string $tableName,array $data,array|string $whereCondition = [],array $dataTypes = [])

Updates data on a table using custom RBDM SQL syntax

publicbooluseExplicitIdValue()

Check whether the database system requires an explicit value for identity

publicboolviewExists(string $viewName,string|null $schemaName = null)

Generates SQL checking for the existence of a schema.view

protectedvoidcheckSavepoints()

Check if savepoints are supported

Properties

protectedint$connectionConsecutive = 0

Connection ID

protectedint$connectionId

Active connection ID

protectedarray$descriptor = []

Descriptor used to connect to a database

protectedDialectInterface$dialect

Dialect instance

protectedstring$dialectType

Name of the dialect used

protectedstring$realSqlStatement = ""

The real SQL statement - what was executed

protectedarray$sqlBindTypes = []

Active SQL Bind Types

protectedstring$sqlStatement

Active SQL Statement

protectedarray$sqlVariables = []

Active SQL bound parameter variables

protectedint$transactionLevel = 0

Current transaction level

protectedbool$transactionsWithSavepoints = false

Whether the database supports transactions with save points

protectedstring$type

Type of database system the adapter is used for

Methods

Public · 64

__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.

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).

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(
    array|string $tableName,
    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` = 101

Warning! If $whereCondition is string it not escaped.

describeIndexes()

public function describeIndexes(
    string $tableName,
    string|null $schemaName = null
): array;

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 $tableName,
    string|null $schemaName = null
): array;

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.

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,
    string $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( array|float|int|string $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 = [],
    int|string $column = 0
): mixed;

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,
    int $fetchMode = Enum::FETCH_ASSOC,
    array $bindParams = [],
    array $bindTypes = []
): array|bool;

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

getColumnDefinition()

public function getColumnDefinition( ColumnInterface $column ): string;

Returns the SQL column definition from a column

getColumnList()

public function getColumnList( array $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",
    ]
);

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

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 $tableName,
    array $values,
    array|null $fields = null,
    array $dataTypes = []
): 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 $tableName,
    array $data,
    array $dataTypes = []
): 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.

refreshMaterializedView()

public function refreshMaterializedView(
    string $viewName,
    string|null $schemaName = null,
    bool $concurrent = false
): bool;

Refreshes a materialized view (PostgreSQL only).

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 statement.

rollbackSavepoint()

public function rollbackSavepoint( string $name ): bool;

Rollbacks given savepoint

setDialect()

public function setDialect( DialectInterface $dialect ): void;

Sets the dialect used to produce the SQL

setNestedTransactionsWithSavepoints()

public function setNestedTransactionsWithSavepoints( bool $flag ): 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 LOCK IN SHARE MODE clause

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 $tableName,
    array $fields,
    array $values,
    array|string $whereCondition = [],
    array $dataTypes = []
): 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 is not escaped.

updateAsDict()

public function updateAsDict(
    string $tableName,
    array $data,
    array|string $whereCondition = [],
    array $dataTypes = []
): 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 = 101

useExplicitIdValue()

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")
);
Protected · 1

checkSavepoints()

protected function checkSavepoints(): void;

Check if savepoints are supported

Db\Adapter\AdapterInterface

InterfaceSource on GitHub

Phalcon\Db\Adapter\AdapterInterface

Uses Phalcon\Contracts\Db\Adapter\Adapter

Db\Adapter\PdoFactory

ClassSource on GitHub

Uses Exception · Phalcon\Config\ConfigInterface · Phalcon\Db\Adapter\Pdo\Mysql · Phalcon\Db\Adapter\Pdo\Postgresql · Phalcon\Db\Adapter\Pdo\Sqlite · Phalcon\Factory\AbstractFactory · Phalcon\Support\Exception

Method Summary

Methods

Public · 3

__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

Protected · 2

getExceptionClass()

protected function getExceptionClass(): string;

getServices()

protected function getServices(): array;

Returns the available adapters

Db\Adapter\Pdo\AbstractPdo

AbstractSource on GitHub

Phalcon\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);

Uses PDO · PDOException · PDOStatement · 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\Exception · Phalcon\Support\Settings · Throwable

Method Summary

public__construct(array $descriptor)

Constructor for Phalcon\Db\Adapter\Pdo

publicintaffectedRows()

Returns the number of affected rows by the latest INSERT/UPDATE/DELETE

publicboolbegin(bool $nesting = true)

Starts a transaction in the connection

publicvoidclose()

Closes the active connection returning success. Phalcon automatically

publicboolcommit(bool $nesting = true)

Commits the active transaction in the connection

publicvoidconnect(array $descriptor = [])

This method is automatically called in \Phalcon\Db\Adapter\Pdo

publicarrayconvertBoundParams(string $sql,array $parameters = [])

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 $input)

Escapes a value to avoid SQL injections according to the active charset

publicboolexecute(string $sqlStatement,array $bindParams = [],array $bindTypes = [])

Sends SQL statements to the database server returning the success state.

publicPDOStatementexecutePrepared(PDOStatement $statement,array $placeholders,array $dataTypes = [])

Executes a prepared statement binding. This function uses integer indexes

publicboolgetAutoReconnect()

Returns whether transparent auto-reconnect is enabled.

publicarraygetErrorInfo()

Return the error info, if any

publicPDO|nullgetInternalHandler()

Return internal PDO handler

publicintgetTransactionLevel()

Returns the current transaction nesting level

publicboolisUnderTransaction()

Checks whether the connection is under a transaction

publicbool|stringlastInsertId(string|null $name = null)

Returns the insert id for the auto_increment/serial column inserted in

publicboolping()

Checks whether the underlying connection is still alive by issuing a

publicPDOStatementprepare(string $sqlStatement)

Returns a PDO prepared statement to be executed with ‘executePrepared’

publicbool|ResultInterfacequery(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 connection

publicstaticsetAutoReconnect(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)

Properties

protectedint$affectedRows = 0

Last affected rows

protectedbool$autoReconnect = false

Whether to transparently reconnect and retry once when a query fails because the connection was lost. Opt-in; off by default.

protectedPDO|null$pdo = null

PDO Handler

Methods

Public · 22

__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 $parameters = []
): 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 $input ): 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(): PDO|null;

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 ): bool|string;

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 = []
): bool|ResultInterface;

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.

Protected · 3

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 GitHub

Specific 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);

Uses PDO · PDOException · 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 · Throwable

Method Summary

Properties

protectedstring$dialectType = "mysql"
protectedstring$type = "mysql"

Methods

Public · 5

addForeignKey()

public function addForeignKey(
    string $tableName,
    string $schemaName,
    ReferenceInterface $reference
): bool;

Adds a foreign key to a table

connect()

public function connect( array $descriptor = [] ): void;

describeColumns()

public function describeColumns(
    string $tableName,
    string|null $schemaName = null
): array;

Returns an array of Phalcon\Db\Column objects describing a table

print_r(
    $connection->describeColumns("posts")
);

describeIndexes()

public function describeIndexes(
    string $tableName,
    string|null $schemaName = null
): array;

Lists table indexes

print_r(
    $connection->describeIndexes("co_orders_x_products")
);

describeReferences()

public function describeReferences(
    string $tableName,
    string|null $schemaName = null
): array;

Lists table references

print_r(
    $connection->describeReferences("co_orders_x_products")
);
Protected · 2

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 GitHub

Specific 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);

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

Properties

protectedstring$dialectType = "postgresql"
protectedstring$type = "pgsql"

Methods

Public · 9

__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 $tableName,
    string|null $schemaName = null
): array;

Returns an array of Phalcon\Db\Column objects describing a table

print_r(
    $connection->describeColumns("posts")
);

describeReferences()

public function describeReferences(
    string $tableName,
    string|null $schemaName = null
): array;

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

Protected · 2

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 GitHub

Specific functions for the SQLite database system

use Phalcon\Db\Adapter\Pdo\Sqlite;

$connection = new Sqlite(
    [
        "dbname" => "/tmp/test.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

Properties

protectedstring$dialectType = "sqlite"
protectedstring$type = "sqlite"

Methods

Public · 8

__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 $tableName,
    string|null $schemaName = null
): array;

Returns an array of Phalcon\Db\Column objects describing a table

print_r(
    $connection->describeColumns("posts")
);

describeIndexes()

public function describeIndexes(
    string $tableName,
    string|null $schemaName = null
): array;

Lists table indexes

print_r(
    $connection->describeIndexes("co_orders_x_products")
);

describeReferences()

public function describeReferences(
    string $tableName,
    string|null $schemaName = null
): array;

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

Protected · 1

getDsnDefaults()

protected function getDsnDefaults(): array;

Returns PDO adapter DSN defaults as a key-value map.

Db\Check

ClassSource on GitHub

Allows 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],
    ]
);

Uses Phalcon\Db\Exceptions\CheckExpressionRequired · Phalcon\Db\Exceptions\InvalidCheckExpression

Method Summary

Properties

protectedstring$expression

The boolean SQL predicate this constraint enforces.

protectedstring$name

The CHECK constraint name. An empty string indicates an unnamed constraint - the dialect will emit the clause without a CONSTRAINT prefix in that case.

Methods

Public · 3

__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 GitHub

Phalcon\Db\CheckInterface

Uses Phalcon\Contracts\Db\Check

Db\Column

ClassSource on GitHub

Allows 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);

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

Constants

intBIND_PARAM_BLOB = 3

Bind Type Blob

intBIND_PARAM_BOOL = 5

Bind Type Bool

intBIND_PARAM_DECIMAL = 32

Bind Type Decimal

intBIND_PARAM_INT = 1

Bind Type Integer

intBIND_PARAM_NULL = 0

Bind Type Null

intBIND_PARAM_STR = 2

Bind Type String

intBIND_SKIP = 1024

Skip binding by type

intTYPE_BIGINTEGER = 14

Big integer abstract data type

intTYPE_BINARY = 27

Binary abstract data type

intTYPE_BIT = 19

Bit abstract data type

intTYPE_BLOB = 11

Blob abstract data type

intTYPE_BOOLEAN = 8

Bool abstract data type

intTYPE_BYTEA = 30

PostgreSQL BYTEA binary type

intTYPE_CHAR = 5

Char abstract data type

intTYPE_CIDR = 32

PostgreSQL CIDR network-address type

intTYPE_DATE = 1

Date abstract data type

intTYPE_DATERANGE = 39

PostgreSQL DATERANGE range-of-date type

intTYPE_DATETIME = 4

Datetime abstract data type

intTYPE_DECIMAL = 3

Decimal abstract data type

intTYPE_DOUBLE = 9

Double abstract data type

intTYPE_ENUM = 18

Enum abstract data type

intTYPE_FLOAT = 7

Float abstract data type

intTYPE_GEOMETRY = 40

Spatial GEOMETRY base type (MySQL 5.7+; PostgreSQL + PostGIS)

intTYPE_GEOMETRYCOLLECTION = 47

Spatial GEOMETRYCOLLECTION type

intTYPE_INET = 31

PostgreSQL INET IPv4/IPv6 address type

intTYPE_INT4RANGE = 34

PostgreSQL INT4RANGE range-of-integer type

intTYPE_INT8RANGE = 35

PostgreSQL INT8RANGE range-of-bigint type

intTYPE_INTEGER = 0

Int abstract data type

intTYPE_JSON = 15

Json abstract data type

intTYPE_JSONB = 16

Jsonb abstract data type

intTYPE_LINESTRING = 42

Spatial LINESTRING type

intTYPE_LONGBLOB = 13

Longblob abstract data type

intTYPE_LONGTEXT = 24

Longtext abstract data type

intTYPE_MACADDR = 33

PostgreSQL MACADDR MAC-address type

intTYPE_MEDIUMBLOB = 12

Mediumblob abstract data type

intTYPE_MEDIUMINTEGER = 21

Mediumintegerr abstract data type

intTYPE_MEDIUMTEXT = 23

Mediumtext abstract data type

intTYPE_MULTILINESTRING = 45

Spatial MULTILINESTRING type

intTYPE_MULTIPOINT = 44

Spatial MULTIPOINT type

intTYPE_MULTIPOLYGON = 46

Spatial MULTIPOLYGON type

intTYPE_NUMRANGE = 36

PostgreSQL NUMRANGE range-of-numeric type

intTYPE_POINT = 41

Spatial POINT type

intTYPE_POLYGON = 43

Spatial POLYGON type

intTYPE_SMALLINTEGER = 22

Smallint abstract data type

intTYPE_TEXT = 6

Text abstract data type

intTYPE_TIME = 20

Time abstract data type

intTYPE_TIMESTAMP = 17

Timestamp abstract data type

intTYPE_TINYBLOB = 10

Tinyblob abstract data type

intTYPE_TINYINTEGER = 26

Tinyint abstract data type

intTYPE_TINYTEXT = 25

Tinytext abstract data type

intTYPE_TSRANGE = 37

PostgreSQL TSRANGE range-of-timestamp (without time zone) type

intTYPE_TSTZRANGE = 38

PostgreSQL TSTZRANGE range-of-timestamp (with time zone) type

intTYPE_UUID = 29

UUID abstract data type

intTYPE_VARBINARY = 28

Varbinary abstract data type

intTYPE_VARCHAR = 2

Varchar abstract data type

Properties

protectedstring|null$after = null

Column Position

protectedint$bindType = 2

Bind Type

protectedstring|null$comment = null

Column’s comment

protectedmixed|null$defaultValue = null

Default column value

protectedstring|null$generated = null

Generation expression for GENERATED ALWAYS AS (...). Null when the column is not generated.

protectedbool$generationStored = false

Whether a generated column is STORED (true) or VIRTUAL (false). PostgreSQL only supports STORED and emits it regardless of this flag.

protectedbool$isArray = false

Whether the column is an array of its base type (PostgreSQL).

protectedbool$isAutoIncrement = false

Column is autoIncrement?

protectedbool$isFirst = false

Position is first

protectedbool$isInvisible = false

Whether the column is declared INVISIBLE (MySQL 8.0.23+).

protectedbool$isNotNull = true

Column not nullable?

Default SQL definition is NOT NULL.

protectedbool$isNumeric = false

The column have some numeric type?

protectedbool$isPrimary = false

Column is part of the primary key?

protectedbool$isUnsigned = false

Integer column unsigned?

protectedstring$name
protectedint$scale = 0

Integer column number scale

protectedint|string$size = 0

Integer column size

protectedint|string$type

Column data type

protectedint$typeReference = -1

Column data type reference

protectedarray|int|string$typeValues = []

Column data type values

Methods

Public · 23

__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|int|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 has the first position in the 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.

isInvisible()

public function isInvisible(): bool;

Whether the column is declared INVISIBLE (MySQL 8.0.23+).

isNotNull()

public function isNotNull(): bool;

Not null

isNumeric()

public function isNumeric(): bool;

Check whether column have a 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 GitHub

Phalcon\Db\ColumnInterface

Uses Phalcon\Contracts\Db\Column

Db\Dialect

AbstractSource on GitHub

This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax

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 PostgreSQL;

publicstringcreateSavepoint(string $name)

Generate SQL to create a new savepoint

publicstringdropMaterializedView(string $viewName,string|null $schemaName = null,bool $ifExists = true)

Generates SQL to drop a materialized view (PostgreSQL only).

publicstringescape(string $input,string $escapeChar = "")

Escape identifiers

publicstringescapeSchema(string $input,string $escapeChar = "")

Escape Schema

publicstringforUpdate(string $sqlQuery,string $modifier = "")

Returns a SQL modified with a FOR UPDATE clause. The optional

publicstringgetColumnList(array $columnList,string $escapeChar = "",array $bindCounts = [])

Gets a list of columns with escaped identifiers

publicarraygetCustomFunctions()

Returns registered functions

publicstringgetSqlColumn(array|string $column,string $escapeChar = "",array $bindCounts = [])

Resolve Column expressions

publicstringgetSqlExpression(array $expression,string $escapeChar = "",array $bindCounts = [])

Transforms an intermediate representation for an expression into a

publicstringgetSqlTable(array|string $tableName,string $escapeChar = "")

Transform an intermediate representation of a schema/table into a

publicstringlimit(string $sqlQuery,mixed $number)

Generates the SQL for LIMIT clause

publicstringonConflictUpdate(string $sqlQuery,array $conflictColumns,array $updateColumns)

Appends an ON CONFLICT (col, ...) DO UPDATE SET col = excluded.col

publicstringrefreshMaterializedView(string $viewName,string|null $schemaName = null,bool $concurrent = false)

Generates SQL to refresh a materialized view (PostgreSQL only).

publicstaticregisterCustomFunction(string $name,callable $customFunction)

Registers custom SQL functions

publicstringreleaseSavepoint(string $name)

Generate SQL to release a savepoint

publicstringreturning(string $sqlQuery,array $columns)

Returns a SQL statement extended with a RETURNING clause.

publicstringrollbackSavepoint(string $name)

Generate SQL to rollback a savepoint

publicstringselect(array $definition)

Builds a SELECT statement

publicboolsupportsAlterTable()

Checks whether the platform supports the full ALTER TABLE matrix:

publicboolsupportsMaterializedViews()

Checks whether the platform supports materialized views. Only PostgreSQL

publicboolsupportsOnConflictUpdate()

Checks whether the platform supports the ON CONFLICT (...) DO UPDATE

publicboolsupportsReleaseSavepoints()

Checks whether the platform supports releasing savepoints.

publicboolsupportsReturning()

Checks whether the platform supports the RETURNING clause. MySQL

publicboolsupportsSavepoints()

Checks whether the platform supports savepoints

protectedintcheckColumnType(ColumnInterface $column)

Checks the column type and if not string it returns the type reference

protectedstringcheckColumnTypeSql(ColumnInterface $column)

Checks the column type and returns the updated SQL statement

protectedstringescapeStringLiteral(string $value)

Escape a string literal for a single quoted SQL string. The standard

protectedstringgetCheckClause(CheckInterface $check,string $escapeChar = "`")

Builds a CHECK constraint clause from a CheckInterface, using the

protectedstringgetColumnSize(ColumnInterface $column)

Returns the size of the column enclosed in parentheses

protectedstringgetColumnSizeAndScale(ColumnInterface $column)

Returns the column size and scale enclosed in parentheses

protectedstringgetGeneratedClause(ColumnInterface $column,bool $forceStored = false)

Builds the GENERATED ALWAYS AS (<expr>) VIRTUAL|STORED clause for a

protectedstringgetIndexColumnList(IndexInterface $index,bool $wrapExpressions = true)

Builds the per-index parenthesized column list, honoring per-column

protectedstringgetLimitValue(mixed $value)

Renders a LIMIT/OFFSET value: a bound placeholder passes through, any

protectedstringgetSqlExpressionAll(array $expression,string $escapeChar = "")

Resolve *

protectedstringgetSqlExpressionBinaryOperations(array $expression,string $escapeChar = "",array $bindCounts = [])

Resolve binary operations expressions

protectedstringgetSqlExpressionCase(array $expression,string $escapeChar = "",array $bindCounts = [])

Resolve CASE expressions

protectedstringgetSqlExpressionCastValue(array $expression,string $escapeChar = "",array $bindCounts = [])

Resolve CAST of values

protectedstringgetSqlExpressionConvertValue(array $expression,string $escapeChar = "",array $bindCounts = [])

Resolve CONVERT of values encodings

protectedstringgetSqlExpressionFrom(array|string $expression,string $escapeChar = "")

Resolve a FROM clause

protectedstringgetSqlExpressionFunctionCall(array $expression,string $escapeChar = "",array $bindCounts = [])

Resolve function calls

protectedstringgetSqlExpressionGroupBy(array|string $expression,string $escapeChar = "",array $bindCounts = [])

Resolve a GROUP BY clause

protectedstringgetSqlExpressionHaving(array $expression,string $escapeChar = "",array $bindCounts = [])

Resolve a HAVING clause

protectedstringgetSqlExpressionJoins(array|string $expression,string $escapeChar = "",array $bindCounts = [])

Resolve a JOINs clause

protectedstringgetSqlExpressionLimit(array|string $expression,string $escapeChar = "",array $bindCounts = [])

Resolve a LIMIT clause

protectedstringgetSqlExpressionList(array $expression,string $escapeChar = "",array $bindCounts = [])

Resolve Lists

protectedstringgetSqlExpressionObject(array $expression,string $escapeChar = "",array $bindCounts = [])

Resolve object expressions

protectedstringgetSqlExpressionOrderBy(array|string $expression,string $escapeChar = "",array $bindCounts = [])

Resolve an ORDER BY clause

protectedstringgetSqlExpressionQualified(array $expression,string $escapeChar = "")

Resolve qualified expressions

protectedstringgetSqlExpressionScalar(array $expression,string $escapeChar = "",array $bindCounts = [])

Resolve Column expressions

protectedstringgetSqlExpressionUnaryOperations(array $expression,string $escapeChar = "",array $bindCounts = [])

Resolve unary operations expressions

protectedstringgetSqlExpressionWhere(array|string $expression,string $escapeChar = "",array $bindCounts = [])

Resolve a WHERE clause

protectedstringprepareColumnAlias(string $qualified,string $alias = "",string $escapeChar = "")

Prepares column for this RDBMS

protectedstringprepareQualified(string $column,string $domain = "",string $escapeChar = "")

Prepares qualified for this RDBMS

protectedstringprepareTable(string $tableName,string|null $schemaName = null,string $alias = "",string $escapeChar = "")

Prepares table for this RDBMS

Properties

protectedarray$customFunctions = []
protectedstring$escapeChar
protectedarray$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

Public · 25

createMaterializedView()

public function createMaterializedView(
    string $viewName,
    array $definition,
    string|null $schemaName = null
): string;

Generates SQL to create a materialized view. Supported by PostgreSQL; MySQL and SQLite inherit this throw.

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 (PostgreSQL only).

escape()

final public function escape(
    string $input,
    string $escapeChar = ""
): string;

Escape identifiers

escapeSchema()

final public function escapeSchema(
    string $input,
    string $escapeChar = ""
): 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

getColumnList()

final public function getColumnList(
    array $columnList,
    string $escapeChar = "",
    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(
    array|string $column,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve Column expressions

getSqlExpression()

public function getSqlExpression(
    array $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Transforms an intermediate representation for an expression into a database system valid expression

getSqlTable()

final public function getSqlTable(
    array|string $tableName,
    string $escapeChar = ""
): 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. Supported by PostgreSQL 9.5+ and SQLite 3.24+. MySQL overrides this method to throw.

refreshMaterializedView()

public function refreshMaterializedView(
    string $viewName,
    string|null $schemaName = null,
    bool $concurrent = false
): string;

Generates SQL to refresh a materialized view (PostgreSQL only).

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. Supported by PostgreSQL and SQLite 3.35+; MySQL inherits the throw.

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

Protected · 30

checkColumnType()

protected function checkColumnType( ColumnInterface $column ): int;

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

escapeStringLiteral()

protected function escapeStringLiteral( string $value ): string;

Escape a string literal for a single quoted SQL string. The standard way doubles the single quotes. A dialect where the backslash is an escape character must override this method.

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.

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 (PostgreSQL uses this).

getIndexColumnList()

protected function getIndexColumnList(
    IndexInterface $index,
    bool $wrapExpressions = true
): string;

Builds the per-index parenthesized column list, honoring per-column sort directions and RawValue expression entries.

getLimitValue()

protected function getLimitValue( mixed $value ): string;

Renders a LIMIT/OFFSET value: a bound placeholder passes through, any other value is coerced to an integer to prevent SQL injection.

getSqlExpressionAll()

final protected function getSqlExpressionAll(
    array $expression,
    string $escapeChar = ""
): string;

Resolve *

getSqlExpressionBinaryOperations()

final protected function getSqlExpressionBinaryOperations(
    array $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve binary operations expressions

getSqlExpressionCase()

final protected function getSqlExpressionCase(
    array $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve CASE expressions

getSqlExpressionCastValue()

final protected function getSqlExpressionCastValue(
    array $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve CAST of values

getSqlExpressionConvertValue()

final protected function getSqlExpressionConvertValue(
    array $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve CONVERT of values encodings

getSqlExpressionFrom()

final protected function getSqlExpressionFrom(
    array|string $expression,
    string $escapeChar = ""
): string;

Resolve a FROM clause

getSqlExpressionFunctionCall()

final protected function getSqlExpressionFunctionCall(
    array $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve function calls

getSqlExpressionGroupBy()

final protected function getSqlExpressionGroupBy(
    array|string $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve a GROUP BY clause

getSqlExpressionHaving()

final protected function getSqlExpressionHaving(
    array $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve a HAVING clause

getSqlExpressionJoins()

final protected function getSqlExpressionJoins(
    array|string $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve a JOINs clause

@todo Isn’t expression just an array?

getSqlExpressionLimit()

final protected function getSqlExpressionLimit(
    array|string $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve a LIMIT clause

getSqlExpressionList()

final protected function getSqlExpressionList(
    array $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve Lists

getSqlExpressionObject()

final protected function getSqlExpressionObject(
    array $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve object expressions

getSqlExpressionOrderBy()

final protected function getSqlExpressionOrderBy(
    array|string $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve an ORDER BY clause

getSqlExpressionQualified()

final protected function getSqlExpressionQualified(
    array $expression,
    string $escapeChar = ""
): string;

Resolve qualified expressions

getSqlExpressionScalar()

final protected function getSqlExpressionScalar(
    array $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve Column expressions

getSqlExpressionUnaryOperations()

final protected function getSqlExpressionUnaryOperations(
    array $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve unary operations expressions

getSqlExpressionWhere()

final protected function getSqlExpressionWhere(
    array|string $expression,
    string $escapeChar = "",
    array $bindCounts = []
): string;

Resolve a WHERE clause

prepareColumnAlias()

protected function prepareColumnAlias(
    string $qualified,
    string $alias = "",
    string $escapeChar = ""
): string;

Prepares column for this RDBMS

prepareQualified()

protected function prepareQualified(
    string $column,
    string $domain = "",
    string $escapeChar = ""
): string;

Prepares qualified for this RDBMS

prepareTable()

protected function prepareTable(
    string $tableName,
    string|null $schemaName = null,
    string $alias = "",
    string $escapeChar = ""
): string;

Prepares table for this RDBMS

Db\DialectInterface

InterfaceSource on GitHub

Phalcon\Db\DialectInterface

Uses Phalcon\Contracts\Db\Dialect

Db\Dialect\Mysql

ClassSource on GitHub

Generates database specific SQL for the MySQL RDBMS

Uses Phalcon\Db\CheckInterface · Phalcon\Db\Column · Phalcon\Db\ColumnInterface · Phalcon\Db\Dialect · Phalcon\Db\Dialect\Traits\TextTrait · Phalcon\Db\Exception · Phalcon\Db\Exceptions\MissingDefinitionKey · Phalcon\Db\Exceptions\MysqlOnConflictNotSupported · Phalcon\Db\Exceptions\UnrecognizedDataType · Phalcon\Db\IndexInterface · 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 table

publicstringaddForeignKey(string $tableName,string $schemaName,ReferenceInterface $reference)

Generates SQL to add an index to a table

publicstringaddIndex(string $tableName,string $schemaName,IndexInterface $index)

Generates SQL to add an index to a table

publicstringaddPrimaryKey(string $tableName,string $schemaName,IndexInterface $index)

Generates SQL to add the primary key to a table

publicstringcreateTable(string $tableName,string $schemaName,array $definition)

Generates SQL to create a table

publicstringcreateView(string $viewName,array $definition,string|null $schemaName = null)

Generates SQL to create a view

publicstringdescribeColumns(string $tableName,string|null $schemaName = null)

Generates SQL describing a table

publicstringdescribeIndexes(string $tableName,string|null $schemaName = null)

Generates SQL to query indexes on a table

publicstringdescribeReferences(string $tableName,string|null $schemaName = null)

Generates SQL to query foreign keys on a table

publicstringdropCheck(string $tableName,string $schemaName,string $checkName)

Generates SQL to delete a CHECK constraint from a 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 table

publicstringdropIndex(string $tableName,string $schemaName,string $indexName)

Generates SQL to delete an index from a table

publicstringdropPrimaryKey(string $tableName,string $schemaName)

Generates SQL to delete primary key from a table

publicstringdropTable(string $tableName,string|null $schemaName = null,bool $ifExists = true)

Generates SQL to drop a table

publicstringdropView(string $viewName,string|null $schemaName = null,bool $ifExists = true)

Generates SQL to drop a view

publicstringgetColumnDefinition(ColumnInterface $column)

Gets the column name in MySQL

publicstringgetForeignKeyChecks()

Generates SQL to check DB parameter FOREIGN_KEY_CHECKS.

publicstringlistTables(string|null $schemaName = null)

List all tables in database

publicstringlistViews(string|null $schemaName = null)

Generates the SQL to list all views of a schema or user

publicstringmodifyColumn(string $tableName,string $schemaName,ColumnInterface $column,ColumnInterface|null $currentColumn = null)

Generates SQL to modify a column in a table

publicstringonConflictUpdate(string $sqlQuery,array $conflictColumns,array $updateColumns)

MySQL does not support the SQL-standard ON CONFLICT DO UPDATE

publicstringsharedLock(string $sqlQuery,string $modifier = "")

Returns a SQL modified with a LOCK IN SHARE MODE clause

publicboolsupportsOnConflictUpdate()

MySQL does not support the SQL-standard ON CONFLICT (...) DO UPDATE

publicstringtableExists(string $tableName,string|null $schemaName = null)

Generates SQL checking for the existence of a schema.table

publicstringtableOptions(string $tableName,string|null $schemaName = null)

Generates the SQL to describe the table creation options

publicstringtruncateTable(string $tableName,string $schemaName = "")

Generates SQL to truncate a table

publicstringviewExists(string $viewName,string|null $schemaName = null)

Generates SQL checking for the existence of a schema.view

protectedstringescapeStringLiteral(string $value)

Escape a string literal for a single quoted SQL string. MySQL treats the

Properties

protectedstring$escapeChar = "`"
protectedarray$supportedOperators = [...]

Methods

Public · 29

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 $tableName,
    string|null $schemaName = null
): string;

Generates SQL describing a table

print_r(
    $dialect->describeColumns("posts")
);

describeIndexes()

public function describeIndexes(
    string $tableName,
    string|null $schemaName = null
): string;

Generates SQL to query indexes on a table

describeReferences()

public function describeReferences(
    string $tableName,
    string|null $schemaName = 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.

sharedLock()

public function sharedLock(
    string $sqlQuery,
    string $modifier = ""
): string;

Returns a SQL modified with a LOCK IN SHARE MODE clause

$sql = $dialect->sharedLock("SELECT * FROM co_invoices");

echo $sql; // SELECT * FROM co_invoices LOCK IN SHARE MODE

supportsOnConflictUpdate()

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 $tableName,
    string|null $schemaName = 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

Protected · 1

escapeStringLiteral()

protected function escapeStringLiteral( string $value ): string;

Escape a string literal for a single quoted SQL string. MySQL treats the backslash as an escape character, so it must be doubled together with the single quote.

Db\Dialect\Postgresql

ClassSource on GitHub

Generates database specific SQL for the PostgreSQL RDBMS

Uses Phalcon\Db\CheckInterface · Phalcon\Db\Column · Phalcon\Db\ColumnInterface · Phalcon\Db\Dialect · 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 table

publicstringaddForeignKey(string $tableName,string $schemaName,ReferenceInterface $reference)

Generates SQL to add an index to a table

publicstringaddIndex(string $tableName,string $schemaName,IndexInterface $index)

Generates SQL to add an index to a table

publicstringaddPrimaryKey(string $tableName,string $schemaName,IndexInterface $index)

Generates SQL to add the primary key to a table

publicstringcreateMaterializedView(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 table

publicstringcreateView(string $viewName,array $definition,string|null $schemaName = null)

Generates SQL to create a view

publicstringdescribeColumns(string $tableName,string|null $schemaName = null)

Generates SQL describing a table

publicstringdescribeIndexes(string $tableName,string|null $schemaName = null)

Generates SQL to query indexes on a table

publicstringdescribeReferences(string $tableName,string|null $schemaName = null)

Generates SQL to query foreign keys on a table

publicstringdropCheck(string $tableName,string $schemaName,string $checkName)

Generates SQL to delete a CHECK constraint from a 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 table

publicstringdropIndex(string $tableName,string $schemaName,string $indexName)

Generates SQL to delete an index from a table

publicstringdropMaterializedView(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 table

publicstringdropTable(string $tableName,string|null $schemaName = null,bool $ifExists = true)

Generates SQL to drop a table

publicstringdropView(string $viewName,string|null $schemaName = null,bool $ifExists = true)

Generates SQL to drop a view

publicstringgetColumnDefinition(ColumnInterface $column)

Gets the column name in PostgreSQL

publicstringlistTables(string|null $schemaName = null)

List all tables in database

publicstringlistViews(string|null $schemaName = null)

Generates the SQL to list all views of a schema or user

publicstringmodifyColumn(string $tableName,string $schemaName,ColumnInterface $column,ColumnInterface|null $currentColumn = null)

Generates SQL to modify a column in a table

publicstringrefreshMaterializedView(string $viewName,string|null $schemaName = null,bool $concurrent = false)

Generates SQL to refresh a materialized view.

publicstringreturning(string $sqlQuery,array $columns)

Appends a RETURNING clause to the supplied INSERT/UPDATE/DELETE

publicstringsharedLock(string $sqlQuery,string $modifier = "")

Returns a SQL modified a shared lock statement. For now this method

publicboolsupportsMaterializedViews()

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.table

publicstringtableOptions(string $tableName,string|null $schemaName = null)

Generates the SQL to describe the table creation options

publicstringtruncateTable(string $tableName,string|null $schemaName = "")

Generates SQL to truncate a table

publicstringviewExists(string $viewName,string|null $schemaName = null)

Generates SQL checking for the existence of a schema.view

protectedstringcastDefault(ColumnInterface $column)protectedstringgetTableOptions(array $definition)

Properties

protectedstring$escapeChar = "\""
protectedarray$supportedOperators = [...]

Methods

Public · 32

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 $tableName,
    string|null $schemaName = null
): string;

Generates SQL describing a table

print_r(
    $dialect->describeColumns("posts")
);

describeIndexes()

public function describeIndexes(
    string $tableName,
    string|null $schemaName = null
): string;

Generates SQL to query indexes on a table

describeReferences()

public function describeReferences(
    string $tableName,
    string|null $schemaName = 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.

returning()

public function returning(
    string $sqlQuery,
    array $columns
): string;

Appends a RETURNING clause to the supplied INSERT/UPDATE/DELETE statement.

sharedLock()

public function sharedLock(
    string $sqlQuery,
    string $modifier = ""
): string;

Returns a SQL modified a shared lock statement. For now this method returns the original query

supportsMaterializedViews()

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 $tableName,
    string|null $schemaName = null
): string;

Generates the SQL to describe the table creation options

truncateTable()

public function truncateTable(
    string $tableName,
    string|null $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

Protected · 2

castDefault()

protected function castDefault( ColumnInterface $column ): string;

getTableOptions()

protected function getTableOptions( array $definition ): string;

Db\Dialect\Sqlite

ClassSource on GitHub

Generates database specific SQL for the SQLite RDBMS

Uses Phalcon\Db\CheckInterface · Phalcon\Db\Column · Phalcon\Db\ColumnInterface · Phalcon\Db\Dialect · Phalcon\Db\Dialect\Traits\TextTrait · 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\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 table

publicstringaddForeignKey(string $tableName,string $schemaName,ReferenceInterface $reference)

Generates SQL to add an index to a table

publicstringaddIndex(string $tableName,string $schemaName,IndexInterface $index)

Generates SQL to add an index to a table

publicstringaddPrimaryKey(string $tableName,string $schemaName,IndexInterface $index)

Generates SQL to add the primary key to a table

publicstringcreateTable(string $tableName,string $schemaName,array $definition)

Generates SQL to create a table

publicstringcreateView(string $viewName,array $definition,string|null $schemaName = null)

Generates SQL to create a view

publicstringdescribeColumns(string $tableName,string|null $schemaName = null)

Generates SQL describing a table

publicstringdescribeIndex(string $index)

Generates SQL to query indexes detail on a table

publicstringdescribeIndexes(string $tableName,string|null $schemaName = null)

Generates SQL to query indexes on a table

publicstringdescribeReferences(string $tableName,string|null $schemaName = null)

Generates SQL to query foreign keys on a table

publicstringdropCheck(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 table

publicstringdropIndex(string $tableName,string $schemaName,string $indexName)

Generates SQL to delete an index from a table

publicstringdropPrimaryKey(string $tableName,string $schemaName)

Generates SQL to delete primary key from a table

publicstringdropTable(string $tableName,string|null $schemaName = null,bool $ifExists = true)

Generates SQL to drop a table

publicstringdropView(string $viewName,string|null $schemaName = null,bool $ifExists = true)

Generates SQL to drop a view

publicstringforUpdate(string $sqlQuery,string $modifier = "")

Returns a SQL modified with a FOR UPDATE clause. For SQLite, it returns

publicstringgetColumnDefinition(ColumnInterface $column)

Gets the column name in SQLite

publicstringlistIndexesSql(string $tableName,string|null $schemaName = null,string|null $keyName = null)

Generates the SQL to get query list of indexes

publicstringlistTables(string|null $schemaName = null)

List all tables in database

publicstringlistViews(string|null $schemaName = null)

Generates the SQL to list all views of a schema or user

publicstringmodifyColumn(string $tableName,string $schemaName,ColumnInterface $column,ColumnInterface|null $currentColumn = null)

Generates SQL to modify a column in a table

publicstringreturning(string $sqlQuery,array $columns)

Appends a RETURNING clause to the supplied INSERT/UPDATE/DELETE

publicstringsharedLock(string $sqlQuery,string $modifier = "")

Returns a SQL modified a shared lock statement. For now this method

publicboolsupportsAlterTable()

SQLite cannot modify existing columns or add/drop foreign keys, primary

publicboolsupportsReturning()

SQLite (3.35+) supports the RETURNING clause.

publicstringtableExists(string $tableName,string|null $schemaName = null)

Generates SQL checking for the existence of a schema.table

publicstringtableOptions(string $tableName,string|null $schemaName = null)

Generates the SQL to describe the table creation options

publicstringtruncateTable(string $tableName,string|null $schemaName = "")

Generates SQL to truncate a table

publicstringviewExists(string $viewName,string|null $schemaName = null)

Generates SQL checking for the existence of a schema.view

Properties

protectedstring$escapeChar = "\""
protectedarray$supportedOperators = [...]

Methods

Public · 32

addCheck()

public function addCheck(
    string $tableName,
    string $schemaName,
    CheckInterface $check
): string;

SQLite cannot ALTER an existing table to add a CHECK constraint.

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 $tableName,
    string|null $schemaName = 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 $tableName,
    string|null $schemaName = null
): string;

Generates SQL to query indexes on a table

describeReferences()

public function describeReferences(
    string $tableName,
    string|null $schemaName = 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

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. For SQLite, it returns the original query

getColumnDefinition()

public function getColumnDefinition( ColumnInterface $column ): string;

Gets the column name in SQLite

listIndexesSql()

public function listIndexesSql(
    string $tableName,
    string|null $schemaName = 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. SQLite 3.35+.

sharedLock()

public function sharedLock(
    string $sqlQuery,
    string $modifier = ""
): string;

Returns a SQL modified a shared lock statement. For now this method returns the original query

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 $tableName,
    string|null $schemaName = null
): string;

Generates the SQL to describe the table creation options

truncateTable()

public function truncateTable(
    string $tableName,
    string|null $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\Dialect\Traits\TextTrait

TraitSource on GitHub
  • Phalcon\Db\Dialect\Traits\TextTrait

Uses Phalcon\Db\Column · Phalcon\Db\Exception · Phalcon\Db\Index · Phalcon\Db\RawValue · Phalcon\Db\Reference

Used by Phalcon\Db\Dialect\Mysql · Phalcon\Db\Dialect\Sqlite

Method Summary

protectedstringalter(string $tableName,string|null $schemaName = null)protectedstringalterTableDrop(string $object,string $item,string $tableName,string $schemaName)protectedstringcheckColumnComment(Column $column)protectedstringcheckColumnFirstAfterPositions(Column $column)protectedstringcheckColumnHasDefault(Column $column)protectedstringcheckColumnIsAutoIncrement(Column $column)protectedstringcheckColumnIsGenerated(Column $column)

Emits the GENERATED ALWAYS AS (…) VIRTUAL|STORED clause. Wraps the

protectedstringcheckColumnIsInvisible(Column $column)

Emits the INVISIBLE keyword for MySQL 8.0.23+ invisible columns.

protectedstringcheckColumnIsNull(Column $column)protectedstringcheckColumnIsPrimary(Column $column)protectedstringcheckColumnSizeAndScale(Column $column)

Checks if the size and/or scale are present and encloses those values

protectedstringcheckColumnUnsigned(Column $column)

Checks if a column is unsigned or not and returns the relevant SQL syntax

protectedstringcheckReferenceConstraint(Reference $reference)protectedstringcheckReferenceOnDelete(Reference $reference)protectedstringcheckReferenceOnUpdate(Reference $reference)protectedstringdelimit(string $identifier,string $delimiter = "`")protectedstringdrop(string $type)protectedstringexists(bool $exists)protectedstringgetExistsSql(string $table,string $viewName,string|null $schemaName)protectedstringgetMysqlSchemaString(string|null $schemaName)protectedstringgetNullString()protectedarraygetTableChecks(array $definition)

Returns the list of CONSTRAINT … CHECK (…) lines for createTable.

protectedarraygetTableColumns(array $definition)protectedarraygetTableIndexes(array $definition)protectedstringgetTableOptions(array $definition)

Generates SQL to add the table creation options

protectedarraygetTableReferences(array $definition)protectedstringwrap(string $identifier)

Methods

Protected · 27

alter()

protected function alter(
    string $tableName,
    string|null $schemaName = null
): string;

alterTableDrop()

protected function alterTableDrop(
    string $object,
    string $item,
    string $tableName,
    string $schemaName
): string;

checkColumnComment()

protected function checkColumnComment( Column $column ): string;

checkColumnFirstAfterPositions()

protected function checkColumnFirstAfterPositions( Column $column ): string;

checkColumnHasDefault()

protected function checkColumnHasDefault( Column $column ): string;

checkColumnIsAutoIncrement()

protected function checkColumnIsAutoIncrement( Column $column ): string;

checkColumnIsGenerated()

protected function checkColumnIsGenerated( Column $column ): string;

Emits the GENERATED ALWAYS AS (…) VIRTUAL|STORED clause. Wraps the shared dialect helper for trait users.

checkColumnIsInvisible()

protected function checkColumnIsInvisible( Column $column ): string;

Emits the INVISIBLE keyword for MySQL 8.0.23+ invisible columns. Other dialects override this trait helper to return an empty string.

checkColumnIsNull()

protected function checkColumnIsNull( Column $column ): string;

checkColumnIsPrimary()

protected function checkColumnIsPrimary( Column $column ): string;

checkColumnSizeAndScale()

protected function checkColumnSizeAndScale( Column $column ): string;

Checks if the size and/or scale are present and encloses those values in parentheses if need be

checkColumnUnsigned()

protected function checkColumnUnsigned( Column $column ): string;

Checks if a column is unsigned or not and returns the relevant SQL syntax

checkReferenceConstraint()

protected function checkReferenceConstraint( Reference $reference ): string;

checkReferenceOnDelete()

protected function checkReferenceOnDelete( Reference $reference ): string;

checkReferenceOnUpdate()

protected function checkReferenceOnUpdate( Reference $reference ): string;

delimit()

protected function delimit(
    string $identifier,
    string $delimiter = "`"
): string;

drop()

protected function drop( string $type ): string;

exists()

protected function exists( bool $exists ): string;

getExistsSql()

protected function getExistsSql(
    string $table,
    string $viewName,
    string|null $schemaName
): string;

getMysqlSchemaString()

protected function getMysqlSchemaString( string|null $schemaName ): string;

getNullString()

protected function getNullString(): string;

getTableChecks()

protected function getTableChecks( array $definition ): array;

Returns the list of CONSTRAINT … CHECK (…) lines for createTable. Uses the dialect’s escape character via the shared getCheckClause() helper.

getTableColumns()

protected function getTableColumns( array $definition ): array;

getTableIndexes()

protected function getTableIndexes( array $definition ): array;

getTableOptions()

protected function getTableOptions( array $definition ): string;

Generates SQL to add the table creation options

getTableReferences()

protected function getTableReferences( array $definition ): array;

wrap()

protected function wrap( string $identifier ): string;

Db\Enum

ClassSource on GitHub

Constants for Phalcon\Db

  • Phalcon\Db\Enum

Uses PDO

Constants

mixedFETCH_ASSOC = PDO::FETCH_ASSOC
mixedFETCH_BOTH = PDO::FETCH_BOTH
mixedFETCH_BOUND = PDO::FETCH_BOUND
mixedFETCH_CLASS = PDO::FETCH_CLASS
mixedFETCH_CLASSTYPE = PDO::FETCH_CLASSTYPE
mixedFETCH_COLUMN = PDO::FETCH_COLUMN
mixedFETCH_DEFAULT = PDO::FETCH_DEFAULT
mixedFETCH_FUNC = PDO::FETCH_FUNC
mixedFETCH_GROUP = PDO::FETCH_GROUP
mixedFETCH_INTO = PDO::FETCH_INTO
mixedFETCH_KEY_PAIR = PDO::FETCH_KEY_PAIR
mixedFETCH_LAZY = PDO::FETCH_LAZY
mixedFETCH_NAMED = PDO::FETCH_NAMED
mixedFETCH_NUM = PDO::FETCH_NUM
mixedFETCH_OBJ = PDO::FETCH_OBJ
mixedFETCH_ORI_NEXT = PDO::FETCH_ORI_NEXT
mixedFETCH_PROPS_LATE = PDO::FETCH_PROPS_LATE
mixedFETCH_SERIALIZE = PDO::FETCH_SERIALIZE
mixedFETCH_UNIQUE = PDO::FETCH_UNIQUE

Db\Event\AbstractCancellableModelEvent

AbstractSource on GitHub

Uses Psr\EventDispatcher\StoppableEventInterface

Method Summary

Methods

Public · 2

cancel()

public function cancel(): void;

isPropagationStopped()

public function isPropagationStopped(): bool;

Db\Event\AbstractModelEvent

AbstractSource on GitHub

Uses Phalcon\Events\PsrEventInterface · Phalcon\Mvc\Model

Method Summary

Properties

publicModel$model

Methods

Public · 1

__construct()

public function __construct( Model $model );

Db\Event\AfterCreateEvent

ClassSource on GitHub

Db\Event\AfterDeleteEvent

ClassSource on GitHub

Db\Event\AfterFetchEvent

ClassSource on GitHub

Db\Event\AfterSaveEvent

ClassSource on GitHub

Db\Event\AfterUpdateEvent

ClassSource on GitHub

Db\Event\AfterValidationEvent

ClassSource on GitHub

Db\Event\AfterValidationOnCreateEvent

ClassSource on GitHub

Db\Event\AfterValidationOnUpdateEvent

ClassSource on GitHub

Db\Event\BeforeCreateEvent

ClassSource on GitHub

Db\Event\BeforeDeleteEvent

ClassSource on GitHub

Db\Event\BeforeSaveEvent

ClassSource on GitHub

Db\Event\BeforeUpdateEvent

ClassSource on GitHub

Db\Event\BeforeValidationEvent

ClassSource on GitHub

Db\Event\BeforeValidationOnCreateEvent

ClassSource on GitHub

Db\Event\BeforeValidationOnUpdateEvent

ClassSource on GitHub

Db\Event\Factory

ClassSource on GitHub
  • Phalcon\Db\Event\Factory

Uses Phalcon\Events\PsrEventInterface · Phalcon\Mvc\Model

Method Summary

Methods

Public · 1

create()

public function create(
    string $eventName,
    Model $model
): PsrEventInterface|null;

Db\Event\ModelEventNameEnum

ClassSource on GitHub
  • Phalcon\Db\Event\ModelEventNameEnum

Method Summary

Constants

stringAFTER_CREATE = "afterCreate"
stringAFTER_DELETE = "afterDelete"
stringAFTER_FETCH = "afterFetch"
stringAFTER_SAVE = "afterSave"
stringAFTER_UPDATE = "afterUpdate"
stringAFTER_VALIDATION = "afterValidation"
stringAFTER_VALIDATION_ON_CREATE = "afterValidationOnCreate"
stringAFTER_VALIDATION_ON_UPDATE = "afterValidationOnUpdate"
stringBEFORE_CREATE = "beforeCreate"
stringBEFORE_DELETE = "beforeDelete"
stringBEFORE_SAVE = "beforeSave"
stringBEFORE_UPDATE = "beforeUpdate"
stringBEFORE_VALIDATION = "beforeValidation"
stringBEFORE_VALIDATION_ON_CREATE = "beforeValidationOnCreate"
stringBEFORE_VALIDATION_ON_UPDATE = "beforeValidationOnUpdate"
stringNOT_DELETED = "notDeleted"
stringNOT_SAVED = "notSaved"
stringON_VALIDATION_FAILS = "onValidationFails"
stringPREPARE_SAVE = "prepareSave"
stringVALIDATION = "validation"

Methods

Public · 3

fromEventClass()

public static function fromEventClass( string $eventClassName ): self;

Get an enum case from event class name

getEventClass()

public static function getEventClass( mixed $eventName ): string;

Get the event class associated with this event type

tryFromEventClass()

public static function tryFromEventClass( string $eventClassName ): self|null;

Db\Event\NotDeletedEvent

ClassSource on GitHub

Db\Event\NotSavedEvent

ClassSource on GitHub

Db\Event\OnValidationFailsEvent

ClassSource on GitHub

Db\Event\PrepareSaveEvent

ClassSource on GitHub

Db\Event\UnknownEventTypeException

ClassSource on GitHub

Uses Phalcon\Db\Exception · Throwable

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $message = "",
    int $code = 0,
    Throwable|null $previous = null
);

Db\Event\ValidationEvent

ClassSource on GitHub

Db\Exception

ClassSource on GitHub

Exceptions thrown in Phalcon\Db will use this class

Db\Exceptions\CannotInsertWithoutData

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $table );

Db\Exceptions\CannotPrepareStatement

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\CheckExpressionRequired

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\ColumnTypeRejectsAutoIncrement

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\ColumnTypeRejectsScale

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\ColumnTypeRequired

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\ConflictTargetColumnRequired

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\ConflictUpdateColumnRequired

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\ForeignKeyColumnsRequired

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\GeneratedAutoIncrementConflict

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\GeneratedDefaultConflict

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\IncompleteBindTypes

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidBindParameter

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidCheckExpression

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidDialectClass

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Db\Exceptions\InvalidGenerationExpression

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidGroupByExpression

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidIndexColumns

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidIndexDirections

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidIndexWhere

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidListExpression

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidOrderByExpression

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidSqlExpression

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidSqlExpressionType

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $type );

Db\Exceptions\InvalidUnaryExpression

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidWhereConditions

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\InvalidWkb

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $reason );

Db\Exceptions\MatchedParameterNotFound

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\MaterializedViewsNotSupported

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\MissingDefinitionKey

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $key );

Db\Exceptions\MissingForeignKeyChecks

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\MissingSqliteDatabase

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\MysqlOnConflictNotSupported

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\NestedTransactionChangeBlocked

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\NoActiveTransaction

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\ReferencedColumnCountMismatch

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\ReferencedColumnsRequired

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\ReferencedTableRequired

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\ReturningNotSupported

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\ReturningRequiresColumn

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\SavepointsNotSupported

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\SqliteAlterCheckNotSupported

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\SqliteAlterColumnNotSupported

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\SqliteAlterForeignKeyNotSupported

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\SqliteAlterPrimaryKeyNotSupported

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\SqliteDropCheckNotSupported

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\SqliteDropForeignKeyNotSupported

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\SqliteDropPrimaryKeyNotSupported

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\TableMustHaveColumn

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Exceptions\UnrecognizedDataType

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $dialect,
    string $column
);

Db\Exceptions\UnsupportedOperator

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $operator );

Db\Exceptions\UpdateFieldCountMismatch

ClassSource on GitHub

Uses Phalcon\Db\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Db\Geometry\AbstractGeometry

AbstractSource on GitHub

Method Summary

Properties

protectedint$srid = 0

Methods

Public · 4

__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 GitHub

Uses Phalcon\Db\Column

Method Summary

Properties

protectedGeometryInterface[]$geometries

Methods

Public · 4

__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 GitHub

Phalcon\Db\Geometry\GeometryInterface

Uses Phalcon\Contracts\Db\Geometry\Geometry

Db\Geometry\LineString

ClassSource on GitHub

Uses Phalcon\Db\Column

Method Summary

Properties

protectedPoint[]$points

Methods

Public · 5

__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 GitHub

Uses Phalcon\Db\Column

Method Summary

Properties

protectedLineString[]$lineStrings

Methods

Public · 4

__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 GitHub

Uses Phalcon\Db\Column

Method Summary

Properties

protectedPoint[]$points

Methods

Public · 4

__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 GitHub

Uses Phalcon\Db\Column

Method Summary

Properties

protectedPolygon[]$polygons

Methods

Public · 4

__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 GitHub

Uses Phalcon\Db\Column

Method Summary

Properties

protectedfloat$x
protectedfloat$y

Methods

Public · 6

__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 GitHub

Uses Phalcon\Db\Column

Method Summary

Properties

protectedPoint[][]$rings

Methods

Public · 5

__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 GitHub

Decodes 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

Properties

protectedstring$buffer = ""
protectedint$length = 0
protectedint$position = 0

Methods

Public · 1

parse()

public function parse( string $raw ): GeometryInterface;
Protected · 8

readByte()

protected function readByte(): int;

readDouble()

protected function readDouble( bool $little ): float;

readGeometry()

protected function readGeometry(
    int $outerSrid,
    int $depth = 0
): 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 GitHub

Allows 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+), directions, where, and concurrently.

// 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,
        'directions' => ['DESC'],
    ]
);

Uses Phalcon\Db\Exceptions\InvalidIndexColumns · Phalcon\Db\Exceptions\InvalidIndexDirections · Phalcon\Db\Exceptions\InvalidIndexWhere

Method Summary

Properties

protectedarray$columns

Index columns. Entries may be plain strings (column names) or Phalcon\Db\RawValue instances (functional/expression index entries).

protectedbool$concurrent = false

Whether to build the index without taking a strong lock that blocks writes - emits CONCURRENTLY between INDEX and the index name on PostgreSQL. MySQL and SQLite 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.

protectedbool$invisible = false

Whether the index is declared INVISIBLE (MySQL 8.0+).

protectedstring$name
protectedstring$type = ""
protectedstring$where = ""

Optional partial-index WHERE predicate. Supported by PostgreSQL and SQLite. Empty string means no predicate.

Methods

Public · 8

__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.

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.

isConcurrent()

public function isConcurrent(): bool;

Whether the index is built CONCURRENTLY (PostgreSQL only).

isInvisible()

public function isInvisible(): bool;

Whether the index is declared INVISIBLE (MySQL 8.0+).

Db\IndexInterface

InterfaceSource on GitHub

Phalcon\Db\IndexInterface

Uses Phalcon\Contracts\Db\Index

Db\Profiler

ClassSource on GitHub

Instances 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

Properties

protectedItem|null$activeProfile = null

Active Item

protectedItem[]$allProfiles = []

All the Items in the active profile

protectedint$maxProfiles = 0

Maximum 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 = 0

Total time spent by all profiles to complete in nanoseconds

Methods

Public · 9

getLastProfile()

public function getLastProfile(): Item|null;

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(): array;

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 GitHub

This class identifies each profile in a Phalcon\Db\Profiler

  • Phalcon\Db\Profiler\Item

Uses Phalcon\Db\Traits\ElapsedTimeTrait

Method Summary

Properties

protectedfloat$finalTime

Timestamp when the profile ended

protectedfloat$initialTime

Timestamp when the profile started

protectedarray$sqlBindTypes

SQL bind types related to the profile

protectedstring$sqlStatement

SQL statement related to the profile

protectedarray$sqlVariables

SQL variables related to the profile

Methods

Public · 11

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 GitHub

This 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();

WARNING: a RawValue is emitted into the SQL verbatim, with no quoting or escaping - including a RawValue passed as a query bind-parameter value, which is spliced into the compiled SQL string rather than bound. Never wrap request-derived or otherwise untrusted data in a RawValue; use ordinary bind parameters for those. RawValue is only for developer-authored SQL fragments (for example database functions such as now()).

  • Phalcon\Db\RawValue

Method Summary

Properties

protectedstring$value

Raw value without quoting or formatting

Methods

Public · 3

__construct()

public function __construct( mixed $value = null );

Phalcon\Db\RawValue constructor

__toString()

public function __toString(): string;

getValue()

public function getValue(): string;

Db\Reference

ClassSource on GitHub

Allows to define reference constraints on tables

$reference = new \Phalcon\Db\Reference(
    "field_fk",
    [
        "referencedSchema"  => "invoicing",
        "referencedTable"   => "products",
        "columns"           => [
            "producttype",
            "product_code",
        ],
        "referencedColumns" => [
            "type",
            "code",
        ],
    ]
);

Uses Phalcon\Db\Exceptions\ForeignKeyColumnsRequired · Phalcon\Db\Exceptions\ReferencedColumnCountMismatch · Phalcon\Db\Exceptions\ReferencedColumnsRequired · Phalcon\Db\Exceptions\ReferencedTableRequired

Method Summary

Properties

protectedarray$columns

Local reference columns

protectedstring$name
protectedstring|null$onDelete = null

ON DELETE

protectedstring|null$onUpdate = null

ON UPDATE

protectedarray$referencedColumns

Referenced Columns

protectedstring|null$referencedSchema = null

Referenced Schema

protectedstring$referencedTable

Referenced Table

protectedstring|null$schemaName = null

Schema name

Methods

Public · 9

__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 GitHub

Phalcon\Db\ReferenceInterface

Uses Phalcon\Contracts\Db\Reference

Db\ResultInterface

InterfaceSource on GitHub

Phalcon\Db\ResultInterface

Uses Phalcon\Contracts\Db\Result

Db\Result\PdoResult

ClassSource on GitHub

Encapsulates 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);
}

Uses PDOStatement · Phalcon\Db\Adapter\AdapterInterface · Phalcon\Db\Enum · Phalcon\Db\ResultInterface

Method Summary

Properties

protectedarray$bindParams = []
protectedarray$bindTypes = []
protectedAdapterInterface$connection
protectedint$fetchMode = Enum::FETCH_DEFAULT

Active fetch mode

protectedPDOStatement$pdoStatement
protectedmixed$result
protectedint|null$rowCount = null
protectedstring$sqlStatement = ""

Methods

Public · 9

__construct()

public function __construct(
    AdapterInterface $connection,
    PDOStatement $pdoStatement,
    string $sqlStatement = "",
    array $bindParams = [],
    array $bindTypes = []
);

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
): mixed;

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,
    array|null $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(): mixed;

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,
    object|string|null $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 GitHub

Derives 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

Methods

Public · 3

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

Navigation

Type to search…

↑↓ navigate↵ selectEsc close