Crate prax_query

Crate prax_query 

Source
Expand description

§prax-query

Type-safe query builder for the Prax ORM.

This crate provides the core query building functionality, including:

  • Fluent API for building queries (find_many, find_unique, create, update, delete)
  • Type-safe filtering with where clauses
  • Sorting and pagination
  • Relation loading (include, select)
  • Transaction support
  • Raw SQL escape hatch
  • Middleware system
  • Multi-tenant support

§Filters

Build type-safe filters for queries:

use prax_query::{Filter, FilterValue};

// Equality filter
let filter = Filter::Equals("email".into(), FilterValue::String("test@example.com".into()));

// Greater than filter
let filter = Filter::Gt("age".into(), FilterValue::Int(18));

// Contains filter (for strings)
let filter = Filter::Contains("name".into(), FilterValue::String("john".into()));

// Combine filters with AND/OR
let combined = Filter::and([
    Filter::Equals("active".into(), FilterValue::Bool(true)),
    Filter::Gt("age".into(), FilterValue::Int(18)),
]);

let either = Filter::or([
    Filter::Equals("role".into(), FilterValue::String("admin".into())),
    Filter::Equals("role".into(), FilterValue::String("moderator".into())),
]);

§Filter Values

Convert Rust types to filter values:

use prax_query::FilterValue;

// Integer values
let val: FilterValue = 42.into();
assert!(matches!(val, FilterValue::Int(42)));

// String values
let val: FilterValue = "hello".into();
assert!(matches!(val, FilterValue::String(_)));

// Boolean values
let val: FilterValue = true.into();
assert!(matches!(val, FilterValue::Bool(true)));

// Float values
let val: FilterValue = 3.14f64.into();
assert!(matches!(val, FilterValue::Float(_)));

// Null values
let val = FilterValue::Null;

§Sorting

Build sort specifications:

use prax_query::{OrderBy, OrderByField, NullsOrder};

// Ascending order
let order = OrderByField::asc("created_at");

// Descending order
let order = OrderByField::desc("updated_at");

// With NULLS FIRST/LAST
let order = OrderByField::asc("name").nulls(NullsOrder::First);
let order = OrderByField::desc("score").nulls(NullsOrder::Last);

// Combine multiple orderings
let orders = OrderBy::Field(OrderByField::asc("name"))
    .then(OrderByField::desc("created_at"));

§Raw SQL

Build raw SQL queries with parameter binding:

use prax_query::Sql;

// Simple query
let sql = Sql::new("SELECT * FROM users");
assert_eq!(sql.sql(), "SELECT * FROM users");

// Query with parameter - bind appends placeholder
let sql = Sql::new("SELECT * FROM users WHERE id = ")
    .bind(42);
assert_eq!(sql.params().len(), 1);

§Connection Strings

Parse database connection strings:

use prax_query::ConnectionString;

// PostgreSQL
let conn = ConnectionString::parse("postgres://user:pass@localhost:5432/mydb").unwrap();
assert_eq!(conn.host(), Some("localhost"));
assert_eq!(conn.port(), Some(5432));
assert_eq!(conn.database(), Some("mydb"));

// MySQL
let conn = ConnectionString::parse("mysql://user:pass@localhost:3306/mydb").unwrap();

§Transaction Config

Configure transaction behavior:

use prax_query::IsolationLevel;

let level = IsolationLevel::Serializable;
assert_eq!(level.as_sql(), "SERIALIZABLE");

§Error Handling

Work with query errors:

use prax_query::{QueryError, ErrorCode};

// Create errors
let err = QueryError::not_found("User");
assert_eq!(err.code, ErrorCode::RecordNotFound);

Re-exports§

pub use error::ErrorCode;
pub use error::ErrorContext;
pub use error::QueryError;
pub use error::QueryResult;
pub use error::Suggestion;
pub use extension::Extension;
pub use extension::ExtensionBuilder;
pub use extension::Point;
pub use extension::Polygon;
pub use filter::AndFilterBuilder;
pub use filter::FieldName;
pub use filter::Filter;
pub use filter::FilterValue;
pub use filter::FluentFilterBuilder;
pub use filter::LargeValueList;
pub use filter::OrFilterBuilder;
pub use filter::ScalarFilter;
pub use filter::SmallValueList;
pub use filter::ValueList;
pub use json::JsonAgg;
pub use json::JsonFilter;
pub use json::JsonIndex;
pub use json::JsonIndexBuilder;
pub use json::JsonOp;
pub use json::JsonPath;
pub use json::PathSegment;
pub use nested::NestedWrite;
pub use nested::NestedWriteBuilder;
pub use nested::NestedWriteOperations;
pub use operations::CreateOperation;
pub use operations::DeleteOperation;
pub use operations::FindManyOperation;
pub use operations::FindUniqueOperation;
pub use operations::UpdateOperation;
pub use operations::MaterializedViewAccessor;
pub use operations::RefreshMaterializedViewOperation;
pub use operations::ViewAccessor;
pub use operations::ViewCountOperation;
pub use operations::ViewFindFirstOperation;
pub use operations::ViewFindManyOperation;
pub use operations::ViewQueryBuilder;
pub use pagination::Cursor;
pub use pagination::CursorDirection;
pub use pagination::Pagination;
pub use partition::HashPartitionDef;
pub use partition::ListPartitionDef;
pub use partition::Partition;
pub use partition::PartitionBuilder;
pub use partition::PartitionDef;
pub use partition::PartitionType;
pub use partition::RangeBound;
pub use partition::RangePartitionDef;
pub use procedure::Parameter;
pub use procedure::ParameterMode;
pub use procedure::ProcedureCall;
pub use procedure::ProcedureCallOperation;
pub use procedure::ProcedureEngine;
pub use procedure::ProcedureResult;
pub use query::QueryBuilder;
pub use raw::RawExecuteOperation;
pub use raw::RawQueryOperation;
pub use raw::Sql;
pub use relations::Include;
pub use relations::IncludeSpec;
pub use relations::RelationLoader;
pub use relations::RelationSpec;
pub use relations::SelectSpec;
pub use search::FullTextIndex;
pub use search::FullTextIndexBuilder;
pub use search::FuzzyOptions;
pub use search::HighlightOptions;
pub use search::RankingOptions;
pub use search::SearchLanguage;
pub use search::SearchMode;
pub use search::SearchQuery;
pub use search::SearchQueryBuilder;
pub use search::SearchSql;
pub use security::ConnectionProfile;
pub use security::ConnectionProfileBuilder;
pub use security::DataMask;
pub use security::Grant;
pub use security::GrantBuilder;
pub use security::GrantObject;
pub use security::MaskFunction;
pub use security::PolicyCommand;
pub use security::Privilege;
pub use security::RlsPolicy;
pub use security::RlsPolicyBuilder;
pub use security::Role;
pub use security::RoleBuilder;
pub use security::TenantPolicy;
pub use security::TenantSource;
pub use sequence::OwnedBy;
pub use sequence::Sequence;
pub use sequence::SequenceBuilder;
pub use traits::Executable;
pub use traits::IntoFilter;
pub use traits::MaterializedView;
pub use traits::Model;
pub use traits::QueryEngine;
pub use traits::View;
pub use traits::ViewQueryEngine;
pub use transaction::IsolationLevel;
pub use transaction::Transaction;
pub use transaction::TransactionConfig;
pub use trigger::Trigger;
pub use trigger::TriggerAction;
pub use trigger::TriggerBuilder;
pub use trigger::TriggerCondition;
pub use trigger::TriggerEvent;
pub use trigger::TriggerLevel;
pub use trigger::TriggerTiming;
pub use trigger::UpdateOf;
pub use types::NullsOrder;
pub use types::OrderBy;
pub use types::OrderByBuilder;
pub use types::OrderByField;
pub use types::Select;
pub use types::SortOrder;
pub use types::order_patterns;
pub use upsert::Assignment;
pub use upsert::AssignmentValue;
pub use upsert::ConflictAction;
pub use upsert::ConflictTarget;
pub use upsert::UpdateSpec;
pub use upsert::Upsert;
pub use upsert::UpsertBuilder;
pub use window::FrameBound;
pub use window::FrameClause;
pub use window::FrameExclude;
pub use window::FrameType;
pub use window::NamedWindow;
pub use window::NullsPosition;
pub use window::OrderSpec;
pub use window::WindowFn;
pub use window::WindowFunction;
pub use window::WindowFunctionBuilder;
pub use window::WindowSpec;
pub use middleware::LoggingMiddleware;
pub use middleware::MetricsMiddleware;
pub use middleware::Middleware;
pub use middleware::MiddlewareBuilder;
pub use middleware::MiddlewareChain;
pub use middleware::MiddlewareStack;
pub use middleware::QueryContext;
pub use middleware::QueryMetadata;
pub use middleware::QueryMetrics;
pub use middleware::QueryType;
pub use middleware::RetryMiddleware;
pub use middleware::TimingMiddleware;
pub use connection::ConnectionError;
pub use connection::ConnectionOptions;
pub use connection::ConnectionString;
pub use connection::DatabaseConfig;
pub use connection::Driver;
pub use connection::EnvExpander;
pub use connection::MultiDatabaseConfig;
pub use connection::PoolConfig;
pub use connection::PoolOptions;
pub use connection::SslConfig;
pub use connection::SslMode;
pub use cte::Cte;
pub use cte::CteBuilder;
pub use cte::CycleClause;
pub use cte::Materialized;
pub use cte::SearchClause;
pub use cte::SearchMethod;
pub use cte::WithClause;
pub use cte::WithQueryBuilder;
pub use advanced::BulkOperation;
pub use advanced::DistinctOn;
pub use advanced::LateralJoin;
pub use advanced::LateralJoinBuilder;
pub use advanced::LateralJoinType;
pub use advanced::LockStrength;
pub use advanced::LockWait;
pub use advanced::ReturnOperation;
pub use advanced::Returning;
pub use advanced::ReturningColumn;
pub use advanced::RowLock;
pub use advanced::RowLockBuilder;
pub use advanced::SampleMethod;
pub use advanced::SampleSize;
pub use advanced::TableSample;
pub use advanced::TableSampleBuilder;
pub use data::BatchCreate;
pub use data::ConnectData;
pub use data::CreateData;
pub use data::DataBuilder;
pub use data::FieldValue;
pub use data::IntoData;
pub use data::UpdateData;
pub use introspection::CheckConstraint;
pub use introspection::ColumnInfo;
pub use introspection::DatabaseSchema;
pub use introspection::EnumInfo;
pub use introspection::ForeignKeyInfo;
pub use introspection::IndexColumn;
pub use introspection::IndexInfo;
pub use introspection::NormalizedType;
pub use introspection::ReferentialAction;
pub use introspection::SequenceInfo;
pub use introspection::TableInfo;
pub use introspection::UniqueConstraint;
pub use introspection::ViewInfo;
pub use introspection::generate_prax_schema;
pub use introspection::normalize_type;
pub use tenant::DynamicResolver;
pub use tenant::IsolationStrategy;
pub use tenant::RowLevelConfig;
pub use tenant::SchemaConfig;
pub use tenant::StaticResolver;
pub use tenant::TenantConfig;
pub use tenant::TenantConfigBuilder;
pub use tenant::TenantContext;
pub use tenant::TenantId;
pub use tenant::TenantInfo;
pub use tenant::TenantMiddleware;
pub use tenant::TenantResolver;
pub use intern::clear_interned;
pub use intern::fields;
pub use intern::intern;
pub use intern::intern_cow;
pub use intern::interned_count;
pub use pool::FilterBuilder;
pub use pool::FilterPool;
pub use pool::IntoPooledValue;
pub use pool::PooledFilter;
pub use pool::PooledValue;
pub use sql::AdvancedQueryCapacity;
pub use sql::CachedSql;
pub use sql::DatabaseType;
pub use sql::FastSqlBuilder;
pub use sql::LazySql;
pub use sql::QueryCapacity;
pub use sql::SqlBuilder;
pub use sql::SqlTemplateCache as SqlCache;
pub use sql::global_sql_cache;
pub use sql::keywords;
pub use sql::templates;
pub use builder::BuilderPool;
pub use builder::ColumnList;
pub use builder::ColumnNameList;
pub use builder::CowColumnList;
pub use builder::CowIdentifier;
pub use builder::ExprList;
pub use builder::Identifier;
pub use builder::OptimizedWindowSpec;
pub use builder::OrderByList;
pub use builder::PartitionByList;
pub use builder::ReusableBuilder;
pub use builder::WindowFrame;
pub use builder::FrameBound as BuilderFrameBound;
pub use builder::FrameType as BuilderFrameType;
pub use db_optimize::BatchConfig;
pub use db_optimize::CachedStatement;
pub use db_optimize::IndexHint;
pub use db_optimize::IndexHintType;
pub use db_optimize::JoinHint;
pub use db_optimize::JoinMethod;
pub use db_optimize::MongoPipelineBuilder;
pub use db_optimize::PipelineStage;
pub use db_optimize::PreparedStatementCache;
pub use db_optimize::PreparedStatementStats;
pub use db_optimize::QueryHints;
pub use db_optimize::global_statement_cache;
pub use zero_copy::CteRef;
pub use zero_copy::FrameBoundRef;
pub use zero_copy::FrameRef;
pub use zero_copy::FrameTypeRef;
pub use zero_copy::JsonPathRef;
pub use zero_copy::PathSegmentRef;
pub use zero_copy::WindowSpecRef;
pub use zero_copy::WithClauseRef;
pub use cache::CacheStats;
pub use cache::CachedQuery;
pub use cache::ExecutionPlan;
pub use cache::ExecutionPlanCache;
pub use cache::PlanHint;
pub use cache::QueryCache;
pub use cache::QueryHash;
pub use cache::QueryKey;
pub use cache::SqlTemplate;
pub use cache::SqlTemplateCache;
pub use cache::get_global_template;
pub use cache::global_template_cache;
pub use cache::patterns as cache_patterns;
pub use cache::precompute_query_hash;
pub use cache::register_global_template;
pub use batch::Batch;
pub use batch::BatchBuilder;
pub use batch::BatchOperation;
pub use batch::BatchResult;
pub use batch::OperationResult;
pub use batch::Pipeline;
pub use batch::PipelineBuilder;
pub use batch::PipelineQuery;
pub use batch::PipelineResult;
pub use batch::QueryResult as PipelineQueryResult;
pub use row::FromColumn;
pub use row::FromRow;
pub use row::FromRowRef;
pub use row::RowData;
pub use row::RowError;
pub use row::RowRef;
pub use row::RowRefIter;
pub use lazy::Lazy;
pub use lazy::LazyRelation;
pub use lazy::ManyToOneLoader;
pub use lazy::OneToManyLoader;
pub use static_filter::CompactValue;
pub use static_filter::StaticFilter;
pub use static_filter::and2;
pub use static_filter::and3;
pub use static_filter::and4;
pub use static_filter::and5;
pub use static_filter::contains;
pub use static_filter::ends_with;
pub use static_filter::eq;
pub use static_filter::fields as static_fields;
pub use static_filter::gt;
pub use static_filter::gte;
pub use static_filter::in_list;
pub use static_filter::is_not_null;
pub use static_filter::is_null;
pub use static_filter::lt;
pub use static_filter::lte;
pub use static_filter::ne;
pub use static_filter::not;
pub use static_filter::not_in_list;
pub use static_filter::or2;
pub use static_filter::or3;
pub use static_filter::or4;
pub use static_filter::or5;
pub use static_filter::starts_with;
pub use typed_filter::And;
pub use typed_filter::AndN;
pub use typed_filter::Contains;
pub use typed_filter::DirectSql;
pub use typed_filter::EndsWith;
pub use typed_filter::Eq;
pub use typed_filter::Gt;
pub use typed_filter::Gte;
pub use typed_filter::InI64;
pub use typed_filter::InI64Slice;
pub use typed_filter::InStr;
pub use typed_filter::InStrSlice;
pub use typed_filter::IsNotNull;
pub use typed_filter::IsNull;
pub use typed_filter::LazyFilter;
pub use typed_filter::Lt;
pub use typed_filter::Lte;
pub use typed_filter::Maybe;
pub use typed_filter::Ne;
pub use typed_filter::Not as TypedNot;
pub use typed_filter::NotInI64Slice;
pub use typed_filter::Or;
pub use typed_filter::OrN;
pub use typed_filter::StartsWith;
pub use typed_filter::TypedFilter;
pub use typed_filter::and_n;
pub use typed_filter::eq as typed_eq;
pub use typed_filter::gt as typed_gt;
pub use typed_filter::gte as typed_gte;
pub use typed_filter::in_i64 as typed_in_i64;
pub use typed_filter::in_i64_slice;
pub use typed_filter::in_str as typed_in_str;
pub use typed_filter::in_str_slice;
pub use typed_filter::is_not_null as typed_is_not_null;
pub use typed_filter::is_null as typed_is_null;
pub use typed_filter::lazy;
pub use typed_filter::lt as typed_lt;
pub use typed_filter::lte as typed_lte;
pub use typed_filter::ne as typed_ne;
pub use typed_filter::not_in_i64_slice;
pub use typed_filter::or_n;
pub use memory::BufferPool;
pub use memory::CompactFilter;
pub use memory::GLOBAL_BUFFER_POOL;
pub use memory::GLOBAL_STRING_POOL;
pub use memory::MemoryStats;
pub use memory::PoolStats;
pub use memory::PooledBuffer;
pub use memory::StringPool;
pub use memory::get_buffer;
pub use memory::intern as memory_intern;
pub use logging::get_log_format;
pub use logging::get_log_level;
pub use logging::init as init_logging;
pub use logging::init_debug;
pub use logging::init_with_level;
pub use logging::is_debug_enabled;
pub use replication::ConnectionRouter;
pub use replication::HealthStatus;
pub use replication::LagMeasurement;
pub use replication::LagMonitor;
pub use replication::ReadPreference;
pub use replication::ReplicaConfig;
pub use replication::ReplicaHealth;
pub use replication::ReplicaRole;
pub use replication::ReplicaSetBuilder;
pub use replication::ReplicaSetConfig;
pub use async_optimize::ConcurrencyConfig;
pub use async_optimize::ConcurrentExecutor;
pub use async_optimize::ExecutionStats;
pub use async_optimize::IntrospectionConfig;
pub use async_optimize::IntrospectionResult;
pub use async_optimize::PipelineConfig;
pub use async_optimize::PipelineError;
pub use async_optimize::PipelineResult as AsyncPipelineResult;
pub use async_optimize::QueryPipeline;
pub use async_optimize::TaskError;
pub use async_optimize::TaskResult;
pub use async_optimize::concurrent::execute_batch as async_execute_batch;
pub use async_optimize::concurrent::execute_chunked as async_execute_chunked;
pub use async_optimize::introspect::BatchIntrospector;
pub use async_optimize::introspect::ColumnMetadata;
pub use async_optimize::introspect::ConcurrentIntrospector;
pub use async_optimize::introspect::ForeignKeyMetadata;
pub use async_optimize::introspect::IndexMetadata;
pub use async_optimize::introspect::IntrospectionError;
pub use async_optimize::introspect::IntrospectionPhase;
pub use async_optimize::introspect::IntrospectorBuilder;
pub use async_optimize::introspect::TableMetadata;
pub use async_optimize::pipeline::BulkInsertPipeline;
pub use async_optimize::pipeline::BulkUpdatePipeline;
pub use async_optimize::pipeline::SimulatedExecutor;
pub use mem_optimize::GlobalInterner;
pub use mem_optimize::IdentifierCache;
pub use mem_optimize::InternedStr;
pub use mem_optimize::ScopedInterner;
pub use mem_optimize::arena::ArenaScope;
pub use mem_optimize::arena::ArenaStats;
pub use mem_optimize::arena::QueryArena;
pub use mem_optimize::arena::ScopedFilter;
pub use mem_optimize::arena::ScopedQuery;
pub use mem_optimize::arena::ScopedValue;
pub use mem_optimize::interning::intern as global_intern;
pub use mem_optimize::interning::intern_component;
pub use mem_optimize::interning::intern_qualified;
pub use mem_optimize::interning::get_interned;
pub use mem_optimize::lazy::LazyColumn;
pub use mem_optimize::lazy::LazyForeignKey;
pub use mem_optimize::lazy::LazyIndex;
pub use mem_optimize::lazy::LazySchema;
pub use mem_optimize::lazy::LazySchemaStats;
pub use mem_optimize::lazy::LazyTable;
pub use profiling::AllocationRecord;
pub use profiling::AllocationStats;
pub use profiling::AllocationTracker;
pub use profiling::HeapProfiler;
pub use profiling::HeapReport;
pub use profiling::HeapStats;
pub use profiling::LeakDetector;
pub use profiling::LeakReport;
pub use profiling::LeakSeverity;
pub use profiling::MemoryProfiler;
pub use profiling::MemoryReport;
pub use profiling::MemorySnapshot;
pub use profiling::PotentialLeak;
pub use profiling::SnapshotDiff;
pub use profiling::TrackedAllocator;
pub use profiling::enable_profiling;
pub use profiling::disable_profiling;
pub use profiling::is_profiling_enabled;
pub use profiling::with_profiling;
pub use smallvec;

Modules§

advanced
Advanced query features.
async_optimize
Async optimizations for high-performance database operations.
batch
Batch query execution for combining multiple operations.
builder
Optimized builder patterns for query construction.
cache
Query caching and prepared statement management.
connection
Connection string parsing and multi-database configuration.
cte
Common Table Expressions (CTEs) support.
data
Ergonomic data creation utilities.
data_cache
High-performance data caching layer for Prax ORM.
db_optimize
Database-specific optimizations.
error
Comprehensive error types for query operations with actionable messages.
extension
Database extensions and plugins support.
filter
Filter types for building WHERE clauses.
intern
String interning for efficient field name storage.
introspection
Database introspection and schema generation.
json
JSON and document operations support.
lazy
Lazy loading utilities for relations.
logging
Logging infrastructure for Prax ORM.
macros
Compile-time filter construction macros.
mem_optimize
Advanced memory optimizations for prax-query.
memory
Memory optimization utilities for prax-query.
middleware
Middleware system for query interception.
nested
Nested write operations for managing relations in a single mutation.
operations
Query operations for the fluent API.
pagination
Pagination types for query results.
partition
Table partitioning and sharding support.
pool
Arena-based filter pool for efficient nested filter construction.
prelude
Prelude module for convenient imports.
procedure
Stored procedure and function call support.
profiling
Memory profiling and leak detection utilities.
query
Query builder entry point.
raw
Raw SQL query execution with type-safe parameter interpolation.
relations
Relation loading support for eager and lazy loading.
replication
Replication and high availability support.
row
Zero-copy row deserialization traits and utilities.
search
Full-text search support across database backends.
security
Security and access control support.
sequence
Database sequence definitions and operations.
sql
SQL generation utilities.
static_filter
Static filter construction for zero-allocation filters.
tenant
High-performance multi-tenant support for Prax.
traits
Core traits for the query builder.
transaction
Transaction support with async closures and savepoints.
trigger
Database trigger definitions and management.
typed_filter
Type-level filter composition for zero-cost filter abstractions.
types
Common types used in query building.
upsert
Upsert and conflict resolution support.
window
Window functions support.
zero_copy
Zero-copy types for performance-critical operations.

Macros§

and_filter
Combine filters with AND.
connect
Macro for creating connection data.
data
Macro for concise data creation.
decrement
Macro for decrement operations.
filter
Create a filter expression with minimal allocations.
impl_from_row
Macro to implement FromRow for simple structs.
increment
Macro for increment operations.
not_filter
Negate a filter.
or_filter
Combine filters with OR.
prax_debug
Macro for conditional debug logging.
prax_trace
Macro for conditional trace logging.
query_error
Helper for creating errors with context.
raw_query
A macro for creating raw SQL queries with inline parameter binding.