{"id":29017831,"url":"https://github.com/cakephp/database","last_synced_at":"2025-06-25T23:07:07.523Z","repository":{"id":25269195,"uuid":"28694634","full_name":"cakephp/database","owner":"cakephp","description":"[READ-ONLY] Flexible and powerful Database abstraction library with a familiar PDO-like API. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp","archived":false,"fork":false,"pushed_at":"2025-06-21T03:34:47.000Z","size":3425,"stargazers_count":96,"open_issues_count":0,"forks_count":12,"subscribers_count":29,"default_branch":"master","last_synced_at":"2025-06-21T04:29:43.534Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cakephp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2015-01-01T20:14:01.000Z","updated_at":"2025-05-19T08:15:31.000Z","dependencies_parsed_at":"2023-01-14T02:26:29.771Z","dependency_job_id":"21362e75-9156-4d80-b8c4-2b18b0b6975d","html_url":"https://github.com/cakephp/database","commit_stats":{"total_commits":1541,"total_committers":118,"mean_commits":"13.059322033898304","dds":0.7793640493186242,"last_synced_commit":"ef7f8ca5e782d54483267a0617118cac09768e57"},"previous_names":[],"tags_count":306,"template":false,"template_full_name":null,"purl":"pkg:github/cakephp/database","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cakephp%2Fdatabase","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cakephp%2Fdatabase/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cakephp%2Fdatabase/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cakephp%2Fdatabase/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cakephp","download_url":"https://codeload.github.com/cakephp/database/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cakephp%2Fdatabase/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":261967132,"owners_count":23237663,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-06-25T23:07:06.826Z","updated_at":"2025-06-25T23:07:07.503Z","avatar_url":"https://github.com/cakephp.png","language":"PHP","readme":"[![Total Downloads](https://img.shields.io/packagist/dt/cakephp/database.svg?style=flat-square)](https://packagist.org/packages/cakephp/database)\n[![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](LICENSE.txt)\n\n# A flexible and lightweight Database Library for PHP\n\nThis library abstracts and provides help with most aspects of dealing with relational\ndatabases such as keeping connections to the server, building queries,\npreventing SQL injections, inspecting and altering schemas, and with debugging and\nprofiling queries sent to the database.\n\nIt adopts the API from the native PDO extension in PHP for familiarity, but solves many of the\ninconsistencies PDO has, while also providing several features that extend PDO's capabilities.\n\nA distinguishing factor of this library when compared to similar database connection packages,\nis that it takes the concept of \"data types\" to its core. It lets you work with complex PHP objects\nor structures that can be passed as query conditions or to be inserted in the database.\n\nThe typing system will intelligently convert the PHP structures when passing them to the database, and\nconvert them back when retrieving.\n\n\n## Connecting to the database\n\nThis library is able to work with the following databases:\n\n* MySQL\n* Postgres\n* SQLite\n* Microsoft SQL Server (2008 and above)\n\nThe first thing you need to do when using this library is create a connection object.\nBefore performing any operations with the connection, you need to specify a driver\nto use:\n\n```php\nuse Cake\\Database\\Connection;\nuse Cake\\Database\\Driver\\Mysql;\n\n$driver = new Mysql([\n\t'database' =\u003e 'test',\n\t'username' =\u003e 'root',\n\t'password' =\u003e 'secret'\n]);\n$connection = new Connection([\n\t'driver' =\u003e $driver\n]);\n```\n\nDrivers are classes responsible for actually executing the commands to the database and\ncorrectly building the SQL according to the database specific dialect. Drivers can also\nbe specified by passing a class name. In that case, include all the connection details\ndirectly in the options array:\n\n```php\nuse Cake\\Database\\Connection;\n\n$connection = new Connection([\n\t'driver' =\u003e Cake\\Database\\Driver\\Sqlite::class,\n\t'database' =\u003e '/path/to/file.db'\n]);\n```\n\n### Connection options\n\nThis is a list of possible options that can be passed when creating a connection:\n\n* `persistent`: Creates a persistent connection\n* `host`: The server host\n* `database`: The database name\n* `username`: Login credential\n* `password`: Connection secret\n* `encoding`: The connection encoding (or charset)\n* `timezone`: The connection timezone or time offset\n\n## Using connections\n\nAfter creating a connection, you can immediately interact with the database. You can choose\neither to use the shorthand methods `execute()`, `insert()`, `update()`, `delete()` or use the\n`newQuery()` for using a query builder.\n\nThe easiest way of executing queries is by using the `execute()` method, it will return a\n`Cake\\Database\\StatementInterface` that you can use to get the data back:\n\n```php\n$statement = $connection-\u003eexecute('SELECT * FROM articles');\n\nwhile($row = $statement-\u003efetch('assoc')) {\n\techo $row['title'] . PHP_EOL;\n}\n```\nBinding values to parametrized arguments is also possible with the execute function:\n\n```php\n$statement = $connection-\u003eexecute('SELECT * FROM articles WHERE id = :id', ['id' =\u003e 1], ['id' =\u003e 'integer']);\n$results = $statement-\u003efetch('assoc');\n```\n\nThe third parameter is the types the passed values should be converted to when passed to the database. If\nno types are passed, all arguments will be interpreted as a string.\n\nAlternatively you can construct a statement manually and then fetch rows from it:\n\n```php\n$statement = $connection-\u003eprepare('SELECT * from articles WHERE id != :id');\n$statement-\u003ebind(['id' =\u003e 1], ['id' =\u003e 'integer']);\n$results = $statement-\u003efetchAll('assoc');\n```\n\nThe default types that are understood by this library and can be passed to the `bind()` function or to `execute()`\nare:\n\n* biginteger\n* binary\n* date\n* float\n* decimal\n* integer\n* time\n* datetime\n* timestamp\n* uuid\n\nMore types can be added dynamically in a bit.\n\nStatements can be reused by binding new values to the parameters in the query:\n\n```php\n$statement = $connection-\u003eprepare('SELECT * from articles WHERE id = :id');\n$statement-\u003ebind(['id' =\u003e 1], ['id' =\u003e 'integer']);\n$results = $statement-\u003efetchAll('assoc');\n\n$statement-\u003ebind(['id' =\u003e 1], ['id' =\u003e 'integer']);\n$results = $statement-\u003efetchAll('assoc');\n```\n\n### Updating Rows\n\nUpdating can be done using the `update()` function in the connection object. In the following\nexample we will update the title of the article with id = 1:\n\n```php\n$connection-\u003eupdate('articles', ['title' =\u003e 'New title'], ['id' =\u003e 1]);\n```\n\nThe concept of data types is central to this library, so you can use the last parameter of the function\nto specify what types should be used:\n\n```php\n$connection-\u003eupdate(\n\t'articles',\n\t['title' =\u003e 'New title'],\n\t['created \u003e=' =\u003e new DateTime('-3 day'), 'created \u003c' =\u003e new DateTime('now')],\n\t['created' =\u003e 'datetime']\n);\n```\n\nThe example above will execute the following SQL:\n\n```sql\nUPDATE articles SET title = 'New Title' WHERE created \u003e= '2014-10-10 00:00:00' AND created \u003c '2014-10-13 00:00:00';\n```\n\nMore on creating complex where conditions or more complex update queries later.\n\n### Deleting Rows\n\nSimilarly, the `delete()` method is used to delete rows from the database:\n\n```php\n$connection-\u003edelete('articles', ['created \u003c' =\u003e DateTime('now')], ['created' =\u003e 'date']);\n```\n\nWill generate the following SQL\n\n```sql\nDELETE FROM articles where created \u003c '2014-10-10'\n```\n\n### Inserting Rows\n\nRows can be inserted using the `insert()` method:\n\n```php\n$connection-\u003einsert(\n\t'articles',\n\t['title' =\u003e 'My Title', 'body' =\u003e 'Some paragraph', 'created' =\u003e new DateTime()],\n\t['created' =\u003e 'datetime']\n);\n```\n\nMore complex updates, deletes and insert queries can be generated using the `Query` class.\n\n## Query Builder\n\nOne of the goals of this library is to allow the generation of both simple and complex queries with\nease. The query builder can be accessed by getting a new instance of a query:\n\n```php\n$query = $connection-\u003enewQuery();\n```\n\n### Selecting Fields\n\nAdding fields to the `SELECT` clause:\n\n```php\n$query-\u003eselect(['id', 'title', 'body']);\n\n// Results in SELECT id AS pk, title AS aliased_title, body ...\n$query-\u003eselect(['pk' =\u003e 'id', 'aliased_title' =\u003e 'title', 'body']);\n\n// Use a closure\n$query-\u003eselect(function ($query) {\n\treturn ['id', 'title', 'body'];\n});\n```\n\n### Where Conditions\n\nGenerating conditions:\n\n```php\n// WHERE id = 1\n$query-\u003ewhere(['id' =\u003e 1]);\n\n// WHERE id \u003e 2\n$query-\u003ewhere(['id \u003e' =\u003e 1]);\n```\n\nAs you can see you can use any operator by placing it with a space after the field name.\nAdding multiple conditions is easy as well:\n\n```php\n$query-\u003ewhere(['id \u003e' =\u003e 1])-\u003eandWhere(['title' =\u003e 'My Title']);\n\n// Equivalent to\n$query-\u003ewhere(['id \u003e' =\u003e 1, 'title' =\u003e 'My title']);\n```\n\nIt is possible to generate `OR` conditions as well\n\n```php\n$query-\u003ewhere(['OR' =\u003e ['id \u003e' =\u003e 1, 'title' =\u003e 'My title']]);\n```\n\nFor even more complex conditions you can use closures and expression objects:\n\n```php\n$query-\u003ewhere(function ($exp) {\n        return $exp\n            -\u003eeq('author_id', 2)\n            -\u003eeq('published', true)\n            -\u003enotEq('spam', true)\n            -\u003egt('view_count', 10);\n    });\n```\n\nWhich results in:\n\n```sql\nSELECT * FROM articles\nWHERE\n\tauthor_id = 2\n\tAND published = 1\n\tAND spam != 1\n\tAND view_count \u003e 10\n```\n\nCombining expressions is also possible:\n\n```php\n$query-\u003ewhere(function ($exp) {\n        $orConditions = $exp-\u003eor(['author_id' =\u003e 2])\n            -\u003eeq('author_id', 5);\n        return $exp\n            -\u003enot($orConditions)\n            -\u003elte('view_count', 10);\n    });\n```\n\nThat generates:\n\n```sql\nSELECT *\nFROM articles\nWHERE\n\tNOT (author_id = 2 OR author_id = 5)\n\tAND view_count \u003c= 10\n```\n\nWhen using the expression objects you can use the following methods to create conditions:\n\n* `eq()` Creates an equality condition.\n* `notEq()` Create an inequality condition\n* `like()` Create a condition using the LIKE operator.\n* `notLike()` Create a negated LIKE condition.\n* `in()` Create a condition using IN.\n* `notIn()` Create a negated condition using IN.\n* `gt()` Create a \u003e condition.\n* `gte()` Create a \u003e= condition.\n* `lt()` Create a \u003c condition.\n* `lte()` Create a \u003c= condition.\n* `isNull()` Create an IS NULL condition.\n* `isNotNull()` Create a negated IS NULL condition.\n\n### Aggregates and SQL Functions\n\n```php\n// Results in SELECT COUNT(*) count FROM ...\n$query-\u003eselect(['count' =\u003e $query-\u003efunc()-\u003ecount('*')]);\n```\n\nA number of commonly used functions can be created with the func() method:\n\n* `sum()` Calculate a sum. The arguments will be treated as literal values.\n* `avg()` Calculate an average. The arguments will be treated as literal values.\n* `min()` Calculate the min of a column. The arguments will be treated as literal values.\n* `max()` Calculate the max of a column. The arguments will be treated as literal values.\n* `count()` Calculate the count. The arguments will be treated as literal values.\n* `concat()` Concatenate two values together. The arguments are treated as bound parameters unless marked as literal.\n* `coalesce()` Coalesce values. The arguments are treated as bound parameters unless marked as literal.\n* `dateDiff()` Get the difference between two dates/times. The arguments are treated as bound parameters unless marked as literal.\n* `now()` Take either 'time' or 'date' as an argument allowing you to get either the current time, or current date.\n\nWhen providing arguments for SQL functions, there are two kinds of parameters you can use, literal arguments and bound parameters. Literal\nparameters allow you to reference columns or other SQL literals. Bound parameters can be used to safely add user data to SQL functions.\nFor example:\n\n```php\n$concat = $query-\u003efunc()-\u003econcat([\n    'title' =\u003e 'literal',\n    ' NEW'\n]);\n$query-\u003eselect(['title' =\u003e $concat]);\n```\n\nThe above generates:\n\n```sql\nSELECT CONCAT(title, :c0) ...;\n```\n\n### Other SQL Clauses\n\nRead of all other SQL clauses that the builder is capable of generating in the [official API docs](https://api.cakephp.org/4.x/class-Cake.Database.Query.html)\n\n### Getting Results out of a Query\n\nOnce you’ve made your query, you’ll want to retrieve rows from it. There are a few ways of doing this:\n\n```php\n// Iterate the query\nforeach ($query as $row) {\n    // Do stuff.\n}\n\n// Get the statement and fetch all results\n$results = $query-\u003eexecute()-\u003efetchAll('assoc');\n```\n\n## Official API\n\nYou can read the official [official API docs](https://api.cakephp.org/4.x/namespace-Cake.Database.html) to learn more of what this library\nhas to offer.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcakephp%2Fdatabase","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcakephp%2Fdatabase","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcakephp%2Fdatabase/lists"}