Database Abstraction Layer


Layer - 图1

Overview

Phalcon\Db is the component behind Phalcon\Mvc\Model that powers the model layer in the framework. It consists of an independent high-level abstraction layer for database systems completely written in C.

This component allows for a lower level database manipulation than using traditional models.

Database Adapters

This component makes use of adapters to encapsulate specific database system details. Phalcon uses PDO to connect to databases. The following database engines are supported:

ClassDescription
Phalcon\Db\Adapter\Pdo\MysqlIs the world’s most used relational database management system (RDBMS) that runs as a server providing multi-user access to a number of databases
Phalcon\Db\Adapter\Pdo\PostgresqlPostgreSQL is a powerful, open source relational database system. It has more than 15 years of active development and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness.
Phalcon\Db\Adapter\Pdo\SqliteSQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine

Factory

Loads PDO Adapter class using adapter option. For example:

  1. <?php
  2. use Phalcon\Db\Adapter\PdoFactory;
  3. $config = [
  4. 'adapter' => 'mysql',
  5. 'options' => [
  6. 'host' => 'localhost',
  7. 'dbname' => 'blog',
  8. 'port' => 3306,
  9. 'username' => 'sigma',
  10. 'password' => 'secret',
  11. ],
  12. ];
  13. $db = (new PdoFactory())->load($config);

Implementing your own adapters

The Phalcon\Db\AdapterInterface interface must be implemented in order to create your own database adapters or extend the existing ones.

Database Dialects

Phalcon encapsulates the specific details of each database engine in dialects. Those provide common functions and SQL generator to the adapters.

ClassDescription
Phalcon\Db\Dialect\MysqlSQL specific dialect for MySQL database system
Phalcon\Db\Dialect\PostgresqlSQL specific dialect for PostgreSQL database system
Phalcon\Db\Dialect\SqliteSQL specific dialect for SQLite database system

Implementing your own dialects

The Phalcon\Db\DialectInterface interface must be implemented in order to create your own database dialects or extend the existing ones. You can also enhance your current dialect by adding more commands/methods that PHQL will understand.

For instance when using the MySQL adapter, you might want to allow PHQL to recognize the MATCH … AGAINST … syntax. We associate that syntax with MATCH_AGAINST

We instantiate the dialect. We add the custom function so that PHQL understands what to do when it finds it during the parsing process. In the example below, we register a new custom function called MATCH_AGAINST. After that all we have to do is add the customized dialect object to our connection.

  1. <?php
  2. use Phalcon\Db\Dialect\MySQL as SqlDialect;
  3. use Phalcon\Db\Adapter\Pdo\MySQL as Connection;
  4. $dialect = new SqlDialect();
  5. $dialect->registerCustomFunction(
  6. 'MATCH_AGAINST',
  7. function($dialect, $expression) {
  8. $arguments = $expression['arguments'];
  9. return sprintf(
  10. " MATCH (%s) AGAINST (%)",
  11. $dialect->getSqlExpression($arguments[0]),
  12. $dialect->getSqlExpression($arguments[1])
  13. );
  14. }
  15. );
  16. $connection = new Connection(
  17. [
  18. "host" => "localhost",
  19. "username" => "root",
  20. "password" => "",
  21. "dbname" => "test",
  22. "dialectClass" => $dialect,
  23. ]
  24. );

We can now use this new function in PHQL, which in turn will translate it to the proper SQL syntax:

  1. $phql = "
  2. SELECT *
  3. FROM Posts
  4. WHERE MATCH_AGAINST(title, :pattern:)";
  5. $posts = $modelsManager->executeQuery(
  6. $phql,
  7. [
  8. 'pattern' => $pattern,
  9. ]
  10. );

Connecting to Databases

To create a connection it’s necessary instantiate the adapter class. It only requires an array with the connection parameters. The example below shows how to create a connection passing both required and optional parameters:

MySQL Required elements
  1. <?php
  2. $config = [
  3. 'host' => '127.0.0.1',
  4. 'username' => 'mike',
  5. 'password' => 'sigma',
  6. 'dbname' => 'test_db',
  7. ];
MySQL Optional
  1. $config['persistent'] = false;
MySQL Create a connection
  1. $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config);
PostgreSQL Required elements
  1. <?php
  2. $config = [
  3. 'host' => 'localhost',
  4. 'username' => 'postgres',
  5. 'password' => 'secret1',
  6. 'dbname' => 'template',
  7. ];
PostgreSQL Optional
  1. $config['schema'] = 'public';
PostgreSQL Create a connection
  1. $connection = new \Phalcon\Db\Adapter\Pdo\Postgresql($config);
SQLite Required elements
  1. <?php
  2. $config = [
  3. 'dbname' => '/path/to/database.db',
  4. ];
SQLite Create a connection
  1. $connection = new \Phalcon\Db\Adapter\Pdo\Sqlite($config);

Setting up additional PDO options

You can set PDO options at connection time by passing the parameters options:

  1. <?php
  2. $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(
  3. [
  4. 'host' => 'localhost',
  5. 'username' => 'root',
  6. 'password' => 'sigma',
  7. 'dbname' => 'test_db',
  8. 'options' => [
  9. PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
  10. PDO::ATTR_CASE => PDO::CASE_LOWER,
  11. ]
  12. ]
  13. );

Connecting using Factory

You can also use a simple ini file to configure/connect your db service to your database.

  1. [database]
  2. host = TEST_DB_MYSQL_HOST
  3. username = TEST_DB_MYSQL_USER
  4. password = TEST_DB_MYSQL_PASSWD
  5. dbname = TEST_DB_MYSQL_NAME
  6. port = TEST_DB_MYSQL_PORT
  7. charset = TEST_DB_MYSQL_CHARSET
  8. adapter = mysql
  1. <?php
  2. use Phalcon\Config\Adapter\Ini;
  3. use Phalcon\Di;
  4. use Phalcon\Db\Adapter\Pdo\Factory;
  5. $di = new Di();
  6. $config = new Ini('config.ini');
  7. $di->set('config', $config);
  8. $di->set(
  9. 'db',
  10. function () {
  11. return Factory::load($this->config->database);
  12. }
  13. );

The above will return the correct database instance and also has the advantage that you can change the connection credentials or even the database adapter without changing a single line of code in your application.

Finding Rows

Phalcon\Db provides several methods to query rows from tables. The specific SQL syntax of the target database engine is required in this case:

  1. <?php
  2. $sql = 'SELECT id, name FROM robots ORDER BY name';
  3. // Send a SQL statement to the database system
  4. $result = $connection->query($sql);
  5. // Print each robot name
  6. while ($robot = $result->fetch()) {
  7. echo $robot['name'];
  8. }
  9. // Get all rows in an array
  10. $robots = $connection->fetchAll($sql);
  11. foreach ($robots as $robot) {
  12. echo $robot['name'];
  13. }
  14. // Get only the first row
  15. $robot = $connection->fetchOne($sql);

By default these calls create arrays with both associative and numeric indexes. You can change this behavior by using Phalcon\Db\Result::setFetchMode(). This method receives a constant, defining which kind of index is required.

ConstantDescription
Phalcon\Db::FETCH_NUMReturn an array with numeric indexes
Phalcon\Db::FETCH_ASSOCReturn an array with associative indexes
Phalcon\Db::FETCH_BOTHReturn an array with both associative and numeric indexes
Phalcon\Db::FETCH_OBJReturn an object instead of an array
  1. <?php
  2. $sql = 'SELECT id, name FROM robots ORDER BY name';
  3. $result = $connection->query($sql);
  4. $result->setFetchMode(
  5. Phalcon\Db::FETCH_NUM
  6. );
  7. while ($robot = $result->fetch()) {
  8. echo $robot[0];
  9. }

The Phalcon\Db::query() returns an instance of Phalcon\Db\Result\Pdo. These objects encapsulate all the functionality related to the returned resultset i.e. traversing, seeking specific records, count etc.

  1. <?php
  2. $sql = 'SELECT id, name FROM robots';
  3. $result = $connection->query($sql);
  4. // Traverse the resultset
  5. while ($robot = $result->fetch()) {
  6. echo $robot['name'];
  7. }
  8. // Seek to the third row
  9. $result->seek(2);
  10. $robot = $result->fetch();
  11. // Count the resultset
  12. echo $result->numRows();

Binding Parameters

Bound parameters is also supported in Phalcon\Db. Although there is a minimal performance impact by using bound parameters, you are encouraged to use this methodology so as to eliminate the possibility of your code being subject to SQL injection attacks. Both string and positional placeholders are supported. Binding parameters can simply be achieved as follows:

  1. <?php
  2. // Binding with numeric placeholders
  3. $sql = 'SELECT * FROM robots WHERE name = ? ORDER BY name';
  4. $result = $connection->query(
  5. $sql,
  6. [
  7. 'Wall-E',
  8. ]
  9. );
  10. // Binding with named placeholders
  11. $sql = 'INSERT INTO `robots`(name`, year) VALUES (:name, :year)';
  12. $success = $connection->query(
  13. $sql,
  14. [
  15. 'name' => 'Astro Boy',
  16. 'year' => 1952,
  17. ]
  18. );

When using numeric placeholders, you will need to define them as integers i.e. 1 or 2. In this case ‘1’ or ‘2’ are considered strings and not numbers, so the placeholder could not be successfully replaced. With any adapter data are automatically escaped using PDO Quote.

This function takes into account the connection charset, so its recommended to define the correct charset in the connection parameters or in your database server configuration, as a wrong charset will produce undesired effects when storing or retrieving data.

Also, you can pass your parameters directly to the execute or query methods. In this case bound parameters are directly passed to PDO:

  1. <?php
  2. // Binding with PDO placeholders
  3. $sql = 'SELECT * FROM robots WHERE name = ? ORDER BY name';
  4. $result = $connection->query(
  5. $sql,
  6. [
  7. 1 => 'Wall-E',
  8. ]
  9. );

Typed placeholders

Placeholders allowed you to bind parameters to avoid SQL injections:

  1. <?php
  2. $phql = "SELECT * FROM Store\Robots WHERE id > :id:";
  3. $robots = $this->modelsManager->executeQuery(
  4. $phql,
  5. [
  6. 'id' => 100,
  7. ]
  8. );

However, some database systems require additional actions when using placeholders such as specifying the type of the bound parameter:

  1. <?php
  2. use Phalcon\Db\Column;
  3. // ...
  4. $phql = "SELECT * FROM Store\Robots LIMIT :number:";
  5. $robots = $this->modelsManager->executeQuery(
  6. $phql,
  7. [
  8. 'number' => 10,
  9. ],
  10. Column::BIND_PARAM_INT
  11. );

You can use typed placeholders in your parameters, instead of specifying the bind type in executeQuery():

  1. <?php
  2. $phql = "SELECT * FROM Store\Robots LIMIT {number:int}";
  3. $robots = $this->modelsManager->executeQuery(
  4. $phql,
  5. [
  6. 'number' => 10,
  7. ]
  8. );
  9. $phql = "SELECT * FROM Store\Robots WHERE name <> {name:str}";
  10. $robots = $this->modelsManager->executeQuery(
  11. $phql,
  12. [
  13. 'name' => $name,
  14. ]
  15. );

You can also omit the type if you don’t need to specify it:

  1. <?php
  2. $phql = "SELECT * FROM Store\Robots WHERE name <> {name}";
  3. $robots = $this->modelsManager->executeQuery(
  4. $phql,
  5. [
  6. 'name' => $name,
  7. ]
  8. );

Typed placeholders are also more powerful, since we can now bind a static array without having to pass each element independently as a placeholder:

  1. <?php
  2. $phql = "SELECT * FROM Store\Robots WHERE id IN ({ids:array})";
  3. $robots = $this->modelsManager->executeQuery(
  4. $phql,
  5. [
  6. 'ids' => [1, 2, 3, 4],
  7. ]
  8. );

The following types are available:

Bind TypeBind Type ConstantExample
strColumn::BIND_PARAM_STR{name:str}
intColumn::BIND_PARAM_INT{number:int}
doubleColumn::BIND_PARAM_DECIMAL{price:double}
boolColumn::BIND_PARAM_BOOL{enabled:bool}
blobColumn::BIND_PARAM_BLOB{image:blob}
nullColumn::BIND_PARAM_NULL{exists:null}
arrayArray of Column::BIND_PARAM_STR{codes:array}
array-strArray of Column::BIND_PARAM_STR{names:array-str}
array-intArray of Column::BIND_PARAM_INT{flags:array-int}

Cast bound parameters values

By default, bound parameters aren’t casted in the PHP userland to the specified bind types, this option allows you to make Phalcon cast values before bind them with PDO. A classic situation when this problem raises is passing a string in a LIMIT/OFFSET placeholder:

  1. <?php
  2. $number = '100';
  3. $robots = $modelsManager->executeQuery(
  4. 'SELECT * FROM Some\Robots LIMIT {number:int}',
  5. [
  6. 'number' => $number,
  7. ]
  8. );

This causes the following exception:

  1. Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]:
  2. Syntax error or access violation: 1064 You have an error in your SQL syntax;
  3. check the manual that corresponds to your MySQL server version for the right
  4. syntax to use near ''100'' at line 1' in /Users/scott/demo.php:78

This happens because 100 is a string variable. It is easily fixable by casting the value to integer first:

  1. <?php
  2. $number = '100';
  3. $robots = $modelsManager->executeQuery(
  4. 'SELECT * FROM Some\Robots LIMIT {number:int}',
  5. [
  6. 'number' => (int) $number,
  7. ]
  8. );

However this solution requires that the developer pays special attention about how bound parameters are passed and their types. To make this task easier and avoid unexpected exceptions you can instruct Phalcon to do this casting for you:

  1. <?php
  2. \Phalcon\Db::setup(
  3. [
  4. 'forceCasting' => true,
  5. ]
  6. );

The following actions are performed according to the bind type specified:

Bind TypeAction
Column::BIND_PARAM_STRCast the value as a native PHP string
Column::BIND_PARAM_INTCast the value as a native PHP integer
Column::BIND_PARAM_BOOLCast the value as a native PHP boolean
Column::BIND_PARAM_DECIMALCast the value as a native PHP double

Cast on Hydrate

Values returned from the database system are always represented as string values by PDO, no matter if the value belongs to a numerical or boolean type column. This happens because some column types cannot be represented with its corresponding PHP native types due to their size limitations. For instance, a BIGINT in MySQL can store large integer numbers that cannot be represented as a 32bit integer in PHP. Because of that, PDO and the ORM by default, make the safe decision of leaving all values as strings.

You can set up the ORM to automatically cast those types considered safe to their corresponding PHP native types:

  1. <?php
  2. \Phalcon\Mvc\Model::setup(
  3. [
  4. 'castOnHydrate' => true,
  5. ]
  6. );

This way you can use strict operators or make assumptions about the type of variables:

  1. <?php
  2. $robot = Robots::findFirst();
  3. if (11 === $robot->id) {
  4. echo $robot->name;
  5. }

Inserting/Updating/Deleting Rows

To insert, update or delete rows, you can use raw SQL or use the preset functions provided by the class:

  1. <?php
  2. // Inserting data with a raw SQL statement
  3. $sql = 'INSERT INTO `robots`(`name`, `year`) VALUES ("Astro Boy", 1952)';
  4. $success = $connection->execute($sql);
  5. // With placeholders
  6. $sql = 'INSERT INTO `robots`(`name`, `year`) VALUES (?, ?)';
  7. $success = $connection->execute(
  8. $sql,
  9. [
  10. 'Astro Boy',
  11. 1952,
  12. ]
  13. );
  14. // Generating dynamically the necessary SQL
  15. $success = $connection->insert(
  16. 'robots',
  17. [
  18. 'Astro Boy',
  19. 1952,
  20. ],
  21. [
  22. 'name',
  23. 'year',
  24. ],
  25. );
  26. // Generating dynamically the necessary SQL (another syntax)
  27. $success = $connection->insertAsDict(
  28. 'robots',
  29. [
  30. 'name' => 'Astro Boy',
  31. 'year' => 1952,
  32. ]
  33. );
  34. // Updating data with a raw SQL statement
  35. $sql = 'UPDATE `robots` SET `name` = "Astro boy" WHERE `id` = 101';
  36. $success = $connection->execute($sql);
  37. // With placeholders
  38. $sql = 'UPDATE `robots` SET `name` = ? WHERE `id` = ?';
  39. $success = $connection->execute(
  40. $sql,
  41. [
  42. 'Astro Boy',
  43. 101,
  44. ]
  45. );
  46. // Generating dynamically the necessary SQL
  47. $success = $connection->update(
  48. 'robots',
  49. [
  50. 'name',
  51. ],
  52. [
  53. 'New Astro Boy',
  54. ],
  55. 'id = 101' // Warning! In this case values are not escaped
  56. );
  57. // Generating dynamically the necessary SQL (another syntax)
  58. $success = $connection->updateAsDict(
  59. 'robots',
  60. [
  61. 'name' => 'New Astro Boy',
  62. ],
  63. 'id = 101' // Warning! In this case values are not escaped
  64. );
  65. // With escaping conditions
  66. $success = $connection->update(
  67. 'robots',
  68. [
  69. 'name',
  70. ],
  71. [
  72. 'New Astro Boy',
  73. ],
  74. [
  75. 'conditions' => 'id = ?',
  76. 'bind' => [101],
  77. 'bindTypes' => [PDO::PARAM_INT], // Optional parameter
  78. ]
  79. );
  80. $success = $connection->updateAsDict(
  81. 'robots',
  82. [
  83. 'name' => 'New Astro Boy',
  84. ],
  85. [
  86. 'conditions' => 'id = ?',
  87. 'bind' => [101],
  88. 'bindTypes' => [PDO::PARAM_INT], // Optional parameter
  89. ]
  90. );
  91. // Deleting data with a raw SQL statement
  92. $sql = 'DELETE `robots` WHERE `id` = 101';
  93. $success = $connection->execute($sql);
  94. // With placeholders
  95. $sql = 'DELETE `robots` WHERE `id` = ?';
  96. $success = $connection->execute($sql, [101]);
  97. // Generating dynamically the necessary SQL
  98. $success = $connection->delete(
  99. 'robots',
  100. 'id = ?',
  101. [
  102. 101,
  103. ]
  104. );

Transactions and Nested Transactions

Working with transactions is supported as it is with PDO. Perform data manipulation inside transactions often increase the performance on most database systems:

  1. <?php
  2. try {
  3. // Start a transaction
  4. $connection->begin();
  5. // Execute some SQL statements
  6. $connection->execute('DELETE `robots` WHERE `id` = 101');
  7. $connection->execute('DELETE `robots` WHERE `id` = 102');
  8. $connection->execute('DELETE `robots` WHERE `id` = 103');
  9. // Commit if everything goes well
  10. $connection->commit();
  11. } catch (Exception $e) {
  12. // An exception has occurred rollback the transaction
  13. $connection->rollback();
  14. }

In addition to standard transactions, Phalcon\Db provides built-in support for nested transactions (if the database system used supports them). When you call begin() for a second time a nested transaction is created:

  1. <?php
  2. try {
  3. // Start a transaction
  4. $connection->begin();
  5. // Execute some SQL statements
  6. $connection->execute('DELETE `robots` WHERE `id` = 101');
  7. try {
  8. // Start a nested transaction
  9. $connection->begin();
  10. // Execute these SQL statements into the nested transaction
  11. $connection->execute('DELETE `robots` WHERE `id` = 102');
  12. $connection->execute('DELETE `robots` WHERE `id` = 103');
  13. // Create a save point
  14. $connection->commit();
  15. } catch (Exception $e) {
  16. // An error has occurred, release the nested transaction
  17. $connection->rollback();
  18. }
  19. // Continue, executing more SQL statements
  20. $connection->execute('DELETE `robots` WHERE `id` = 104');
  21. // Commit if everything goes well
  22. $connection->commit();
  23. } catch (Exception $e) {
  24. // An exception has occurred rollback the transaction
  25. $connection->rollback();
  26. }

Database Events

Phalcon\Db is able to send events to a EventsManager if it’s present. Some events when returning boolean false could stop the active operation. The following events are supported:

Event NameTriggeredCan stop operation?
afterConnectAfter a successfully connection to a database systemNo
afterQueryAfter send a SQL statement to database systemNo
beforeDisconnectBefore close a temporal database connectionNo
beforeQueryBefore send a SQL statement to the database systemYes
beginTransactionBefore a transaction is going to be startedNo
commitTransactionBefore a transaction is committedNo
rollbackTransactionBefore a transaction is rollbackedNo

Bind an EventsManager to a connection is simple, Phalcon\Db will trigger the events with the type db:

  1. <?php
  2. use Phalcon\Events\Manager as EventsManager;
  3. use Phalcon\Db\Adapter\Pdo\Mysql as Connection;
  4. $eventsManager = new EventsManager();
  5. // Listen all the database events
  6. $eventsManager->attach('db', $dbListener);
  7. $connection = new Connection(
  8. [
  9. 'host' => 'localhost',
  10. 'username' => 'root',
  11. 'password' => 'secret',
  12. 'dbname' => 'invo',
  13. ]
  14. );
  15. // Assign the eventsManager to the db adapter instance
  16. $connection->setEventsManager($eventsManager);

Stop SQL operations are very useful if for example you want to implement some last-resource SQL injector checker:

  1. <?php
  2. use Phalcon\Events\Event;
  3. $eventsManager->attach(
  4. 'db:beforeQuery',
  5. function (Event $event, $connection) {
  6. $sql = $connection->getSQLStatement();
  7. // Check for malicious words in SQL statements
  8. if (preg_match('/DROP|ALTER/i', $sql)) {
  9. // DROP/ALTER operations aren't allowed in the application,
  10. // this must be a SQL injection!
  11. return false;
  12. }
  13. // It's OK
  14. return true;
  15. }
  16. );

Profiling SQL Statements

Phalcon\Db includes a profiling component called Phalcon\Db\Profiler, that is used to analyze the performance of database operations so as to diagnose performance problems and discover bottlenecks.

Database profiling is really easy With Phalcon\Db\Profiler:

  1. <?php
  2. use Phalcon\Events\Event;
  3. use Phalcon\Events\Manager as EventsManager;
  4. use Phalcon\Db\Profiler as DbProfiler;
  5. $eventsManager = new EventsManager();
  6. $profiler = new DbProfiler();
  7. // Listen all the database events
  8. $eventsManager->attach(
  9. 'db',
  10. function (Event $event, $connection) use ($profiler) {
  11. if ($event->getType() === 'beforeQuery') {
  12. $sql = $connection->getSQLStatement();
  13. // Start a profile with the active connection
  14. $profiler->startProfile($sql);
  15. }
  16. if ($event->getType() === 'afterQuery') {
  17. // Stop the active profile
  18. $profiler->stopProfile();
  19. }
  20. }
  21. );
  22. // Assign the events manager to the connection
  23. $connection->setEventsManager($eventsManager);
  24. $sql = 'SELECT buyer_name, quantity, product_name '
  25. . 'FROM buyers '
  26. . 'LEFT JOIN products ON buyers.pid = products.id';
  27. // Execute a SQL statement
  28. $connection->query($sql);
  29. // Get the last profile in the profiler
  30. $profile = $profiler->getLastProfile();
  31. echo 'SQL Statement: ', $profile->getSQLStatement(), "\n";
  32. echo 'Start Time: ', $profile->getInitialTime(), "\n";
  33. echo 'Final Time: ', $profile->getFinalTime(), "\n";
  34. echo 'Total Elapsed Time: ', $profile->getTotalElapsedSeconds(), "\n";

You can also create your own profile class based on Phalcon\Db\Profiler to record real time statistics of the statements sent to the database system:

  1. <?php
  2. use Phalcon\Events\Manager as EventsManager;
  3. use Phalcon\Db\Profiler as Profiler;
  4. use Phalcon\Db\Profiler\Item as Item;
  5. class DbProfiler extends Profiler
  6. {
  7. /**
  8. * Executed before the SQL statement will sent to the db server
  9. */
  10. public function beforeStartProfile(Item $profile)
  11. {
  12. echo $profile->getSQLStatement();
  13. }
  14. /**
  15. * Executed after the SQL statement was sent to the db server
  16. */
  17. public function afterEndProfile(Item $profile)
  18. {
  19. echo $profile->getTotalElapsedSeconds();
  20. }
  21. }
  22. // Create an Events Manager
  23. $eventsManager = new EventsManager();
  24. // Create a listener
  25. $dbProfiler = new DbProfiler();
  26. // Attach the listener listening for all database events
  27. $eventsManager->attach('db', $dbProfiler);

Logging SQL Statements

Using high-level abstraction components such as Phalcon\Db to access a database, it is difficult to understand which statements are sent to the database system. Phalcon\Logger interacts with Phalcon\Db, providing logging capabilities on the database abstraction layer.

  1. <?php
  2. use Phalcon\Logger;
  3. use Phalcon\Events\Event;
  4. use Phalcon\Events\Manager as EventsManager;
  5. use Phalcon\Logger\Adapter\File as FileLogger;
  6. $eventsManager = new EventsManager();
  7. $logger = new FileLogger('app/logs/db.log');
  8. $eventsManager->attach(
  9. 'db:beforeQuery',
  10. function (Event $event, $connection) use ($logger) {
  11. $sql = $connection->getSQLStatement();
  12. $logger->log($sql, Logger::INFO);
  13. }
  14. );
  15. // Assign the eventsManager to the db adapter instance
  16. $connection->setEventsManager($eventsManager);
  17. // Execute some SQL statement
  18. $connection->insert(
  19. 'products',
  20. [
  21. 'Hot pepper',
  22. 3.50,
  23. ],
  24. [
  25. 'name',
  26. 'price',
  27. ]
  28. );

As above, the file app/logs/db.log will contain something like this:

  1. [Sun, 29 Apr 12 22:35:26 -0500][DEBUG][Resource Id #77] INSERT INTO products
  2. (name, price) VALUES ('Hot pepper', 3.50)

Implementing your own Logger

You can implement your own logger class for database queries, by creating a class that implements a single method called log. The method needs to accept a string as the first argument. You can then pass your logging object to Phalcon\Db::setLogger(), and from then on any SQL statement executed will call that method to log the results.

Describing Tables/Views

Phalcon\Db also provides methods to retrieve detailed information about tables and views:

  1. <?php
  2. // Get tables on the test_db database
  3. $tables = $connection->listTables('test_db');
  4. // Is there a table 'robots' in the database?
  5. $exists = $connection->tableExists('robots');
  6. // Get name, data types and special features of 'robots' fields
  7. $fields = $connection->describeColumns('robots');
  8. foreach ($fields as $field) {
  9. echo 'Column Type: ', $field['Type'];
  10. }
  11. // Get indexes on the 'robots' table
  12. $indexes = $connection->describeIndexes('robots');
  13. foreach ($indexes as $index) {
  14. print_r(
  15. $index->getColumns()
  16. );
  17. }
  18. // Get foreign keys on the 'robots' table
  19. $references = $connection->describeReferences('robots');
  20. foreach ($references as $reference) {
  21. // Print referenced columns
  22. print_r(
  23. $reference->getReferencedColumns()
  24. );
  25. }

A table description is very similar to the MySQL DESCRIBE command, it contains the following information:

FieldTypeKeyNull
Field’s nameColumn TypeIs the column part of the primary key or an index?Does the column allow null values?

Methods to get information about views are also implemented for every supported database system:

  1. <?php
  2. // Get views on the test_db database
  3. $tables = $connection->listViews('test_db');
  4. // Is there a view 'robots' in the database?
  5. $exists = $connection->viewExists('robots');

Creating/Altering/Dropping Tables

Different database systems (MySQL, Postgresql etc.) offer the ability to create, alter or drop tables with the use of commands such as CREATE, ALTER or DROP. The SQL syntax differs based on which database system is used. Phalcon\Db offers a unified interface to alter tables, without the need to differentiate the SQL syntax based on the target storage system.

Creating Tables

The following example shows how to create a table:

  1. <?php
  2. use \Phalcon\Db\Column as Column;
  3. $connection->createTable(
  4. 'robots',
  5. null,
  6. [
  7. 'columns' => [
  8. new Column(
  9. 'id',
  10. [
  11. 'type' => Column::TYPE_INTEGER,
  12. 'size' => 10,
  13. 'notNull' => true,
  14. 'autoIncrement' => true,
  15. 'primary' => true,
  16. ]
  17. ),
  18. new Column(
  19. 'name',
  20. [
  21. 'type' => Column::TYPE_VARCHAR,
  22. 'size' => 70,
  23. 'notNull' => true,
  24. ]
  25. ),
  26. new Column(
  27. 'year',
  28. [
  29. 'type' => Column::TYPE_INTEGER,
  30. 'size' => 11,
  31. 'notNull' => true,
  32. ]
  33. ),
  34. ]
  35. ]
  36. );

Phalcon\Db::createTable() accepts an associative array describing the table. Columns are defined with the class Phalcon\Db\Column. The table below shows the options available to define a column:

OptionDescriptionOptional
typeColumn type. Must be a Phalcon\Db\Column constant (see below for a list)No
primaryTrue if the column is part of the table’s primary keyYes
sizeSome type of columns like VARCHAR or INTEGER may have a specific sizeYes
scaleDECIMAL or NUMBER columns may be have a scale to specify how many decimals should be storedYes
unsignedINTEGER columns may be signed or unsigned. This option does not apply to other types of columnsYes
notNullColumn can store null values?Yes
defaultDefault value (when used with 'notNull' => true).Yes
autoIncrementWith this attribute column will filled automatically with an auto-increment integer. Only one column in the table can have this attribute.Yes
bindOne of the BINDTYPE* constants telling how the column must be bound before save itYes
firstColumn must be placed at first position in the column orderYes
afterColumn must be placed after indicated columnYes

Phalcon\Db supports the following database column types:

  • Phalcon\Db\Column::TYPE_INTEGER
  • Phalcon\Db\Column::TYPE_DATE
  • Phalcon\Db\Column::TYPE_VARCHAR
  • Phalcon\Db\Column::TYPE_DECIMAL
  • Phalcon\Db\Column::TYPE_DATETIME
  • Phalcon\Db\Column::TYPE_CHAR
  • Phalcon\Db\Column::TYPE_TEXTThe associative array passed in Phalcon\Db::createTable() can have the possible keys:
IndexDescriptionOptional
columnsAn array with a set of table columns defined with Phalcon\Db\ColumnNo
indexesAn array with a set of table indexes defined with Phalcon\Db\IndexYes
referencesAn array with a set of table references (foreign keys) defined with Phalcon\Db\ReferenceYes
optionsAn array with a set of table creation options. These options often relate to the database system in which the migration was generated.Yes

Altering Tables

As your application grows, you might need to alter your database, as part of a refactoring or adding new features. Not all database systems allow to modify existing columns or add columns between two existing ones. Phalcon\Db is limited by these constraints.

  1. <?php
  2. use Phalcon\Db\Column as Column;
  3. // Adding a new column
  4. $connection->addColumn(
  5. 'robots',
  6. null,
  7. new Column(
  8. 'robot_type',
  9. [
  10. 'type' => Column::TYPE_VARCHAR,
  11. 'size' => 32,
  12. 'notNull' => true,
  13. 'after' => 'name',
  14. ]
  15. )
  16. );
  17. // Modifying an existing column
  18. $connection->modifyColumn(
  19. 'robots',
  20. null,
  21. new Column(
  22. 'name',
  23. [
  24. 'type' => Column::TYPE_VARCHAR,
  25. 'size' => 40,
  26. 'notNull' => true,
  27. ]
  28. )
  29. );
  30. // Deleting the column 'name'
  31. $connection->dropColumn(
  32. 'robots',
  33. null,
  34. 'name'
  35. );

Dropping Tables

To drop an existing table from the current database, use the dropTable method. To drop an table from custom database, use second parameter describes database name. Examples on dropping tables:

  1. <?php
  2. // Drop table 'robots' from active database
  3. $connection->dropTable('robots');
  4. // Drop table 'robots' from database 'machines'
  5. $connection->dropTable('robots', 'machines');