{"id":16924463,"url":"https://github.com/devtheorem/peachy-sql","last_synced_at":"2026-01-03T15:30:18.045Z","repository":{"id":14195758,"uuid":"16902315","full_name":"devtheorem/peachy-sql","owner":"devtheorem","description":"A high-performance query builder and runner for PHP","archived":false,"fork":false,"pushed_at":"2025-01-27T00:04:01.000Z","size":340,"stargazers_count":22,"open_issues_count":1,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-02-10T20:24:04.342Z","etag":null,"topics":["pdo","php","sql"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"sergiou87/SPDebugMenu","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/devtheorem.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","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":"2014-02-17T04:56:18.000Z","updated_at":"2025-01-26T23:56:17.000Z","dependencies_parsed_at":"2024-10-28T04:26:51.819Z","dependency_job_id":null,"html_url":"https://github.com/devtheorem/peachy-sql","commit_stats":{"total_commits":224,"total_committers":3,"mean_commits":74.66666666666667,"dds":0.0669642857142857,"last_synced_commit":"82485e6580170d41208724a102a9bcbb2f76dc37"},"previous_names":["devtheorem/peachysql","theodorejb/peachy-sql","devtheorem/peachy-sql"],"tags_count":31,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devtheorem%2Fpeachy-sql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devtheorem%2Fpeachy-sql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devtheorem%2Fpeachy-sql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devtheorem%2Fpeachy-sql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/devtheorem","download_url":"https://codeload.github.com/devtheorem/peachy-sql/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239731673,"owners_count":19687874,"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":["pdo","php","sql"],"created_at":"2024-10-13T20:05:15.962Z","updated_at":"2026-01-03T15:30:17.960Z","avatar_url":"https://github.com/devtheorem.png","language":"PHP","readme":"# PeachySQL\n\nPeachySQL is a high-performance query builder and runner which streamlines prepared statements\nand working with large datasets. It is officially tested with MySQL, PostgreSQL, and SQL Server,\nbut it should also work with any standards-compliant database which has a driver for PDO.\n\n## Install via Composer\n\n`composer require devtheorem/peachy-sql`\n\n## Usage\n\nStart by instantiating the `PeachySql` class with a database connection,\nwhich should be an existing [PDO object](https://www.php.net/manual/en/class.pdo.php):\n\n```php\nuse DevTheorem\\PeachySQL\\PeachySql;\n\n$connection = new PDO('sqlsrv:server=(local)', $username, $password, [\n    PDO::ATTR_EMULATE_PREPARES =\u003e false,\n    PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE =\u003e true,\n    'Database' =\u003e 'someDbName',\n]);\n\n$db = new PeachySql($connection);\n```\n\nAfter instantiation, arbitrary statements can be prepared by passing a\nSQL string and array of bound parameters to the `prepare()` method:\n\n```php\n$sql = \"UPDATE Users SET fname = ? WHERE user_id = ?\";\n$stmt = $db-\u003eprepare($sql, [\u0026$fname, \u0026$id]);\n\n$nameUpdates = [\n    3 =\u003e 'Theodore',\n    7 =\u003e 'Luke',\n];\n\nforeach ($nameUpdates as $id =\u003e $fname) {\n    $stmt-\u003eexecute();\n}\n\n$stmt-\u003eclose();\n```\n\nMost of the time prepared statements only need to be executed a single time.\nTo make this easier, PeachySQL provides a `query()` method which automatically\nprepares, executes, and closes a statement after results are retrieved:\n\n```php\n$sql = 'SELECT * FROM Users WHERE fname LIKE ? AND lname LIKE ?';\n$result = $db-\u003equery($sql, ['theo%', 'b%']);\necho json_encode($result-\u003egetAll());\n```\n\nBoth `prepare()` and `query()` return a `Statement` object with the following methods:\n\n| Method          | Behavior                                                                                                         |\n|-----------------|------------------------------------------------------------------------------------------------------------------|\n| `execute()`     | Executes the prepared statement (automatically called when using `query()`).                                     |\n| `getIterator()` | Returns a `Generator` object which can be used to iterate over large result sets without caching them in memory. |\n| `getAll()`      | Returns all selected rows as an array of associative arrays.                                                     |\n| `getFirst()`    | Returns the first selected row as an associative array (or `null` if no rows were selected).                     |\n| `getAffected()` | Returns the number of rows affected by the query.                                                                |\n| `close()`       | Closes the prepared statement and frees its resources (automatically called when using `query()`).               |\n\nInternally, `getAll()` and `getFirst()` are implemented using `getIterator()`.\nAs such they can only be called once for a given statement.\n\n### Shorthand methods\n\nPeachySQL comes with five shorthand methods for selecting, inserting, updating,\nand deleting records.\n\n\u003e [!NOTE]\n\u003e To prevent SQL injection, the queries PeachySQL generates for these methods\n\u003e always use bound parameters for values, and column names are automatically escaped.\n\n#### select / selectFrom\n\nThe `selectFrom()` method takes a single string argument containing a SQL SELECT query.\nIt returns an object with three chainable methods:\n\n1. `where()`\n2. `orderBy()`\n3. `offset()`\n\nAdditionally, the object has a `getSqlParams()` method which builds the select query,\nand a `query()` method which executes the query and returns a `Statement` object.\n\n```php\n// select all columns and rows in a table, ordered by last name and then first name\n$rows = $db-\u003eselectFrom(\"SELECT * FROM Users\")\n    -\u003eorderBy(['lname', 'fname'])\n    -\u003equery()-\u003egetAll();\n\n// select from multiple tables with conditions and pagination\n$rows = $db-\u003eselectFrom(\"SELECT * FROM Users u INNER JOIN Customers c ON c.CustomerID = u.CustomerID\")\n    -\u003ewhere(['c.CustomerName' =\u003e 'Amazing Customer'])\n    -\u003eorderBy(['u.fname' =\u003e 'desc', 'u.lname' =\u003e 'asc'])\n    -\u003eoffset(0, 50) // page 1 with 50 rows per page\n    -\u003equery()-\u003egetIterator();\n```\n\nThe `select()` method works the same as `selectFrom()`, but takes a `SqlParams`\nobject rather than a string and supports bound params in the select query:\n\n```php\nuse DevTheorem\\PeachySQL\\QueryBuilder\\SqlParams;\n\n$sql = \"\n    WITH UserVisits AS (\n        SELECT user_id, COUNT(*) AS recent_visits\n        FROM UserHistory\n        WHERE date \u003e ?\n        GROUP BY user_id\n    )\n    SELECT u.fname, u.lname, uv.recent_visits\n    FROM Users u\n    INNER JOIN UserVisits uv ON uv.user_id = u.user_id\";\n\n$date = (new DateTime('2 months ago'))-\u003eformat('Y-m-d');\n\n$rows = $db-\u003eselect(new SqlParams($sql, [$date]))\n    -\u003ewhere(['u.status' =\u003e 'verified'])\n    -\u003equery()-\u003egetIterator();\n```\n\n##### Where clause generation\n\nIn addition to passing basic column =\u003e value arrays to the `where()` method, you can\nspecify more complex conditions by using arrays as values. For example, passing\n`['col' =\u003e ['lt' =\u003e 15, 'gt' =\u003e 5]]` would generate the condition `WHERE col \u003c 15 AND col \u003e 5`.\n\nFull list of recognized operators:\n\n| Operator | SQL condition |\n|----------|---------------|\n| eq       | =             |\n| ne       | \u003c\u003e            |\n| lt       | \u003c             |\n| le       | \u003c=            |\n| gt       | \u003e             |\n| ge       | \u003e=            |\n| lk       | LIKE          |\n| nl       | NOT LIKE      |\n| nu       | IS NULL       |\n| nn       | IS NOT NULL   |\n\nIf a list of values is passed with the `eq` or `ne` operator, it will generate an\nIN(...) or NOT IN(...) condition, respectively. Passing a list with the `lk`, `nl`,\n`nu`, or `nn` operator will generate an AND condition for each value. The `lt`, `le`,\n`gt`, and `ge` operators cannot be used with a list of values.\n\n#### insertRow\n\nThe `insertRow()` method allows a single row to be inserted from an associative array.\nIt returns an `InsertResult` object with readonly `id` and `affected` properties.\n\n```php\n$userData = [\n    'fname' =\u003e 'Donald',\n    'lname' =\u003e 'Chamberlin'\n];\n\n$id = $db-\u003einsertRow('Users', $userData)-\u003eid;\n```\n\n#### insertRows\n\nThe `insertRows()` method makes it possible to bulk-insert multiple rows from an array.\nIt returns a `BulkInsertResult` object with readonly `ids`, `affected`, and `queryCount` properties.\n\n```php\n$userData = [\n    [\n        'fname' =\u003e 'Grace',\n        'lname' =\u003e 'Hopper'\n    ],\n    [\n        'fname' =\u003e 'Douglas',\n        'lname' =\u003e 'Engelbart'\n    ],\n    [\n        'fname' =\u003e 'Margaret',\n        'lname' =\u003e 'Hamilton'\n    ]\n];\n\n$result = $db-\u003einsertRows('Users', $userData);\n$ids = $result-\u003eids; // e.g. [64, 65, 66]\n$affected = $result-\u003eaffected; // 3\n$queries = $result-\u003equeryCount; // 1\n```\n\nAn optional third parameter can be passed to `insertRows()` to override the default\nidentity increment value:\n\n```php\n$result = $db-\u003einsertRows('Users', $userData, 2);\n$ids = $result-\u003eids; // e.g. [64, 66, 68]\n```\n\n\u003e [!NOTE]\n\u003e SQL Server allows a maximum of 1,000 rows to be inserted at a time, and limits individual queries\n\u003e to 2,099 or fewer bound parameters. MySQL and PostgreSQL support a maximum of 65,535 bound\n\u003e parameters per query. These limits can be easily reached when attempting to bulk-insert hundreds\n\u003e or thousands of rows at a time. To avoid these limits, the `insertRows()` method automatically\n\u003e splits row sets that exceed the limits into chunks to efficiently insert any number of rows\n\u003e (`queryCount` contains the number of required queries).\n\n#### updateRows and deleteFrom\n\nThe `updateRows()` method takes three arguments: a table name, an associative array of\ncolumns/values to update, and a WHERE array to filter which rows are updated.\n\nThe `deleteFrom()` method takes a table name and a WHERE array to filter the rows to delete.\n\nBoth methods return the number of affected rows.\n\n```php\n// update the user with user_id 4\n$newData = ['fname' =\u003e 'Raymond', 'lname' =\u003e 'Boyce'];\n$db-\u003eupdateRows('Users', $newData, ['user_id' =\u003e 4]);\n\n// delete users with IDs 1, 2, and 3\n$userTable-\u003edeleteFrom('Users', ['user_id' =\u003e [1, 2, 3]]);\n```\n\n### Transactions\n\nCall the `begin()` method to start a transaction. `prepare()`, `execute()`, `query()`\nand any of the shorthand methods can then be called as needed, before committing\nor rolling back the transaction with `commit()` or `rollback()`.\n\n### Binary columns\n\nIn order to insert/update raw binary data (e.g. to a binary, blob, or bytea column),\nthe bound parameter must have its encoding type set to binary. PeachySQL provides a\n`makeBinaryParam()` method to simplify this:\n\n```php\n$db-\u003einsertRow('Users', [\n    'fname' =\u003e 'Tony',\n    'lname' =\u003e 'Hoare',\n    'uuid' =\u003e $db-\u003emakeBinaryParam(Uuid::uuid4()-\u003egetBytes()),\n]);\n```\n\n## Author\n\nTheodore Brown  \n\u003chttps://theodorejb.me\u003e\n\n## License\n\nMIT\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevtheorem%2Fpeachy-sql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdevtheorem%2Fpeachy-sql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevtheorem%2Fpeachy-sql/lists"}