{"id":22092124,"url":"https://github.com/krakphp/aql","last_synced_at":"2025-03-23T23:44:58.632Z","repository":{"id":57009010,"uuid":"77673420","full_name":"krakphp/aql","owner":"krakphp","description":"API Query Language","archived":false,"fork":false,"pushed_at":"2017-04-09T08:48:39.000Z","size":37,"stargazers_count":1,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-29T06:52:26.295Z","etag":null,"topics":["aql","ast","semantic-analysis"],"latest_commit_sha":null,"homepage":null,"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/krakphp.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}},"created_at":"2016-12-30T08:38:25.000Z","updated_at":"2021-08-20T10:16:51.000Z","dependencies_parsed_at":"2022-08-21T14:31:01.130Z","dependency_job_id":null,"html_url":"https://github.com/krakphp/aql","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krakphp%2Faql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krakphp%2Faql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krakphp%2Faql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krakphp%2Faql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/krakphp","download_url":"https://codeload.github.com/krakphp/aql/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245186925,"owners_count":20574554,"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":["aql","ast","semantic-analysis"],"created_at":"2024-12-01T03:08:23.167Z","updated_at":"2025-03-23T23:44:58.611Z","avatar_url":"https://github.com/krakphp.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# AQL - API Query Language\n\nAPI Query Language is a library designed to validate/transform string expressions to be used in API's for querying/filtering data. It allows user generated expressions to be used for querying data sets yet allows full verification to prevent any unwanted expression types.\n\n## Installation\n\nInstall with composer at `krak/aql`.\n\n## Usage\n\nAn example might be the easiest way to understand what this library does.\n\n```php\n\u003c?php\n\nuse Krak\\AQL;\n\n$engine = AQL\\Engine::createWithDomain([\n    'orders' =\u003e ['status', 'created_at']\n]);\n$query = 'orders.created_at \u003c date(now()) and orders.status = \"cancelled\"';\ntry {\n    $processed_query = $engine-\u003eprocess($query);\n} catch (AQL\\AQLException $e) {\n    // any errors regarding data syntax or semantics will be caught here.\n}\n```\n\nThe `AQL\\Engine::process` does several things.\n\n1. It parses the expression into an AST. Any syntax or lexing errors will be thrown here. This includes bad characters or an invalid expression.\n2. It runs semantic analysis on the generated AST which will verify that the expression makes sense and can enforce any custom domain rules. In the example above, it makes sure the fields being compared are within the `orders.{status,created_at}` domain.\n3. It runs any custom transformations\n4. It then compiles the AST back into a string to be used for generating queries.\n\nThe final `$processed_query` is now validated and can be used as part of an SQL where clause or something similar. Thus, it provides a way for API's to support a powerful query interface while providing total control of the queries generated.\n\n### Sort Queries\n\nIn addition to expression queries that can be used in database `WHERE` clause. The library also supports parsing sort expressions which might show up in a database `ORDER BY` clause.\n\n```php\n\u003c?php\n\nuse Krak\\AQL;\n\n$engine = AQL\\Engine::createSortWithDomain([\n    'categories' =\u003e ['sort', 'created_at']\n]);\n$query = 'categories.sort DESC, categories.created_at'; // defaults to ASCENDING.\ntry {\n    $processed_query = $engine-\u003eprocess($query);\n} catch (AQL\\AQLException $e) {\n    // any errors regarding data syntax or semantics will be caught here.\n}\n```\n\n\n## Visitors\n\nVisitors provide a way to transform the AST. In context of the engine, visitors are run *after* semantic analysis. Each visitor implements `Krak\\AQL\\AST\\Visitor`. The AST accepts the visitor and then traverses itself with a [Depth First Pre-Order Traversal](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search).\n\n### Chain Visitor\n\nThe chain visitor `Krak\\AQL\\AST\\ChainVisitor` accepts an array of other visitors. As it the AST is being traversed, it delegates to each of the other visitors. This allows for many transformations in one Pass.\n\n### DoubleToSingleQuotes Visitor\n\nThis visitor `Krak\\AQL\\Visitor\\DoubleToSingleQuotesVisitor` transforms double quoted strings to single quotes.\n\nSo this input:\n\n```\n\"string\"\n```\n\nwould be be mapped to:\n\n```\n'string'\n```\n\n### RenameId Visitor\n\nThis visitor `Krak\\AQL\\Visitor\\RenameIdVisitor` renames identifiers. You can use dot notation to access sub identifiers.\n\n```php\n$ast-\u003eaccept(new AQL\\Visitor\\RenameIdVisitor([\n    'a' =\u003e 'alpha',\n    'b' =\u003e 'beta',\n    'b.a' =\u003e 'attribute',\n]));\n```\n\nUsing this rename visitor, it'd apply the following transformation:\n\n```\na = b.a\n```\n\nGoes to:\n\n```\nalpha = beta.attribute\n```\n\n### FuncEval Visitor\n\nThe FuncEval lets your evaluate a function and transform it into another Element value.\n\nIt can turn an input:\n\n```\n1 = id(1)\n```\n\nto:\n\n```\n1 = 1\n```\n\nCheckout [example/func-eval.php](example/func-eval.php) to see a working example.\n\n## Semantic Analysis\n\nSemantic Analysis provides extra validation of the parsed AST to make sure the parsed expression is semantically correct.\n\nSA Enforcers are simply just visitors that will throw an `SAException` if the AST failed semantic analysis. SA is done via a single pass because it makes use of the `AST\\ChainVisitor`.\n\nTo utilize SA, you create your list of enforces and construct the `SemanticAnalysis` object.\n\n```php\n\u003c?php\n\n$sa = new SA\\SemanticAnalysis([$enforce]);\n$sa-\u003eanalyze($ast);\n```\n\n### EnforceDomain\n\nEnforces identifiers are within a certain domain.\n\n```php\n\u003c?php\n\n$enforce = new SA\\EnforceDomain([\n    'user' =\u003e [\n        'id',\n        'email',\n        'group' =\u003e ['id', 'name']\n    ]\n]);\n```\n\nThis would allow any identifier path like `user.id`, `user.email`, `user.group.id` and a few others.\n\n### EnforceFunc\n\nEnforces only certain functions to be used.\n\n```php\n\u003c?php\n\n$enforce = new SA\\EnforceFunc(['now', 'date']);\n```\n\nThis would allow only the `now` and `date` functions to be used, anything else would throw an exception.\n\n## Parser\n\nThere are two interfaces into the AQLParser: ExpressionParser and SortParser.\n\nThe ExpressionParser will assume a string input is an expression and parse accordingly. The SortParser will assume a string is a SortExpressionList and parse accordingly. Each Parser will return a root AST node of Expression or SortExpressionList accordingly.\n\n### Operators\n\nFrom highest to lowest precedence\n\n```\n()\n\u003c = \u003e \u003c= \u003e= IN LIKE\nAND\nOR\n```\n\n### EBNF (Grammar)\n\n    Expression    ::= AndExpression | AndExpression \"OR\" Expression\n    AndExpression ::= OpExpression | OpExression \"AND\" AndExpression\n    OpExpression  ::= Element\n    OpExpression  ::= Element \"\u003c\" OpExpression\n    OpExpression  ::= Element \"\u003e\" OpExpression\n    OpExpression  ::= Element \"=\" OpExpression\n    OpExpression  ::= Element \"!=\" OpExpression\n    OpExpression  ::= Element \"\u003c=\" OpExpression\n    OpExpression  ::= Element \"\u003e=\" OpExpression\n    OpExpression  ::= Element \"LIKE\" OpExpression\n    OpExpression  ::= Element \"IN\" \"(\" ValueList \")\"\n    Element       ::= Value | IdExpression | Func | \"(\" Expression \")\"\n    Value         ::= string | number\n    ValueList     ::= Value | Value \",\" ValueList\n    IdExpression  ::= identifier | identifier \".\" IdExpression\n    Func          ::= identifier \"(\" ElementList \")\"\n    ElementList   ::= Element | Element \",\" ElementList\n\n    SortExpressionList ::= SortExpression | SortExpression \",\" SortExpressionList\n    SortExpression     ::= IdExpression \"DESC\"\n    SortExpression     ::= IdExpression \"ASC\"\n    SortExpression     ::= IdExpression\n\n    string     = \"[^\"]\\*\"\n    number     = (\\d*\\.\\d+|\\d+)\n    identifier = [_a-zA-Z][_a-zA-Z0-9]*\n\n## Tests\n\nTests are executed via [Peridot](http://peridot-php.github.io)\n\n```\nmake test\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkrakphp%2Faql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkrakphp%2Faql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkrakphp%2Faql/lists"}