Fexpr
A Crystal port of ganigeorgiev/fexpr, a filter expression parser that generates AST structures from user input for safe creation of SQL, Elasticsearch, and other queries.
Installation
-
Add the dependency to your
shard.yml
:dependencies: fexpr: github: rubyattack3r/fexpr
-
Run
shards install
Usage
require "fexpr"
Basic Example
# Input: "id > 1"
result = Fexpr.parse("id > 1")
# => [ExpressionGroup.new(
# item: Expression.new(
# left: Token.new(type: TokenType::Identifier, literal: "id"),
# operation: SignOperation::SignGt,
# right: Token.new(type: TokenType::Number, literal: "1")
# ),
# join: JoinOperation::JoinAnd
# )]
Supported Operators
-
Comparison Operators:
=
Equal!=
NOT Equal>
Greater than>=
Greater than or equal<
Less than<=
Less than or equal~
Like/Contains!~
NOT Like/Contains
-
Array Operators:
?=
Array/Any equal?!=
Array/Any NOT Equal?>
Array/Any Greater than?>=
Array/Any Greater than or equal?<
Array/Any Less than?<=
Array/Any Less than or equal?~
Array/Any Like/Contains?!~
Array/Any NOT Like/Contains
-
Logical Operators:
&&
AND join operator||
OR join operator()
Parenthesis for grouping
Token Types
Numbers
Number tokens can be integer or decimal numbers:
"123" # Integer
"10.50" # Decimal
"-14" # Negative
Identifiers
Identifiers start with a letter, _
, @
or #
and can contain letters, digits, .
or :
:
"id" # Simple identifier
"a.b.c" # Nested field
"field123" # With numbers
"@request.method" # With @ prefix
"author.name:length" # With modifier
Quoted Text
Text can be wrapped in single or double quotes:
"'Lorem ipsum dolor 123!'" # Single quotes
"\"escaped \\\"word\\\"\"" # Escaped quotes
"\"mixed 'quotes' are fine\"" # Mixed quotes
Comments
Single line comments start with //
and are ignored by the parser:
"// This is a comment"
Contributing
- Fork it (https://github.com/rubyattack3r/fexpr/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Contributors
- rubyattack3r - creator and maintainer