{"id":16446612,"url":"https://github.com/sad-spirit/pg-builder","last_synced_at":"2025-08-20T12:32:03.614Z","repository":{"id":20966370,"uuid":"24255170","full_name":"sad-spirit/pg-builder","owner":"sad-spirit","description":"Query builder for Postgres backed by SQL parser","archived":false,"fork":false,"pushed_at":"2024-05-21T19:23:48.000Z","size":1597,"stargazers_count":50,"open_issues_count":0,"forks_count":5,"subscribers_count":2,"default_branch":"2.x","last_synced_at":"2024-05-22T13:50:39.164Z","etag":null,"topics":["ast","php","postgres","postgresql","query-builder","query-parser","sql","sql-builder","sql-parser"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-2-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sad-spirit.png","metadata":{"files":{"readme":"README.md","changelog":"Changelog.md","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":"2014-09-20T05:58:34.000Z","updated_at":"2024-06-19T05:16:39.132Z","dependencies_parsed_at":"2024-06-19T05:16:37.213Z","dependency_job_id":"3d033b02-8554-48a6-b423-b59928edb0ae","html_url":"https://github.com/sad-spirit/pg-builder","commit_stats":{"total_commits":315,"total_committers":3,"mean_commits":105.0,"dds":0.006349206349206327,"last_synced_commit":"c37c44cb71a6594b2c56c1f6b28d15ea303fcc95"},"previous_names":[],"tags_count":24,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sad-spirit%2Fpg-builder","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sad-spirit%2Fpg-builder/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sad-spirit%2Fpg-builder/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sad-spirit%2Fpg-builder/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sad-spirit","download_url":"https://codeload.github.com/sad-spirit/pg-builder/tar.gz/refs/heads/2.x","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":230423564,"owners_count":18223435,"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":["ast","php","postgres","postgresql","query-builder","query-parser","sql","sql-builder","sql-parser"],"created_at":"2024-10-11T09:48:13.609Z","updated_at":"2024-12-19T11:12:50.300Z","avatar_url":"https://github.com/sad-spirit.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# sad_spirit/pg_builder\n\n[![Build Status](https://github.com/sad-spirit/pg-builder/workflows/Continuous%20Integration/badge.svg?branch=2.x)](https://github.com/sad-spirit/pg-builder/actions?query=branch%3A2.x+workflow%3A%22Continuous+Integration%22)\n\n[![Static Analysis](https://github.com/sad-spirit/pg-builder/workflows/Static%20Analysis/badge.svg?branch=2.x)](https://github.com/sad-spirit/pg-builder/actions?query=branch%3A2.x+workflow%3A%22Static+Analysis%22)\n\nThis is a query builder for Postgres with a twist: it contains a partial\u003csup\u003e[1](#footnote1)\u003c/sup\u003e reimplementation of PostgreSQL's own\nquery parser. This sets it aside from the usual breed of \"write-only\" query builders:\n\n* Query is represented as an Abstract Syntax Tree quite similar to PostgreSQL's internal representation.\n* Query parts can be added to the AST either as objects or as strings (that will be processed by Parser).\n* Nodes can be removed and replaced in AST.\n* AST can be analyzed and transformed, the package takes advantage of this to allow named parameters like\n  `:foo` instead of standard PostgreSQL's positional parameters `$1` and to infer parameters' types\n  from SQL typecasts.\n* Almost all syntax available for `SELECT` (and `VALUES`) / `INSERT` / `UPDATE` / `DELETE` / `MERGE` in PostgreSQL 16\n  is supported, query being built is automatically checked for correct syntax.\n\nSubstantial effort was made to optimise parsing, but not parsing is faster anyway, so there are means to cache parts \nof AST and the resultant query.\n\n## Usage example\n\n```PHP\nuse sad_spirit\\pg_builder\\{\n    Select,\n    StatementFactory,\n    converters\\BuilderSupportDecorator\n};\nuse sad_spirit\\pg_wrapper\\{\n    Connection,\n    converters\\DefaultTypeConverterFactory\n};\n\n$wantPDO = false;\n\nif ($wantPDO) {\n    $pdo       = new \\PDO('pgsql:host=localhost;user=username;dbname=cms');\n    // Uses DB connection properties to set up parsing and building of SQL \n    $factory   = StatementFactory::forPDO($pdo);\n    // NB: This still requires sad_spirit/pg_wrapper for type conversion code\n    $converter = new BuilderSupportDecorator(new DefaultTypeConverterFactory(), $factory-\u003egetParser());\n} else {\n    $connection = new Connection('host=localhost user=username dbname=cms');\n    // Uses DB connection properties to set up parsing and building of SQL \n    $factory    = StatementFactory::forConnection($connection);\n    // Needed for handling type info extracted from query\n    $connection-\u003esetTypeConverterFactory(new BuilderSupportDecorator(\n        $connection-\u003egetTypeConverterFactory(),\n        $factory-\u003egetParser()\n    ));\n}\n\n// latest 5 news\n/** @var Select $query */\n$query      = $factory-\u003ecreateFromString(\n    'select n.* from news as n order by news_added desc limit 5'\n);\n\n// we also need pictures for these...\n$query-\u003elist[] = 'p.*';\n$query-\u003efrom[0]-\u003eleftJoin('pictures as p')-\u003eon = 'n.picture_id = p.picture_id';\n\n// ...and need to limit them to only specific rubrics\n$query-\u003efrom[] = 'objects_rubrics as ro';\n$query-\u003ewhere-\u003eand('ro.rubric_id = any(:rubric::integer[]) and ro.obj_id = n.news_id');\n\n// ...and keep 'em fresh\n$query-\u003ewhere-\u003eand('age(news_added) \u003c :age::interval');\n\n// $generated contains a query, mapping from named parameters to positional ones, types info\n// it can be easily cached to prevent parsing/building SQL on each request\n$generated = $factory-\u003ecreateFromAST($query);\n\n// Note that we don't have to specify parameter types, these are extracted from query\nif ($wantPDO) {\n    $result = $pdo-\u003eprepare($generated-\u003egetSql());\n    $result-\u003eexecute($converter-\u003econvertParameters(\n        $generated,\n        [\n            'rubric' =\u003e [19, 20, 21],\n            'age'    =\u003e 30 * 24 * 3600        \n        ]       \n    ));\n} else {\n    $result = $generated-\u003eexecuteParams(\n        $connection, \n        [\n            'rubric' =\u003e [19, 20, 21],\n            'age'    =\u003e 30 * 24 * 3600\n        ]\n    );\n}\n\n\nforeach ($result as $row) {\n    print_r($row);\n}\n\necho $generated-\u003egetSql();\n```\nthe last `echo` statement will output something like\n```SQL\nselect n.*, p.*\nfrom news as n left join pictures as p on n.picture_id = p.picture_id, objects_rubrics as ro\nwhere ro.rubric_id = any($1::pg_catalog.int4[])\n    and ro.obj_id = n.news_id\n    and age(news_added) \u003c $2::interval\norder by news_added desc\nlimit 5\n```\nif targeting `Connection` and something like\n```SQL\nselect n.*, p.*\nfrom news as n left join pictures as p on n.picture_id = p.picture_id, objects_rubrics as ro\nwhere ro.rubric_id = any(:rubric::pg_catalog.int4[])\n    and ro.obj_id = n.news_id\n    and age(news_added) \u003c :age::interval\norder by news_added desc\nlimit 5\n```\nif targeting PDO\n\n## Documentation\n\nIs in the [wiki](https://github.com/sad-spirit/pg-builder/wiki)\n\n---\n\u003ca name=\"footnote1\"\u003e1\u003c/a\u003e: \"Partial\" here means the following: PostgreSQL grammar file `src/backend/parser/gram.y` is about 19K lines long. \nOf these about 5K lines are used for `SELECT` / `INSERT` / `UPDATE` / `DELETE` / `MERGE` queries and are reimplemented here.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsad-spirit%2Fpg-builder","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsad-spirit%2Fpg-builder","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsad-spirit%2Fpg-builder/lists"}