ClickHouse Filters
A powerful Rust helper to generate ClickHouse SQL for pagination, sorting, and advanced filtering with support for complex AND/OR conditions.
Overview
clickhouse-filters
is designed to work with ClickHouse databases while maintaining API compatibility with pg_filters
. This crate helps you build SQL clauses for ClickHouse, handling:
- Complex filtering with AND/OR conditions
- Pagination with limit and offset
- Multi-column sorting
- Type-aware filtering for various ClickHouse data types
- Special ClickHouse-specific features and optimizations
- JSON filters for API-friendly filtering
Installation
Add this to your Cargo.toml
:
[]
= "0.1.0"
Supported Column Types
ClickHouse Filters supports a wide range of ClickHouse data types:
String Types
String
/FixedString
Numeric Types
- Integers:
UInt8
,UInt16
,UInt32
,UInt64
,UInt128
,UInt256
,Int8
,Int16
,Int32
,Int64
,Int128
,Int256
- Floating Points:
Float32
,Float64
Date and Time Types
Date
,Date32
DateTime
,DateTime64
Other Basic Types
Boolean
UUID
Decimal
Complex Types
- Arrays:
ArrayString
,ArrayUInt8
,ArrayUInt16
, etc. JSON
Enum8
,Enum16
- Network Types:
IPv4
,IPv6
Usage
Column Definitions
First, define your column types:
use HashMap;
use ColumnDef;
Basic Filtering
use ;
use ;
let columns = setup_columns;
// Using helper constructors
let name_filter = string;
let age_filter = uint32;
// Create filter expressions
let name_expr = Condition;
let age_expr = Condition;
// Create filtering options
let filtering = new;
// Create filters without pagination or sorting
let filters = new?;
let sql = filters.sql?;
// Results in: WHERE (lower(name) = lower('John') AND age > 18)
Supported Filter Operators
ClickHouse Filters supports a rich set of operators:
// Comparison operators
Equal // =
NotEqual // !=
GreaterThan // >
GreaterThanOrEqual // >=
LessThan // <
LessThanOrEqual // <=
// String operators
Like // LIKE
NotLike // NOT LIKE
StartsWith // LIKE 'value%'
EndsWith // LIKE '%value'
// Collection operators
In // IN (...)
NotIn // NOT IN (...)
// NULL checks
IsNull // IS NULL
IsNotNull // IS NOT NULL
// Array operators (ClickHouse specific)
ArrayContains // hasAll
ArrayHas // has
ArrayAll // ALL
ArrayAny // ANY
// Date operators
DateEqual // Exact date match
DateRange // Date between range
RelativeDate // Relative date expressions
Complex Filtering with AND/OR Logic
use ;
// Create individual conditions
let name_condition = string;
let age_condition = uint32;
let active_condition = uint8;
// Combine with AND/OR logic
let age_and_active = and;
// Finally combine everything with OR
let complex_filter = or;
// Use in FilteringOptions
let filtering = new;
// Generated SQL will be: WHERE (lower(name) LIKE lower('%John%') OR (age > 25 AND active = 1))
Array Filtering
ClickHouse has specific array functions that this library supports:
// Filter for array containing a specific value
let tags_filter = array_has;
// Generates: has(tags, 'developer')
// Filter for array containing all specified values
let tags_filter = array_contains;
// Generates: hasAll(tags, array['developer', 'rust'])
JSON Filtering
You can filter on JSON fields using path notation:
// Simple JSON field equality
let json_filter = json;
// Generates: JSONExtractString(user_data, 'subscription.type') = 'premium'
JSON-based API Filtering
For API-friendly filtering, use the JsonFilter structure:
use JsonFilter;
// Create JSON filters that can be easily serialized/deserialized
let json_filters = vec!;
// Convert to FilteringOptions
let filtering = from_json_filters?;
// Generated SQL: WHERE (age > 25 AND active = 1 OR has(tags, 'developer'))
Supported operators in JsonFilter format:
Operator | Description |
---|---|
= |
Equal |
!= |
Not Equal |
> |
Greater Than |
>= |
Greater Than or Equal |
< |
Less Than |
<= |
Less Than or Equal |
LIKE |
Like pattern matching |
NOT LIKE |
Not like pattern matching |
IN |
In a list of values (comma-separated) |
NOT IN |
Not in a list of values |
IS NULL |
Is null check |
IS NOT NULL |
Is not null check |
STARTS WITH |
Starts with pattern |
ENDS WITH |
Ends with pattern |
ARRAY HAS |
Array contains value |
ARRAY CONTAINS |
Array contains all values |
ARRAY ALL |
Check if all elements match a condition |
ARRAY ANY |
Check if any elements match a condition |
DATE_ONLY |
Match date part only |
DATE_RANGE |
Date within range (comma-separated start,end) |
RELATIVE |
Relative date expression |
Pagination
To implement pagination:
use PaginationOptions;
// Create pagination options
let pagination = new;
// Use with ClickHouseFilters
let filters = new?;
let sql = filters.sql?;
// Results in: LIMIT 15 OFFSET 15
The PaginationOptions
struct will automatically calculate:
- Page boundaries (preventing out-of-range pages)
- Proper offset values
- Previous and next page numbers
- Total page count
Sorting
To implement sorting:
use SortedColumn;
// Create sorting options
let sorting = vec!;
// Use with ClickHouseFilters
let filters = new?;
let sql = filters.sql?;
// Results in: ORDER BY age DESC, name ASC
Combining Everything
use ;
use ;
use SortedColumn;
let columns = setup_columns;
// Create a filter condition
let filter_expr = Condition;
// Create filters with pagination, sorting, and filtering
let filters = new?;
// Generate the full SQL for a query
let sql = filters.query_sql?;
// Results in: SELECT id, name, email FROM my_database.users_table WHERE lower(name) LIKE lower('J%') ORDER BY created_at DESC LIMIT 10 OFFSET 0
Complete Example with ClickHouse Client
use Client;
use ;
use ;
use Deserialize;
async
Testing
Unit tests can be run with cargo test
. Integration tests require a running ClickHouse instance via Docker containers and will be automatically set up when running cargo test --test mod
.
Compatibility with pg_filters
This library maintains API compatibility with pg_filters
where possible, allowing for easy transition between PostgreSQL and ClickHouse implementations. There are some ClickHouse-specific features and optimizations that differ from the PostgreSQL implementation, such as:
- ClickHouse-specific array functions (
has
,hasAll
) - Different JSON path extraction using
JSONExtractString
- Additional ClickHouse data types
- ClickHouse-specific date/time handling
License
Licensed under either of these:
- MIT (https://opensource.org/licenses/MIT)
- Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0)