{"id":14973971,"url":"https://github.com/skipperbent/pecee-pixie","last_synced_at":"2025-06-15T19:34:19.667Z","repository":{"id":49575818,"uuid":"81995505","full_name":"skipperbent/pecee-pixie","owner":"skipperbent","description":"Lightweight, easy-to-use querybuilder for PHP inspired by Laravel Eloquent - but with less overhead.","archived":false,"fork":false,"pushed_at":"2024-03-06T13:52:42.000Z","size":724,"stargazers_count":40,"open_issues_count":8,"forks_count":13,"subscribers_count":4,"default_branch":"v4-release","last_synced_at":"2025-05-07T13:33:05.153Z","etag":null,"topics":["database","eloquent","models","mysql","pecee","pgsql","php","query","query-builder","querybuilder","sqlite"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/skipperbent.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","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}},"created_at":"2017-02-14T22:28:46.000Z","updated_at":"2025-04-20T19:07:48.000Z","dependencies_parsed_at":"2024-06-18T18:33:07.862Z","dependency_job_id":"a442e08d-7b58-46f2-a3e3-2114d0c8c749","html_url":"https://github.com/skipperbent/pecee-pixie","commit_stats":{"total_commits":359,"total_committers":25,"mean_commits":14.36,"dds":0.6211699164345403,"last_synced_commit":"1bbfcdc270e4691b55fe0ac4ef224e8cf3dc1ac7"},"previous_names":[],"tags_count":62,"template":false,"template_full_name":null,"purl":"pkg:github/skipperbent/pecee-pixie","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skipperbent%2Fpecee-pixie","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skipperbent%2Fpecee-pixie/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skipperbent%2Fpecee-pixie/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skipperbent%2Fpecee-pixie/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/skipperbent","download_url":"https://codeload.github.com/skipperbent/pecee-pixie/tar.gz/refs/heads/v4-release","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skipperbent%2Fpecee-pixie/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259560876,"owners_count":22876700,"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":["database","eloquent","models","mysql","pecee","pgsql","php","query","query-builder","querybuilder","sqlite"],"created_at":"2024-09-24T13:49:45.767Z","updated_at":"2025-06-15T19:34:19.621Z","avatar_url":"https://github.com/skipperbent.png","language":"PHP","readme":"# pecee/pixie: Advanced lightweight querybuilder\n\nA lightweight, expressive, framework agnostic query builder for PHP it can also be referred as a Database Abstraction Layer.\nPixie supports MySQL, MS-SQL, SQLite and PostgreSQL will handle all your query sanitization, table alias, unions among many other things, with a unified API.\n\nThe syntax is similar to Laravel's query builder \"Eloquent\", but with less overhead.\n\nThis library is stable, maintained and are used by sites around the world (check the [credits](#credits)).\n\n**Requirements:**\n- PHP version 7.1 or higher is required for pecee-pixie version 4.x and above (versions prior to 4.x are available [here](https://github.com/skipperbent/pixie)).\n- PDO extension enabled.\n\n**Features:**\n\n- Improved sub-queries.\n- Custom prefix/aliases for tables (prefix.`table`).\n- Support for not defining table and/or removing defined table.\n- Better handling of `Raw` objects in `where` statements.\n- Union queries.\n- Better connection handling.\n- Performance optimisations.\n- Tons of bug fixes.\n- Much more...\n\n**Including all the original features like:**\n\n- Query events\n- Nested criteria\n- Sub queries\n- Nested queries\n- Multiple database connections.\n\nMost importantly this project is used on many live-sites and maintained.\n\n### Examples\n```php\n// Make sure you have Composer's autoload file included\nrequire 'vendor/autoload.php';\n\n// Create a connection, once only.\n$config =\n[\n    // Name of database driver or IConnectionAdapter class\n    'driver'    =\u003e 'mysql',\n    'host'      =\u003e 'localhost',\n    'database'  =\u003e 'your-database',\n    'username'  =\u003e 'root',\n    'password'  =\u003e 'your-password',\n\n    // Optional\n    'charset'   =\u003e 'utf8',\n\n    // Optional\n    'collation' =\u003e 'utf8_unicode_ci',\n\n    // Table prefix, optional\n    'prefix'    =\u003e 'cb_',\n\n    // PDO constructor options, optional\n    'options'   =\u003e [\n        PDO::ATTR_TIMEOUT =\u003e 5,\n        PDO::ATTR_EMULATE_PREPARES =\u003e false,\n    ],\n];\n\n$queryBuilder = (new \\Pecee\\Pixie\\Connection('mysql', $config))-\u003egetQueryBuilder();\n```\n\n**Simple query:**\n\nGet user with the id of `3`. Returns `null` when no match.\n\n```php\n$user = $queryBuilder\n            -\u003etable('users')\n            -\u003efind(3);\n```\n\n**Full queries:**\n\nGet all users with blue or red hair.\n\n```php\n$users = $queryBuilder\n            -\u003etable('users')\n            -\u003ewhere('hair_color', '=', 'blue')\n            -\u003eorWhere('hair_color', '=', 'red')\n            -\u003eget();\n```\n\n___\n\n## Table of Contents\n\n - [Installation](#installation)\n - [Feedback and development](#feedback-and-development)\n    - [Issues guidelines](#issues-guidelines)\n    - [Contribution and development guidelines](#contribution-and-development-guidelines)\n - [Connecting to the database](#connecting-to-the-database)\n    - [SQLite and PostgreSQL config example](#sqlite-and-postgresql-config-example)\n - [**Select**](#select)\n    - [Table alias](#table-alias)\n    - [Get easily](#get-easily)\n    - [Multiple selects](#multiple-selects)\n    - [Select distinct](#select-distinct)\n    - [Select from query](#select-from-query)\n    - [Select single field](#select-single-field)\n    - [Select multiple fields](#select-multiple-fields)\n    - [Get all](#get-all)\n    - [Get first row](#get-first-row)\n    - [**Aggregate methods**](#aggregate-methods)\n        - [Getting the row count](#getting-the-row-count)\n        - [Getting the sum](#getting-the-sum)\n        - [Getting the average](#getting-the-average)\n        - [Getting the minimum](#getting-the-minimum)\n        - [Getting the maximum](#getting-the-maximum)\n    - [Selects with sub-queries](#select-with-sub-queries)\n - [**Where**](#where)\n    - [Where in](#where-in)\n    - [Where between](#where-between)\n    - [Where null](#where-null)\n    - [Grouped where](#grouped-where)\n - [Group- and order by](#group--and-order-by)\n - [Having](#having)\n - [Limit and offset](#limit-and-offset)\n - [Join](#join)\n    - [Join USING syntax](#join-using-syntax)\n    - [Multiple join criteria](#multiple-join-criteria)\n - [Unions](#unions)\n - [Raw query](#raw-query)\n    - [Raw expressions](#raw-expressions)\n - [**Insert**](#insert)\n    - [Batch insert](#batch-insert)\n    - [Insert with ON DUPLICATE KEY statement](#insert-with-on-duplicate-key-statement)\n - [**Update**](#update)\n - [**Delete**](#delete)\n - [Transactions](#transactions)\n - [Get raw query](#get-built-query)\n    - [Get QueryObject from last executed query](#get-queryobject-from-last-executed-query)\n - [Sub-queries and nested queries](#sub-queries-and-nested-queries)\n - [Getting the PDO instance](#getting-the-pdo-instance)\n - [Fetch results as objects of specified class](#fetch-results-as-objects-of-specified-class)\n - [Advanced](#advanced)\n     - [Enable query-overwriting](#enable-query-overwriting)\n - [Query events](#query-events)\n    - [Available event](#available-event)\n    - [Registering event](#registering-event)\n    - [Removing event](#removing-event)\n    - [Use cases](#use-cases)\n    - [Notes](#notes)\n - [Exceptions](#exceptions)\n    - [Getting sql-query from exceptions](#getting-sql-query-from-exceptions)\n - [Credits](#credits)\n\n___\n\n## Installation\n\nPixie uses [Composer](http://getcomposer.org/doc/00-intro.md#installation-nix) to make things easy.\n\nLearn to use composer and add this to require section (in your composer.json):\n\n```\ncomposer install pecee/pixie\n```\n\n## Feedback and development\n\nIf you are missing a feature, experience problems or have ideas or feedback that you want us to hear, please feel free to create an issue.\n\n#### Issues guidelines\n\n- Please be as detailed as possible in the description when creating a new issue. This will help others to more easily understand- and solve your issue. For example: if you are experiencing issues, you should provide the necessary steps to reproduce the error within your description.\n\n- We love to hear out any ideas or feedback to the library.\n\n[Create a new issue here](https://github.com/skipperbent/pecee-pixie/issues)\n\n#### Contribution and development guidelines\n\n- Please try to follow the PSR-2 codestyle guidelines.\n\n- Please create your pull requests to the development base that matches the version number you want to change.\nFor example when pushing changes to version 3, the pull request should use the `v3-development` base/branch.\n\n- Create detailed descriptions for your commits, as these will be used in the changelog for new releases.\n\n- When changing existing functionality, please ensure that the unit-tests working.\n\n- When adding new stuff, please remember to add new unit-tests for the functionality.\n\n## Connecting to the database\nPixie supports three database drivers, MySQL, SQLite and PostgreSQL.\nYou can specify the driver during connection and the associated configuration when creating a new connection. You can also create multiple connections, but you can use alias for only one connection at a time.;\n\n```php\n// Make sure you have Composer's autoload file included\nrequire 'vendor/autoload.php';\n\n$config = [\n    'driver'    =\u003e 'mysql',\n    'host'      =\u003e 'localhost',\n    'database'  =\u003e 'your-database',\n    'username'  =\u003e 'root',\n    'password'  =\u003e 'your-password',\n    'charset'   =\u003e 'utf8',\n    'collation' =\u003e 'utf8_unicode_ci',\n    'prefix'    =\u003e '',\n];\n\n// Creates new connection\n$connection = new \\Pecee\\Pixie\\Connection('mysql', $config);\n\n// Get the query-builder object which will initialize the database connection\n$queryBuilder = $connection-\u003egetQueryBuilder();\n\n// Run query\n$person = $queryBuilder\n            -\u003etable('persons')\n            -\u003ewhere('name', '=', 'Bobby')\n            -\u003efirst();\n```\n\n`$connection` here is optional, if not given it will always associate itself to the first connection, but it can be useful when you have multiple database connections.\n\n**NOTE:**\nCalling the `getQueryBuilder` method will automatically make a connection to the database, if none has already established.\nIf you want to access the `Pdo` instance directly from the `Connection` class, make sure to call `$connection-\u003econnect();` to establish a connection to the database.\n\n### SQLite and PostgreSQL config example\n\nThe example below is for use with sqlite-databases.\n\n```php\n$queryBuilder = new \\Pecee\\Pixie\\Connection('sqlite', [\n    'driver'   =\u003e 'sqlite',\n    'database' =\u003e 'your-file.sqlite',\n    'prefix'   =\u003e 'cb_',\n]);\n```\n\nThe example below is for pgsql databases.\n\n```php\n$queryBuilder = new \\Pecee\\Pixie\\Connection('pgsql', [\n    'driver'   =\u003e 'pgsql',\n    'host'     =\u003e 'localhost',\n    'database' =\u003e 'your-database',\n    'username' =\u003e 'postgres',\n    'password' =\u003e 'your-password',\n    'charset'  =\u003e 'utf8',\n    'prefix'   =\u003e 'cb_',\n    'schema'   =\u003e 'public',\n]);\n```\n\n## Select\n\nIt is recommend to use `table()` method before every query, except raw `query()`.\nTo select from multiple tables just pass an array.\n\nHowever this is not required.\n\n```php\n$queryBuilder-\u003etable(array('mytable1', 'mytable2'));\n```\n\n#### Table alias\n\nYou can easily set the table alias by using\n\n```php\n$queryBuilder\n    -\u003etable(['table1' =\u003e 'foo1'])\n    -\u003ejoin('table2', 'table2.person_id', '=', 'foo1.id');\n```\n\nYou can change the alias anytime by using:\n\n```php\n$queryBuilder-\u003ealias('foo1', 'table1');\n\n// Simplified way...\n\n$queryBuilder-\u003etable('table1')-\u003ealias('foo1');\n```\n\nOutput:\n\n```sql\nSELECT *\nFROM `table1` AS `foo1`\nINNER JOIN `cb_table2` ON `cb_table2`.`person_id` = `cb_foo1`.`id`\n```\n\n**NOTE:**\nYou can always remove a table from a query by calling the `table` method with no arguments like this `$queryBuilder-\u003etable()`.\n\n#### Get easily\n\nThe query below returns the (first) row where id = 3, null if no rows.\n\n```php\n$row = $queryBuilder\n            -\u003etable('my_table')\n            -\u003efind(3);\n```\n\nAccess your row like, `echo $row-\u003ename`. If your field name is not `id` then pass the field name as second parameter `$queryBuilder-\u003etable('my_table')-\u003efind(3, 'person_id');`.\n\nThe query below returns the all rows where name = 'Sana', null if no rows.\n\n```php\n$result = $queryBuilder\n            -\u003etable('my_table')\n            -\u003efindAll('name', 'Sana');\n```\n\n#### Multiple selects\n\n```php\n$queryBuilder\n    -\u003eselect(\n        [\n            'mytable.myfield1',\n            'mytable.myfield2',\n            'another_table.myfield3'\n        ]\n    );\n```\n\nUsing select method multiple times `select('a')-\u003eselect('b')` will also select `a` and `b`. Can be useful if you want to do conditional selects (within a PHP `if`).\n\n#### Select distinct\n\n```php\n$queryBuilder-\u003eselectDistinct(array('mytable.myfield1', 'mytable.myfield2'));\n```\n\n#### Select from query\n\nYou can easily select items from another query by using\n\n```php\n$subQuery = $queryBuilder-\u003etable('person');\n$builder = $queryBuilder-\u003etable($queryBuilder-\u003esubQuery($subQuery))-\u003ewhere('id', '=', 2);\n```\n\nWill produce the following output:\n\n```sql\nSELECT * FROM (SELECT * FROM `person`) WHERE `id` = 2\n```\n\n#### Select single field\n\n```php\n$queryBuilder-\u003etable('my_table')-\u003eselect('*');\n```\n\n#### Select multiple fields\n\n```php\n$queryBuilder-\u003etable('my_table')-\u003eselect(array('field1', 'field2'));\n```\n\n#### Get all\n\nReturns an array.\n\n```php\n$results = $queryBuilder\n                -\u003etable('my_table')\n                -\u003ewhere('name', '=', 'Sana')\n                -\u003eget();\n```\n\nYou can loop through it like:\n\n```php\nforeach ($results as $row) {\n    echo $row-\u003ename;\n}\n```\n\n#### Get first row\n\n```php\n$row = $queryBuilder\n            -\u003etable('my_table')\n            -\u003ewhere('name', '=', 'Sana')\n            -\u003efirst();\n```\nReturns the first row, or null if there is no record. Using this method you can also make sure if a record exists. Access these like `echo $row-\u003ename`.\n\n#### Aggregate methods\n\n##### Getting the row count\n\nThis will return the count for the entire number of rows in the result.\n\nThe default behavior will count `*` (all) fields. You can specify a custom field by changing the `field` parameter.\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhere('name', '=', 'Sana')\n    -\u003ecount();\n```\n\n##### Getting the sum\n\nThis will return the sum for a field in the entire number of rows in the result.\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhere('name', '=', 'Sana')\n    -\u003esum('views');\n```\n\n##### Getting the average\n\nThis will return the average for a field in the entire number of rows in the result.\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhere('name', '=', 'Sana')\n    -\u003eaverage('views');\n```\n\n##### Getting the minimum\n\nThis will return the minimum for a field in the entire number of rows in the result.\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhere('name', '=', 'Sana')\n    -\u003emin('views');\n```\n\n##### Getting the maximum\n\nThis will return the average for a field in the entire number of rows in the result.\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhere('name', '=', 'Sana')\n    -\u003emax('views');\n```\n\n#### Select with sub-queries\n\n```php\n// Creates the first sub-query\n\n$subQuery1 =\n    $queryBuilder\n        -\u003etable('mail')\n        -\u003eselect(\n            $queryBuilder-\u003eraw('COUNT(*)')\n        );\n\n// Create the second sub-query\n\n$subQuery2 =\n    $queryBuilder\n        -\u003etable('event_message')\n        -\u003eselect(\n            $queryBuilder-\u003eraw('COUNT(*)')\n        );\n\n// Executes the query which uses the subqueries as fields\n$count =\n    $queryBuilder\n        -\u003eselect(\n            $queryBuilder-\u003esubQuery($subQuery1, 'row1'),\n            $queryBuilder-\u003esubQuery($subQuery2, 'row2')\n        )\n        -\u003efirst();\n```\n\nThe example above will output a SQL-query like this:\n\n```sql\nSELECT\n  (SELECT COUNT(*)\n   FROM `cb_mail`) AS row1,\n\n  (SELECT COUNT(*)\n   FROM `cb_event_message`) AS row2\nLIMIT 1\n```\n\nYou can also easily create a subjquery within the `where` statement:\n\n```php\n$queryBuilder-\u003ewhere($queryBuilder-\u003esubQuery($subQuery), '!=', 'value');\n```\n\n### Where\n\nBasic syntax is `(fieldname, operator, value)`, if you give two parameters then `=` operator is assumed. So `where('name', 'usman')` and `where('name', '=', 'usman')` is the same.\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhere('name', '=', 'usman')\n    -\u003ewhereNot('age', '\u003e', 25)\n    -\u003eorWhere('type', '=', 'admin')\n    -\u003eorWhereNot('description', 'LIKE', '%query%');\n```\n\n\n#### Where in\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhereIn('name', array('usman', 'sana'))\n    -\u003eorWhereIn('name', array('heera', 'dalim'));\n\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhereNotIn('name', array('heera', 'dalim'))\n    -\u003eorWhereNotIn('name', array('usman', 'sana'));\n```\n\n#### Where between\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhereBetween('id', 10, 100)\n    -\u003eorWhereBetween('status', 5, 8);\n```\n\n#### Where null\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhereNull('modified')\n    -\u003eorWhereNull('field2')\n    -\u003ewhereNotNull('field3')\n    -\u003eorWhereNotNull('field4');\n```\n\n#### Grouped where\n\nSometimes queries get complex, where you need grouped criteria, for example `WHERE age = 10 and (name like '%usman%' or description LIKE '%usman%')`.\n\nPixie allows you to do so, you can nest as many closures as you need, like below.\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhere('my_table.age', 10)\n    -\u003ewhere(function(QueryBuilderHandler $qb) {\n        $qb-\u003ewhere('name', 'LIKE', '%pecee%');\n\n        // You can provide a closure on these wheres too, to nest further.\n        $qb-\u003eorWhere('description', 'LIKE', '%usman%');\n    });\n```\n\n### Group- and order by\n\n```php\n$query = $queryBuilder\n            -\u003etable('my_table')\n            -\u003egroupBy('age')\n            -\u003eorderBy('created_at', 'ASC');\n```\n\n#### Multiple group by\n\n```php\n$queryBuilder\n    -\u003egroupBy(array('mytable.myfield1', 'mytable.myfield2', 'another_table.myfield3'));\n    -\u003eorderBy(array('mytable.myfield1', 'mytable.myfield2', 'another_table.myfield3'));\n```\n\nUsing `groupBy()` or `orderBy()` methods multiple times `groupBy('a')-\u003egroupBy('b')` will also group by first `a` and than `b`. Can be useful if you want to do conditional grouping (within a PHP `if`). Same applies to `orderBy()`.\n\n### Having\n\n```php\n$queryBuilder\n    -\u003ehaving('total_count', '\u003e', 2)\n    -\u003eorHaving('type', '=', 'admin');\n```\n\n### Limit and offset\n\n```php\n$queryBuilder\n    -\u003elimit(30);\n    -\u003eoffset(10);\n```\n\n### Join\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ejoin('another_table', 'another_table.person_id', '=', 'my_table.id')\n```\n\nAvailable methods,\n\n - join() or innerJoin\n - leftJoin()\n - rightJoin()\n\nIf you need `FULL OUTER` join or any other join, just pass it as 5th parameter of `join` method.\n\n```php\n$queryBuilder\n    -\u003ejoin('another_table', 'another_table.person_id', '=', 'my_table.id', 'FULL OUTER')\n```\n\n#### Join USING syntax\n\nThe `JOIN USING` syntax allows you to easily map two identical identifiers to one, which can be helpful on large queries.\n\nExample:\n\n```php\n$queryBuilder\n    -\u003etable('user')\n    -\u003ejoin('user_data', 'user_data.user_id', '=', 'user.user_id');\n```\n\nCan be simplified to:\n\n```php\n$queryBuilder\n    -\u003etable('user')\n    -\u003ejoinUsing('user_data', 'user_id');\n```\n\n#### Multiple join criteria\n\nIf you need more than one criterion to join a table then pass a closure as second parameter.\n\n```php\n$queryBuilder\n    -\u003ejoin('another_table', function($table)\n    {\n        $table\n            -\u003eon('another_table.person_id', '=', 'my_table.id')\n            -\u003eon('another_table.person_id2', '=', 'my_table.id2')\n            -\u003eorOn('another_table.age', '\u003e', $queryBuilder-\u003eraw(1));\n    })\n```\n\n### Unions\n\nYou can easily create unions by calling the `union` method on the `QueryBuilderHandler`.\n\nExample:\n\n```php\n$firstQuery =\n    $queryBuilder\n    -\u003etable('people')\n    -\u003ewhereNull('email');\n\n$secondQuery =\n    $queryBuilder\n    -\u003etable('people')\n    -\u003ewhere('hair_color', '=', 'green')\n    -\u003eunion($firstQuery);\n\n$thirdQuery =\n    $queryBuilder\n    -\u003etable('people')\n    -\u003ewhere('gender', '=', 'male')\n    -\u003eunion($secondQuery);\n\n$items = $thirdQuery-\u003eget();\n```\n\nThe example above will create a sql-statement similar to this:\n\n```sql\n(\n\tSELECT *\n\tFROM\n\t\t`cb_people`\n\tWHERE\n\t\t`gender` = 'male'\n)\nUNION\n(\n\tSELECT *\n\tFROM\n\t\t`cb_people`\n\tWHERE\n\t\t`email`\n\tIS NULL\n)\nUNION\n(\n\tSELECT *\n\tFROM\n\t\t`cb_people`\n\tWHERE\n\t\t`hair_color` = 'green'\n)\n```\n\n### Raw query\n\nYou can always perform raw queries, if needed.\n\n```php\n$query = $queryBuilder-\u003equery('SELECT * FROM persons WHERE age = 12');\n\n$kids = $query-\u003eget();\n```\n\nYou can also pass custom bindings\n\n```php\n$queryBuilder\n    -\u003equery('SELECT * FROM persons WHERE age = ? AND name = ?', array(10, 'usman'));\n```\n\n#### Raw expressions\n\nWhen you wrap an expression with `raw()` method, Pixie doesn't try to sanitize these.\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003eselect($queryBuilder-\u003eraw('count(cb_my_table.id) as tot'))\n    -\u003ewhere('value', '=', 'Ifrah')\n    -\u003ewhere($queryBuilder-\u003eraw('DATE(?)', 'now'))\n```\n\n\n___\n\n**NOTE:** Queries that run through `query()` method are not sanitized until you pass all values through bindings. Queries that run through `raw()` method are not sanitized either, you have to do it yourself. And of course these don't add table prefix too, but you can use the `addTablePrefix()` method.\n\n### Insert\n\n```php\n$data = [\n    'name' =\u003e 'Sana',\n    'description' =\u003e 'Blah'\n];\n\n$insertId = $queryBuilder\n                -\u003etable('my_table')\n                -\u003einsert($data);\n```\n\n`insert()` method returns the insert id.\n\n#### Batch insert\n\n```php\n$data = [\n    array(\n        'name'        =\u003e 'Sana',\n        'description' =\u003e 'Blah'\n    ),\n    array(\n        'name'        =\u003e 'Usman',\n        'description' =\u003e 'Blah'\n    ),\n];\n\n$insertIds = $queryBuilder\n                -\u003etable('my_table')\n                -\u003einsert($data);\n```\n\nIn case of batch insert, it will return an array of insert ids.\n\n#### Insert with ON DUPLICATE KEY statement\n\n```php\n$data = [\n    'name'    =\u003e 'Sana',\n    'counter' =\u003e 1\n];\n\n$dataUpdate = [\n    'name'    =\u003e 'Sana',\n    'counter' =\u003e 2\n];\n\n$insertId =\n    $queryBuilder\n        -\u003etable('my_table')\n        -\u003eonDuplicateKeyUpdate($dataUpdate)\n        -\u003einsert($data);\n```\n\n### Update\n\n```php\n$data = [\n    'name'        =\u003e 'Sana',\n    'description' =\u003e 'Blah'\n];\n\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhere('id', 5)\n    -\u003eupdate($data);\n```\n\nWill update the name field to Sana and description field to Blah where id = 5.\n\n### Delete\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003ewhere('id', '\u003e', 5)\n    -\u003edelete();\n```\n\nWill delete all the rows where id is greater than 5.\n\n### Transactions\n\nPixie has the ability to run database \"transactions\", in which all database\nchanges are not saved until committed. That way, if something goes wrong or\ndifferently then you intend, the database changes are not saved and no changes\nare made.\n\nHere's a basic transaction:\n\n```php\n$queryBuilder\n    -\u003etransaction(function (Transaction $transaction) {\n\n        $transaction\n            -\u003etable('my_table')\n            -\u003einsert(array(\n                'name' =\u003e 'Test',\n                'url' =\u003e 'example.com'\n            );\n\n        $transaction\n            -\u003etable('my_table')\n            -\u003einsert(array(\n                'name' =\u003e 'Test2',\n                'url' =\u003e 'example.com'\n            ));\n});\n```\n\nIf this were to cause any errors (such as a duplicate name or some other such\nerror), neither data set would show up in the database. If not, the changes would\nbe successfully saved.\n\nIf you wish to manually commit or rollback your changes, you can use the\n`commit()` and `rollback()` methods accordingly:\n\n```php\n$queryBuilder\n    -\u003etransaction(function (Transaction $transaction)\n        {\n            $transaction\n                -\u003etable('my_table')\n                -\u003einsert($data);\n\n            // Commit changes (data will be saved)\n            $transaction-\u003ecommit();\n\n            // Rollback changes (data would be rejected)\n            $transaction-\u003erollback();\n        }\n    );\n```\n\nTransactions will automatically be used when inserting multiple records. For example:\n\n```php\n$queryBuilder-\u003etable('people')-\u003einsert([\n    [\n        'name' =\u003e 'Simon',\n        'age' =\u003e 12,\n        'awesome' =\u003e true,\n        'nickname' =\u003e 'ponylover94',\n    ],\n    [\n        'name' =\u003e 'Peter',\n        'age' =\u003e 40,\n        'awesome' =\u003e false,\n        'nickname' =\u003e null,\n    ],\n    [\n        'name' =\u003e 'Bobby',\n        'age' =\u003e 20,\n        'awesome' =\u003e true,\n        'nickname' =\u003e 'peter',\n    ],\n]);\n```\n\n### Get raw query\n\nSometimes you may need to get the query string, it's possible.\n\n```php\n$queryHandler =\n    $queryBuilder\n        -\u003etable('my_table')\n        -\u003ewhere('id', '=', 3)\n        -\u003egetQuery();\n```\n\n`getQuery()` will return a `QueryBuilderHandler` object.\n\nYou can use this to get the SQL, bindings or raw SQL.\n\n```php\n$queryHandler-\u003egetSql();\n```\n\nCalling `getSql()` will return the SQL-query without any processing.\n\n```sql\nSELECT * FROM my_table where `id` = ?\n```\n\nYou can easily get any bindings on the query by calling the `getBindings()`method.\n\n**Example:**\n\n```php\n$queryHandler-\u003egetBindings();\n```\n\nYou can also get the raw SQL-query directly by calling the `getRawSql()` method.\n\n**Example:**\n\n```php\n$queryHandler-\u003egetRawSql();\n```\n\nCalling the `getRawSql()` method will return a query including bindings like this.\n\n```sql\nSELECT * FROM my_table where `id` = 3\n```\n\n#### Get QueryObject from last executed query\n\nYou can also retrieve the query-object from the last executed query.\n\n**Example:**\n\n```php\n$queryString = $queryBuilder-\u003egetLastQuery()-\u003egetRawSql();\n```\n\n### Sub-queries and nested queries\n\nRarely but you may need to do sub queries or nested queries. Pixie is powerful enough to do this for you. You can create different query objects and use the `$queryBuilder-\u003esubQuery()` method.\n\n```php\n$subQuery =\n    $queryBuilder\n        -\u003etable('person_details')\n        -\u003eselect('details')\n        -\u003ewhere('person_id', '=', 3);\n\n\n$query =\n    $queryBuilder\n        -\u003etable('my_table')\n        -\u003eselect('my_table.*')\n        -\u003eselect(\n            $queryBuilder-\u003esubQuery($subQuery, 'table_alias1')\n        );\n\n$nestedQuery =\n    $queryBuilder\n        -\u003etable(\n            $queryBuilder-\u003esubQuery($query, 'table_alias2')\n        )\n        -\u003eselect('*');\n\n// Execute query\n$result = $nestedQuery-\u003eget();\n```\n\nThis will produce a query like this:\n\n```sql\nSELECT *\nFROM\n  (SELECT `cb_my_table`.*,\n\n     (SELECT `details`\n      FROM `cb_person_details`\n      WHERE `person_id` = 3) AS table_alias1\n   FROM `cb_my_table`) AS table_alias2\n```\n\n**NOTE:**\n\nPixie doesn't use bindings for sub queries and nested queries. It quotes values with PDO's `quote()` method.\n\n### Getting the PDO instance\n\nIf you need the `\\PDO` instance, you can easily get it by calling:\n\n```php\n$queryBuilder-\u003epdo();\n```\n\nIf you want to get the `Connection` object you can do so like this:\n\n```php\n$connection = $queryBuilder-\u003egetConnection();\n```\n\n### Fetch results as objects of specified class\n\nSimply call `asObject` query's method.\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003easObject('SomeClass', array('ctor', 'args'))\n    -\u003efirst();\n```\n\nFurthermore, you may fine-tune fetching mode by calling `setFetchMode` method.\n\n```php\n$queryBuilder\n    -\u003etable('my_table')\n    -\u003esetFetchMode(PDO::FETCH_COLUMN|PDO::FETCH_UNIQUE)\n    -\u003eget();\n```\n\n### Advanced\n\n#### Enable query-overwriting\n\nIf enabled calling from, select etc. will overwrite any existing values from previous calls in query.\n\nYou can enable or disable query-overwriting by calling the `setOverwriteEnabled` method on the `QueryBuilderHandler` object.\n\nThe feature is disabled as default.\n\n**Example:**\n\n```php\n$queryBuilder\n    -\u003esetOverwriteEnabled(true);\n```\n\nIf you want this feature to be enabled on all `QueryBuilderHandler` object as default, you can add the following setting to the connection configuration:\n\n```php\n$adapterConfig = [\n    'query_overwriting' =\u003e false,\n];\n```\n\n### Query events\n\nPixie comes with powerful query events to supercharge your application. These events are like database triggers, you can perform some actions when an event occurs, for example you can hook `after-delete` event of a table and delete related data from another table.\n\n#### Available events\n\n| Event constant                        | Event value/name  | Description                                           |\n| :------------------------------------ | :-------------    | :------------                                         |\n| `EventHandler::EVENT_BEFORE_ALL`      | `before-*`        | Event-type that fires before each query.              |\n| `EventHandler::EVENT_AFTER_ALL`       | `after-*`         | Event-type that fires after each query.               |\n| `EventHandler::EVENT_BEFORE_QUERY`    | `before-query`    | Event-type that fires before a raw query is executed. |\n| `EventHandler::EVENT_AFTER_QUERY`     | `after-query`     | Event-type that fires after a raw query is executed   |\n| `EventHandler::EVENT_BEFORE_SELECT`   | `before-select`   | Event-type that fires before select query.            |\n| `EventHandler::EVENT_AFTER_SELECT`    | `after-select`    | Event-type that fires after insert query.             |\n| `EventHandler::EVENT_BEFORE_INSERT`   | `before-insert`   | Event-type that fires before insert query             |\n| `EventHandler::EVENT_AFTER_INSERT`    | `after-insert`    | Event-type that fires after insert query.             |\n| `EventHandler::EVENT_BEFORE_UPDATE`   | `before-update`   | Event-type that fires before update query.            |\n| `EventHandler::EVENT_AFTER_UPDATE`    | `after-update`    | Event-type that fires after update query.             |\n| `EventHandler::EVENT_BEFORE_DELETE`   | `before-delete`   | Event-type that fires before delete query.            |\n| `EventHandler::EVENT_AFTER_DELETE`    | `after-delete`    | Event-type that fires after delete query.             |\n\n#### Registering event\n\nYou can easily register a new event either by using the `registerEvent` method on either the `QueryBuilderHandler`, `Connection` or `EventHandler` class.\n\nThe event needs a custom callback function with a `EventArguments` object as parameters.\n\n**Examples:**\n\n```php\n$queryBuilder-\u003eregisterEvent(EventHandler::EVENT_BEFORE_SELECT, function(EventArguments $arguments)\n{\n    $arguments\n        -\u003egetQueryBuilder()\n        -\u003ewhere('status', '!=', 'banned');\n}, 'users');\n```\nNow every time a select query occurs on `users` table, it will add this where criteria, so banned users don't get access.\n\nThe syntax is `registerEvent('event type', action in a closure, 'table name')`.\n\nIf you want the event to be performed when **any table is being queried**, provide `':any'` as table name.\n\n**Other examples:**\n\nAfter inserting data into `my_table`, details will be inserted into another table\n\n```php\n$queryBuilder-\u003eregisterEvent(EventHandler::EVENT_AFTER_INSERT, function(EventArguments $arguments)\n{\n    $arguments\n        -\u003egetQueryBuilder()\n        -\u003etable('person_details')-\u003einsert(array(\n        'person_id' =\u003e $insertId,\n        'details' =\u003e 'Meh',\n        'age' =\u003e 5\n    ));\n}, 'my_table');\n```\n\nWhenever data is inserted into `person_details` table, set the timestamp field `created_at`, so we don't have to specify it everywhere:\n\n```php\n$queryBuilder-\u003eregisterEvent(EventHandler::EVENT_AFTER_INSERT, function(EventArguments $arguments)\n{\n    $arguments\n        -\u003egetQueryBuilder()\n        -\u003etable('person_details')\n        -\u003ewhere('id', $insertId)\n        -\u003eupdate([\n            'created_at' =\u003e date('Y-m-d H:i:s')\n        ]);\n}, 'person_details');\n```\n\nAfter deleting from `my_table` delete the relations:\n\n```php\n$queryBuilder-\u003eregisterEvent(EventHandler::EVENT_AFTER_DELETE, function(EventArguments $arguments)\n{\n    $bindings = $arguments-\u003egetQuery()-\u003egetBindings();\n\n    $arguments\n        -\u003egetQueryBuilder()\n        -\u003etable('person_details')\n        -\u003ewhere('person_id', $binding[0])\n        -\u003edelete();\n}, 'my_table');\n```\n\nPixie passes the current instance of query builder as first parameter of your closure so you can build queries with this object, you can do anything like usual query builder (`QB`).\n\nIf something other than `null` is returned from the `before-*` query handler, the value will be result of execution and DB will not be actually queried (and thus, corresponding `after-*` handler will not be called ether).\n\nOnly on `after-*` events you get three parameters: **first** is the query builder, **third** is the execution time as float and **the second** varies:\n\n - On `after-query` fires after a raw query has been executed.\n - On `after-select` you get the `results` obtained from `select`.\n - On `after-insert` you get the insert id (or array of ids in case of batch insert)\n - On `after-delete` you get the [query object](#get-built-query) (same as what you get from `getQuery()`), from it you can get SQL and Bindings.\n - On `after-update` you get the [query object](#get-built-query) like `after-delete`.\n\n#### Removing event\n\n```php\n$queryBuilder-\u003eremoveEvent($event, $table = null);\n```\n\n#### Use cases\n\nHere are some cases where Query Events can be extremely helpful:\n\n - Restrict banned users.\n - Get only `deleted = 0` records.\n - Implement caching of all queries.\n - Trigger user notification after every entry.\n - Delete relationship data after a delete query.\n - Insert relationship data after an insert query.\n - Keep records of modification after each update query.\n - Add/edit created_at and updated _at data after each entry.\n\n#### Notes\n - Query Events are set as per connection basis so multiple database connection don't create any problem, and creating new query builder instance preserves your events.\n - Query Events go recursively, for example after inserting into `table_a` your event inserts into `table_b`, now you can have another event registered with `table_b` which inserts into `table_c`.\n - Of course Query Events don't work with raw queries.\n\n### Exceptions\n\n This is a list over exceptions thrown by pecee-pixie.\n\n All exceptions inherit from the base `Exception` class.\n\n | Exception name             |\n | :------------------------- |\n | `ColumnNotFoundException`  |\n | `ConnectionException`      |\n | `DuplicateColumnException` |\n | `DuplicateEntryException`  |\n | `ForeignKeyException`      |\n | `NotNullException`         |\n | `TableNotFoundException`   |\n | `Exception`                |\n\n#### Getting sql-query from exceptions\n\nIf an error occurs and you want to debug your query - you can easily do so as all exceptions thrown by Pixie will\ncontain the last executed query.\n\nYou can retrieve the `QueryObject` by calling\n\n```php\n$sql = $exception-\u003egetQueryObject()-\u003egetRawSql();\n```\n\n## Credits\n\nThis project is based on the original [Pixie project](https://github.com/usmanhalalit/pixie) by the incredible talented usmanhalalit.\n\nThanks to all the people that have contributed and the users enjoying our library.\n\nHere's some of our references:\n\n- [Holla.dk](https://holla.dk)\n- [Dscuz.com](https://dscuz.com)\n- [NinjaImg.com](https://ninjaimg.com)\n- [BookAndBegin.com](https://bookandbegin.com)\n\n___\n\n## Licence\n\nLicensed under the MIT licence.\n\n### The MIT License (MIT)\n\nCopyright (c) 2016 Simon Sessingø / pecee-pixie\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fskipperbent%2Fpecee-pixie","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fskipperbent%2Fpecee-pixie","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fskipperbent%2Fpecee-pixie/lists"}