use std::fmt;
use super::builders::{GraphQueryBuilder, PathQueryBuilder, TableQueryBuilder};
use crate::catalog::CollectionModel;
pub use crate::storage::engine::distance::DistanceMetric;
pub use crate::storage::engine::vector_metadata::MetadataFilter;
pub use crate::storage::queue::QueueMode;
use crate::storage::schema::{SqlTypeName, Value};
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum QueryExpr {
Table(TableQuery),
Graph(GraphQuery),
Join(JoinQuery),
Path(PathQuery),
Vector(VectorQuery),
Hybrid(HybridQuery),
Insert(InsertQuery),
Update(UpdateQuery),
Delete(DeleteQuery),
CreateTable(CreateTableQuery),
DropTable(DropTableQuery),
DropGraph(DropGraphQuery),
DropVector(DropVectorQuery),
DropDocument(DropDocumentQuery),
DropKv(DropKvQuery),
DropCollection(DropCollectionQuery),
Truncate(TruncateQuery),
AlterTable(AlterTableQuery),
GraphCommand(GraphCommand),
SearchCommand(SearchCommand),
Ask(AskQuery),
CreateIndex(CreateIndexQuery),
DropIndex(DropIndexQuery),
ProbabilisticCommand(ProbabilisticCommand),
CreateTimeSeries(CreateTimeSeriesQuery),
DropTimeSeries(DropTimeSeriesQuery),
CreateQueue(CreateQueueQuery),
AlterQueue(AlterQueueQuery),
DropQueue(DropQueueQuery),
QueueSelect(QueueSelectQuery),
QueueCommand(QueueCommand),
KvCommand(KvCommand),
ConfigCommand(ConfigCommand),
CreateTree(CreateTreeQuery),
DropTree(DropTreeQuery),
TreeCommand(TreeCommand),
SetConfig { key: String, value: Value },
ShowConfig { prefix: Option<String> },
SetSecret { key: String, value: Value },
DeleteSecret { key: String },
ShowSecrets { prefix: Option<String> },
SetTenant(Option<String>),
ShowTenant,
ExplainAlter(ExplainAlterQuery),
CreateMigration(CreateMigrationQuery),
ApplyMigration(ApplyMigrationQuery),
RollbackMigration(RollbackMigrationQuery),
ExplainMigration(ExplainMigrationQuery),
EventsBackfill(EventsBackfillQuery),
EventsBackfillStatus { collection: String },
TransactionControl(TxnControl),
MaintenanceCommand(MaintenanceCommand),
CreateSchema(CreateSchemaQuery),
DropSchema(DropSchemaQuery),
CreateSequence(CreateSequenceQuery),
DropSequence(DropSequenceQuery),
CopyFrom(CopyFromQuery),
CreateView(CreateViewQuery),
DropView(DropViewQuery),
RefreshMaterializedView(RefreshMaterializedViewQuery),
CreatePolicy(CreatePolicyQuery),
DropPolicy(DropPolicyQuery),
CreateServer(CreateServerQuery),
DropServer(DropServerQuery),
CreateForeignTable(CreateForeignTableQuery),
DropForeignTable(DropForeignTableQuery),
Grant(GrantStmt),
Revoke(RevokeStmt),
AlterUser(AlterUserStmt),
CreateIamPolicy { id: String, json: String },
DropIamPolicy { id: String },
AttachPolicy {
policy_id: String,
principal: PolicyPrincipalRef,
},
DetachPolicy {
policy_id: String,
principal: PolicyPrincipalRef,
},
ShowPolicies { filter: Option<PolicyPrincipalRef> },
ShowEffectivePermissions {
user: PolicyUserRef,
resource: Option<PolicyResourceRef>,
},
SimulatePolicy {
user: PolicyUserRef,
action: String,
resource: PolicyResourceRef,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PolicyUserRef {
pub tenant: Option<String>,
pub username: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PolicyResourceRef {
pub kind: String,
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PolicyPrincipalRef {
User(PolicyUserRef),
Group(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GrantObjectKind {
Table,
Schema,
Database,
Function,
}
#[derive(Debug, Clone)]
pub struct GrantObject {
pub schema: Option<String>,
pub name: String,
}
#[derive(Debug, Clone)]
pub enum GrantPrincipalRef {
User {
tenant: Option<String>,
name: String,
},
Public,
Group(String),
}
#[derive(Debug, Clone)]
pub struct GrantStmt {
pub actions: Vec<String>,
pub columns: Option<Vec<String>>,
pub object_kind: GrantObjectKind,
pub objects: Vec<GrantObject>,
pub principals: Vec<GrantPrincipalRef>,
pub with_grant_option: bool,
pub all: bool,
}
#[derive(Debug, Clone)]
pub struct RevokeStmt {
pub actions: Vec<String>,
pub columns: Option<Vec<String>>,
pub object_kind: GrantObjectKind,
pub objects: Vec<GrantObject>,
pub principals: Vec<GrantPrincipalRef>,
pub grant_option_for: bool,
pub all: bool,
}
#[derive(Debug, Clone)]
pub enum AlterUserAttribute {
ValidUntil(String),
ConnectionLimit(i64),
Enable,
Disable,
SetSearchPath(String),
AddGroup(String),
DropGroup(String),
Password(String),
}
#[derive(Debug, Clone)]
pub struct AlterUserStmt {
pub tenant: Option<String>,
pub username: String,
pub attributes: Vec<AlterUserAttribute>,
}
#[derive(Debug, Clone)]
pub struct CreateServerQuery {
pub name: String,
pub wrapper: String,
pub options: Vec<(String, String)>,
pub if_not_exists: bool,
}
#[derive(Debug, Clone)]
pub struct DropServerQuery {
pub name: String,
pub if_exists: bool,
pub cascade: bool,
}
#[derive(Debug, Clone)]
pub struct CreateForeignTableQuery {
pub name: String,
pub server: String,
pub columns: Vec<ForeignColumnDef>,
pub options: Vec<(String, String)>,
pub if_not_exists: bool,
}
#[derive(Debug, Clone)]
pub struct ForeignColumnDef {
pub name: String,
pub data_type: String,
pub not_null: bool,
}
#[derive(Debug, Clone)]
pub struct DropForeignTableQuery {
pub name: String,
pub if_exists: bool,
}
#[derive(Debug, Clone)]
pub struct CreatePolicyQuery {
pub name: String,
pub table: String,
pub action: Option<PolicyAction>,
pub role: Option<String>,
pub using: Box<Filter>,
pub target_kind: PolicyTargetKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PolicyTargetKind {
Table,
Nodes,
Edges,
Vectors,
Messages,
Points,
Documents,
}
impl PolicyTargetKind {
pub fn as_ident(&self) -> &'static str {
match self {
Self::Table => "table",
Self::Nodes => "nodes",
Self::Edges => "edges",
Self::Vectors => "vectors",
Self::Messages => "messages",
Self::Points => "points",
Self::Documents => "documents",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PolicyAction {
Select,
Insert,
Update,
Delete,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DropPolicyQuery {
pub name: String,
pub table: String,
pub if_exists: bool,
}
#[derive(Debug, Clone)]
pub struct CreateViewQuery {
pub name: String,
pub query: Box<QueryExpr>,
pub materialized: bool,
pub if_not_exists: bool,
pub or_replace: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DropViewQuery {
pub name: String,
pub materialized: bool,
pub if_exists: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefreshMaterializedViewQuery {
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CopyFromQuery {
pub table: String,
pub path: String,
pub format: CopyFormat,
pub delimiter: Option<char>,
pub has_header: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CopyFormat {
Csv,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateSchemaQuery {
pub name: String,
pub if_not_exists: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DropSchemaQuery {
pub name: String,
pub if_exists: bool,
pub cascade: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateSequenceQuery {
pub name: String,
pub if_not_exists: bool,
pub start: i64,
pub increment: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DropSequenceQuery {
pub name: String,
pub if_exists: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TxnControl {
Begin,
Commit,
Rollback,
Savepoint(String),
ReleaseSavepoint(String),
RollbackToSavepoint(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MaintenanceCommand {
Vacuum { target: Option<String>, full: bool },
Analyze { target: Option<String> },
}
#[derive(Debug, Clone)]
pub struct ExplainAlterQuery {
pub target: CreateTableQuery,
pub format: ExplainFormat,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ExplainFormat {
#[default]
Sql,
Json,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CreateMigrationQuery {
pub name: String,
pub body: String,
pub depends_on: Vec<String>,
pub batch_size: Option<u64>,
pub no_rollback: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ApplyMigrationQuery {
pub target: ApplyMigrationTarget,
pub for_tenant: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ApplyMigrationTarget {
Named(String),
All,
}
#[derive(Debug, Clone, PartialEq)]
pub struct RollbackMigrationQuery {
pub name: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ExplainMigrationQuery {
pub name: String,
}
#[derive(Debug, Clone)]
pub enum ProbabilisticCommand {
CreateHll {
name: String,
if_not_exists: bool,
},
HllAdd {
name: String,
elements: Vec<String>,
},
HllCount {
names: Vec<String>,
},
HllMerge {
dest: String,
sources: Vec<String>,
},
HllInfo {
name: String,
},
DropHll {
name: String,
if_exists: bool,
},
CreateSketch {
name: String,
width: usize,
depth: usize,
if_not_exists: bool,
},
SketchAdd {
name: String,
element: String,
count: u64,
},
SketchCount {
name: String,
element: String,
},
SketchMerge {
dest: String,
sources: Vec<String>,
},
SketchInfo {
name: String,
},
DropSketch {
name: String,
if_exists: bool,
},
CreateFilter {
name: String,
capacity: usize,
if_not_exists: bool,
},
FilterAdd {
name: String,
element: String,
},
FilterCheck {
name: String,
element: String,
},
FilterDelete {
name: String,
element: String,
},
FilterCount {
name: String,
},
FilterInfo {
name: String,
},
DropFilter {
name: String,
if_exists: bool,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IndexMethod {
BTree,
Hash,
Bitmap,
RTree,
}
impl fmt::Display for IndexMethod {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::BTree => write!(f, "BTREE"),
Self::Hash => write!(f, "HASH"),
Self::Bitmap => write!(f, "BITMAP"),
Self::RTree => write!(f, "RTREE"),
}
}
}
#[derive(Debug, Clone)]
pub struct CreateIndexQuery {
pub name: String,
pub table: String,
pub columns: Vec<String>,
pub method: IndexMethod,
pub unique: bool,
pub if_not_exists: bool,
}
#[derive(Debug, Clone)]
pub struct DropIndexQuery {
pub name: String,
pub table: String,
pub if_exists: bool,
}
#[derive(Debug, Clone)]
pub struct AskQuery {
pub question: String,
pub provider: Option<String>,
pub model: Option<String>,
pub depth: Option<usize>,
pub limit: Option<usize>,
pub collection: Option<String>,
}
impl QueryExpr {
pub fn table(name: &str) -> TableQueryBuilder {
TableQueryBuilder::new(name)
}
pub fn graph() -> GraphQueryBuilder {
GraphQueryBuilder::new()
}
pub fn path(from: NodeSelector, to: NodeSelector) -> PathQueryBuilder {
PathQueryBuilder::new(from, to)
}
}
#[derive(Debug, Clone)]
pub struct TableQuery {
pub table: String,
pub source: Option<TableSource>,
pub alias: Option<String>,
pub select_items: Vec<SelectItem>,
pub columns: Vec<Projection>,
pub where_expr: Option<super::Expr>,
pub filter: Option<Filter>,
pub group_by_exprs: Vec<super::Expr>,
pub group_by: Vec<String>,
pub having_expr: Option<super::Expr>,
pub having: Option<Filter>,
pub order_by: Vec<OrderByClause>,
pub limit: Option<u64>,
pub offset: Option<u64>,
pub expand: Option<ExpandOptions>,
pub as_of: Option<AsOfClause>,
}
#[derive(Debug, Clone)]
pub enum AsOfClause {
Commit(String),
Branch(String),
Tag(String),
TimestampMs(i64),
Snapshot(u64),
}
#[derive(Debug, Clone)]
pub enum TableSource {
Name(String),
Subquery(Box<QueryExpr>),
}
#[derive(Debug, Clone, Default)]
pub struct ExpandOptions {
pub graph: bool,
pub graph_depth: usize,
pub cross_refs: bool,
pub index_hint: Option<crate::storage::query::planner::optimizer::IndexHint>,
}
impl TableQuery {
pub fn new(table: &str) -> Self {
Self {
table: table.to_string(),
source: None,
alias: None,
select_items: Vec::new(),
columns: Vec::new(),
where_expr: None,
filter: None,
group_by_exprs: Vec::new(),
group_by: Vec::new(),
having_expr: None,
having: None,
order_by: Vec::new(),
limit: None,
offset: None,
expand: None,
as_of: None,
}
}
pub fn from_subquery(subquery: QueryExpr, alias: Option<String>) -> Self {
let sentinel = match &alias {
Some(a) => format!("__subq_{a}"),
None => "__subq_anon".to_string(),
};
Self {
table: sentinel,
source: Some(TableSource::Subquery(Box::new(subquery))),
alias,
select_items: Vec::new(),
columns: Vec::new(),
where_expr: None,
filter: None,
group_by_exprs: Vec::new(),
group_by: Vec::new(),
having_expr: None,
having: None,
order_by: Vec::new(),
limit: None,
offset: None,
expand: None,
as_of: None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum SelectItem {
Wildcard,
Expr {
expr: super::Expr,
alias: Option<String>,
},
}
#[derive(Debug, Clone)]
pub struct GraphQuery {
pub alias: Option<String>,
pub pattern: GraphPattern,
pub filter: Option<Filter>,
pub return_: Vec<Projection>,
}
impl GraphQuery {
pub fn new(pattern: GraphPattern) -> Self {
Self {
alias: None,
pattern,
filter: None,
return_: Vec::new(),
}
}
pub fn alias(mut self, alias: &str) -> Self {
self.alias = Some(alias.to_string());
self
}
}
#[derive(Debug, Clone, Default)]
pub struct GraphPattern {
pub nodes: Vec<NodePattern>,
pub edges: Vec<EdgePattern>,
}
impl GraphPattern {
pub fn new() -> Self {
Self::default()
}
pub fn node(mut self, pattern: NodePattern) -> Self {
self.nodes.push(pattern);
self
}
pub fn edge(mut self, pattern: EdgePattern) -> Self {
self.edges.push(pattern);
self
}
}
#[derive(Debug, Clone)]
pub struct NodePattern {
pub alias: String,
pub node_label: Option<String>,
pub properties: Vec<PropertyFilter>,
}
impl NodePattern {
pub fn new(alias: &str) -> Self {
Self {
alias: alias.to_string(),
node_label: None,
properties: Vec::new(),
}
}
pub fn of_label(mut self, label: impl Into<String>) -> Self {
self.node_label = Some(label.into());
self
}
pub fn with_property(mut self, name: &str, op: CompareOp, value: Value) -> Self {
self.properties.push(PropertyFilter {
name: name.to_string(),
op,
value,
});
self
}
}
#[derive(Debug, Clone)]
pub struct EdgePattern {
pub alias: Option<String>,
pub from: String,
pub to: String,
pub edge_label: Option<String>,
pub direction: EdgeDirection,
pub min_hops: u32,
pub max_hops: u32,
}
impl EdgePattern {
pub fn new(from: &str, to: &str) -> Self {
Self {
alias: None,
from: from.to_string(),
to: to.to_string(),
edge_label: None,
direction: EdgeDirection::Outgoing,
min_hops: 1,
max_hops: 1,
}
}
pub fn of_label(mut self, label: impl Into<String>) -> Self {
self.edge_label = Some(label.into());
self
}
pub fn direction(mut self, dir: EdgeDirection) -> Self {
self.direction = dir;
self
}
pub fn hops(mut self, min: u32, max: u32) -> Self {
self.min_hops = min;
self.max_hops = max;
self
}
pub fn alias(mut self, alias: &str) -> Self {
self.alias = Some(alias.to_string());
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EdgeDirection {
Outgoing,
Incoming,
Both,
}
#[derive(Debug, Clone)]
pub struct PropertyFilter {
pub name: String,
pub op: CompareOp,
pub value: Value,
}
#[derive(Debug, Clone)]
pub struct JoinQuery {
pub left: Box<QueryExpr>,
pub right: Box<QueryExpr>,
pub join_type: JoinType,
pub on: JoinCondition,
pub filter: Option<Filter>,
pub order_by: Vec<OrderByClause>,
pub limit: Option<u64>,
pub offset: Option<u64>,
pub return_items: Vec<SelectItem>,
pub return_: Vec<Projection>,
}
impl JoinQuery {
pub fn new(left: QueryExpr, right: QueryExpr, on: JoinCondition) -> Self {
Self {
left: Box::new(left),
right: Box::new(right),
join_type: JoinType::Inner,
on,
filter: None,
order_by: Vec::new(),
limit: None,
offset: None,
return_items: Vec::new(),
return_: Vec::new(),
}
}
pub fn join_type(mut self, jt: JoinType) -> Self {
self.join_type = jt;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JoinType {
Inner,
LeftOuter,
RightOuter,
FullOuter,
Cross,
}
#[derive(Debug, Clone)]
pub struct JoinCondition {
pub left_field: FieldRef,
pub right_field: FieldRef,
}
impl JoinCondition {
pub fn new(left: FieldRef, right: FieldRef) -> Self {
Self {
left_field: left,
right_field: right,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FieldRef {
TableColumn { table: String, column: String },
NodeProperty { alias: String, property: String },
EdgeProperty { alias: String, property: String },
NodeId { alias: String },
}
impl FieldRef {
pub fn column(table: &str, column: &str) -> Self {
Self::TableColumn {
table: table.to_string(),
column: column.to_string(),
}
}
pub fn node_prop(alias: &str, property: &str) -> Self {
Self::NodeProperty {
alias: alias.to_string(),
property: property.to_string(),
}
}
pub fn node_id(alias: &str) -> Self {
Self::NodeId {
alias: alias.to_string(),
}
}
pub fn edge_prop(alias: &str, property: &str) -> Self {
Self::EdgeProperty {
alias: alias.to_string(),
property: property.to_string(),
}
}
}
#[derive(Debug, Clone)]
pub struct PathQuery {
pub alias: Option<String>,
pub from: NodeSelector,
pub to: NodeSelector,
pub via: Vec<String>,
pub max_length: u32,
pub filter: Option<Filter>,
pub return_: Vec<Projection>,
}
impl PathQuery {
pub fn new(from: NodeSelector, to: NodeSelector) -> Self {
Self {
alias: None,
from,
to,
via: Vec::new(),
max_length: 10,
filter: None,
return_: Vec::new(),
}
}
pub fn alias(mut self, alias: &str) -> Self {
self.alias = Some(alias.to_string());
self
}
pub fn via_label(mut self, label: impl Into<String>) -> Self {
self.via.push(label.into());
self
}
}
#[derive(Debug, Clone)]
pub enum NodeSelector {
ById(String),
ByType {
node_label: String,
filter: Option<PropertyFilter>,
},
ByRow { table: String, row_id: u64 },
}
impl NodeSelector {
pub fn by_id(id: &str) -> Self {
Self::ById(id.to_string())
}
pub fn by_label(label: impl Into<String>) -> Self {
Self::ByType {
node_label: label.into(),
filter: None,
}
}
pub fn by_row(table: &str, row_id: u64) -> Self {
Self::ByRow {
table: table.to_string(),
row_id,
}
}
}
#[derive(Debug, Clone)]
pub struct VectorQuery {
pub alias: Option<String>,
pub collection: String,
pub query_vector: VectorSource,
pub k: usize,
pub filter: Option<MetadataFilter>,
pub metric: Option<DistanceMetric>,
pub include_vectors: bool,
pub include_metadata: bool,
pub threshold: Option<f32>,
}
impl VectorQuery {
pub fn new(collection: &str, query: VectorSource) -> Self {
Self {
alias: None,
collection: collection.to_string(),
query_vector: query,
k: 10,
filter: None,
metric: None,
include_vectors: false,
include_metadata: true,
threshold: None,
}
}
pub fn limit(mut self, k: usize) -> Self {
self.k = k;
self
}
pub fn with_filter(mut self, filter: MetadataFilter) -> Self {
self.filter = Some(filter);
self
}
pub fn with_vectors(mut self) -> Self {
self.include_vectors = true;
self
}
pub fn min_similarity(mut self, threshold: f32) -> Self {
self.threshold = Some(threshold);
self
}
pub fn alias(mut self, alias: &str) -> Self {
self.alias = Some(alias.to_string());
self
}
}
#[derive(Debug, Clone)]
pub enum VectorSource {
Literal(Vec<f32>),
Text(String),
Reference { collection: String, vector_id: u64 },
Subquery(Box<QueryExpr>),
}
impl VectorSource {
pub fn literal(values: Vec<f32>) -> Self {
Self::Literal(values)
}
pub fn text(s: &str) -> Self {
Self::Text(s.to_string())
}
pub fn reference(collection: &str, vector_id: u64) -> Self {
Self::Reference {
collection: collection.to_string(),
vector_id,
}
}
}
#[derive(Debug, Clone)]
pub struct HybridQuery {
pub alias: Option<String>,
pub structured: Box<QueryExpr>,
pub vector: VectorQuery,
pub fusion: FusionStrategy,
pub limit: Option<usize>,
}
impl HybridQuery {
pub fn new(structured: QueryExpr, vector: VectorQuery) -> Self {
Self {
alias: None,
structured: Box::new(structured),
vector,
fusion: FusionStrategy::Rerank { weight: 0.5 },
limit: None,
}
}
pub fn with_fusion(mut self, fusion: FusionStrategy) -> Self {
self.fusion = fusion;
self
}
pub fn limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
pub fn alias(mut self, alias: &str) -> Self {
self.alias = Some(alias.to_string());
self
}
}
#[derive(Debug, Clone)]
pub enum FusionStrategy {
Rerank { weight: f32 },
FilterThenSearch,
SearchThenFilter,
RRF { k: u32 },
Intersection,
Union {
structured_weight: f32,
vector_weight: f32,
},
}
impl Default for FusionStrategy {
fn default() -> Self {
Self::Rerank { weight: 0.5 }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum InsertEntityType {
#[default]
Row,
Node,
Edge,
Vector,
Document,
Kv,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ReturningItem {
All,
Column(String),
}
#[derive(Debug, Clone)]
pub struct InsertQuery {
pub table: String,
pub entity_type: InsertEntityType,
pub columns: Vec<String>,
pub value_exprs: Vec<Vec<super::Expr>>,
pub values: Vec<Vec<Value>>,
pub returning: Option<Vec<ReturningItem>>,
pub ttl_ms: Option<u64>,
pub expires_at_ms: Option<u64>,
pub with_metadata: Vec<(String, Value)>,
pub auto_embed: Option<AutoEmbedConfig>,
pub suppress_events: bool,
}
#[derive(Debug, Clone)]
pub struct AutoEmbedConfig {
pub fields: Vec<String>,
pub provider: String,
pub model: Option<String>,
}
#[derive(Debug, Clone)]
pub struct EventsBackfillQuery {
pub collection: String,
pub where_filter: Option<String>,
pub target_queue: String,
pub limit: Option<u64>,
}
#[derive(Debug, Clone)]
pub struct UpdateQuery {
pub table: String,
pub assignment_exprs: Vec<(String, super::Expr)>,
pub assignments: Vec<(String, Value)>,
pub where_expr: Option<super::Expr>,
pub filter: Option<Filter>,
pub ttl_ms: Option<u64>,
pub expires_at_ms: Option<u64>,
pub with_metadata: Vec<(String, Value)>,
pub returning: Option<Vec<ReturningItem>>,
pub limit: Option<u64>,
pub suppress_events: bool,
}
#[derive(Debug, Clone)]
pub struct DeleteQuery {
pub table: String,
pub where_expr: Option<super::Expr>,
pub filter: Option<Filter>,
pub returning: Option<Vec<ReturningItem>>,
pub suppress_events: bool,
}
#[derive(Debug, Clone)]
pub struct CreateTableQuery {
pub collection_model: CollectionModel,
pub name: String,
pub columns: Vec<CreateColumnDef>,
pub if_not_exists: bool,
pub default_ttl_ms: Option<u64>,
pub context_index_fields: Vec<String>,
pub context_index_enabled: bool,
pub timestamps: bool,
pub partition_by: Option<PartitionSpec>,
pub tenant_by: Option<String>,
pub append_only: bool,
pub subscriptions: Vec<crate::catalog::SubscriptionDescriptor>,
pub vault_own_master_key: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PartitionSpec {
pub kind: PartitionKind,
pub column: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PartitionKind {
Range,
List,
Hash,
}
#[derive(Debug, Clone)]
pub struct CreateColumnDef {
pub name: String,
pub data_type: String,
pub sql_type: SqlTypeName,
pub not_null: bool,
pub default: Option<String>,
pub compress: Option<u8>,
pub unique: bool,
pub primary_key: bool,
pub enum_variants: Vec<String>,
pub array_element: Option<String>,
pub decimal_precision: Option<u8>,
}
#[derive(Debug, Clone)]
pub struct DropTableQuery {
pub name: String,
pub if_exists: bool,
}
#[derive(Debug, Clone)]
pub struct DropGraphQuery {
pub name: String,
pub if_exists: bool,
}
#[derive(Debug, Clone)]
pub struct DropVectorQuery {
pub name: String,
pub if_exists: bool,
}
#[derive(Debug, Clone)]
pub struct DropDocumentQuery {
pub name: String,
pub if_exists: bool,
}
#[derive(Debug, Clone)]
pub struct DropKvQuery {
pub name: String,
pub if_exists: bool,
pub model: CollectionModel,
}
#[derive(Debug, Clone)]
pub struct DropCollectionQuery {
pub name: String,
pub if_exists: bool,
}
#[derive(Debug, Clone)]
pub struct TruncateQuery {
pub name: String,
pub model: Option<CollectionModel>,
pub if_exists: bool,
}
#[derive(Debug, Clone)]
pub struct AlterTableQuery {
pub name: String,
pub operations: Vec<AlterOperation>,
}
#[derive(Debug, Clone)]
pub enum AlterOperation {
AddColumn(CreateColumnDef),
DropColumn(String),
RenameColumn { from: String, to: String },
AttachPartition {
child: String,
bound: String,
},
DetachPartition { child: String },
EnableRowLevelSecurity,
DisableRowLevelSecurity,
EnableTenancy { column: String },
DisableTenancy,
SetAppendOnly(bool),
SetVersioned(bool),
EnableEvents(crate::catalog::SubscriptionDescriptor),
DisableEvents,
AddSubscription {
name: String,
descriptor: crate::catalog::SubscriptionDescriptor,
},
DropSubscription { name: String },
}
#[derive(Debug, Clone, PartialEq)]
pub enum Projection {
All,
Column(String),
Alias(String, String),
Function(String, Vec<Projection>),
Expression(Box<Filter>, Option<String>),
Field(FieldRef, Option<String>),
}
impl Projection {
pub fn from_field(field: FieldRef) -> Self {
Projection::Field(field, None)
}
pub fn column(name: &str) -> Self {
Projection::Column(name.to_string())
}
pub fn with_alias(column: &str, alias: &str) -> Self {
Projection::Alias(column.to_string(), alias.to_string())
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Filter {
Compare {
field: FieldRef,
op: CompareOp,
value: Value,
},
CompareFields {
left: FieldRef,
op: CompareOp,
right: FieldRef,
},
CompareExpr {
lhs: super::Expr,
op: CompareOp,
rhs: super::Expr,
},
And(Box<Filter>, Box<Filter>),
Or(Box<Filter>, Box<Filter>),
Not(Box<Filter>),
IsNull(FieldRef),
IsNotNull(FieldRef),
In { field: FieldRef, values: Vec<Value> },
Between {
field: FieldRef,
low: Value,
high: Value,
},
Like { field: FieldRef, pattern: String },
StartsWith { field: FieldRef, prefix: String },
EndsWith { field: FieldRef, suffix: String },
Contains { field: FieldRef, substring: String },
}
impl Filter {
pub fn compare(field: FieldRef, op: CompareOp, value: Value) -> Self {
Self::Compare { field, op, value }
}
pub fn and(self, other: Filter) -> Self {
Self::And(Box::new(self), Box::new(other))
}
pub fn or(self, other: Filter) -> Self {
Self::Or(Box::new(self), Box::new(other))
}
pub fn not(self) -> Self {
Self::Not(Box::new(self))
}
pub fn optimize(self) -> Self {
crate::storage::query::filter_optimizer::optimize(self)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompareOp {
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
}
impl fmt::Display for CompareOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CompareOp::Eq => write!(f, "="),
CompareOp::Ne => write!(f, "<>"),
CompareOp::Lt => write!(f, "<"),
CompareOp::Le => write!(f, "<="),
CompareOp::Gt => write!(f, ">"),
CompareOp::Ge => write!(f, ">="),
}
}
}
#[derive(Debug, Clone)]
pub struct OrderByClause {
pub field: FieldRef,
pub expr: Option<super::Expr>,
pub ascending: bool,
pub nulls_first: bool,
}
impl OrderByClause {
pub fn asc(field: FieldRef) -> Self {
Self {
field,
expr: None,
ascending: true,
nulls_first: false,
}
}
pub fn desc(field: FieldRef) -> Self {
Self {
field,
expr: None,
ascending: false,
nulls_first: true,
}
}
pub fn with_expr(mut self, expr: super::Expr) -> Self {
self.expr = Some(expr);
self
}
}
#[derive(Debug, Clone)]
pub enum GraphCommand {
Neighborhood {
source: String,
depth: u32,
direction: String,
},
ShortestPath {
source: String,
target: String,
algorithm: String,
direction: String,
},
Traverse {
source: String,
strategy: String,
depth: u32,
direction: String,
},
Centrality { algorithm: String },
Community {
algorithm: String,
max_iterations: u32,
},
Components { mode: String },
Cycles { max_length: u32 },
Clustering,
TopologicalSort,
Properties,
}
#[derive(Debug, Clone)]
pub enum SearchCommand {
Similar {
vector: Vec<f32>,
text: Option<String>,
provider: Option<String>,
collection: String,
limit: usize,
min_score: f32,
vector_param: Option<usize>,
limit_param: Option<usize>,
min_score_param: Option<usize>,
text_param: Option<usize>,
},
Text {
query: String,
collection: Option<String>,
limit: usize,
fuzzy: bool,
limit_param: Option<usize>,
},
Hybrid {
vector: Option<Vec<f32>>,
query: Option<String>,
collection: String,
limit: usize,
limit_param: Option<usize>,
},
Multimodal {
query: String,
collection: Option<String>,
limit: usize,
limit_param: Option<usize>,
},
Index {
index: String,
value: String,
collection: Option<String>,
limit: usize,
exact: bool,
limit_param: Option<usize>,
},
Context {
query: String,
field: Option<String>,
collection: Option<String>,
limit: usize,
depth: usize,
limit_param: Option<usize>,
},
SpatialRadius {
center_lat: f64,
center_lon: f64,
radius_km: f64,
collection: String,
column: String,
limit: usize,
limit_param: Option<usize>,
},
SpatialBbox {
min_lat: f64,
min_lon: f64,
max_lat: f64,
max_lon: f64,
collection: String,
column: String,
limit: usize,
limit_param: Option<usize>,
},
SpatialNearest {
lat: f64,
lon: f64,
k: usize,
collection: String,
column: String,
k_param: Option<usize>,
},
}
#[derive(Debug, Clone)]
pub struct CreateTimeSeriesQuery {
pub name: String,
pub retention_ms: Option<u64>,
pub chunk_size: Option<usize>,
pub downsample_policies: Vec<String>,
pub if_not_exists: bool,
pub hypertable: Option<HypertableDdl>,
}
#[derive(Debug, Clone)]
pub struct HypertableDdl {
pub time_column: String,
pub chunk_interval_ns: u64,
pub default_ttl_ns: Option<u64>,
}
#[derive(Debug, Clone)]
pub struct DropTimeSeriesQuery {
pub name: String,
pub if_exists: bool,
}
#[derive(Debug, Clone)]
pub struct CreateQueueQuery {
pub name: String,
pub mode: QueueMode,
pub priority: bool,
pub max_size: Option<usize>,
pub ttl_ms: Option<u64>,
pub dlq: Option<String>,
pub max_attempts: u32,
pub if_not_exists: bool,
}
#[derive(Debug, Clone)]
pub struct AlterQueueQuery {
pub name: String,
pub mode: QueueMode,
}
#[derive(Debug, Clone)]
pub struct DropQueueQuery {
pub name: String,
pub if_exists: bool,
}
#[derive(Debug, Clone)]
pub struct QueueSelectQuery {
pub queue: String,
pub columns: Vec<String>,
pub filter: Option<Filter>,
pub limit: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueueSide {
Left,
Right,
}
#[derive(Debug, Clone)]
pub enum QueueCommand {
Push {
queue: String,
value: Value,
side: QueueSide,
priority: Option<i32>,
},
Pop {
queue: String,
side: QueueSide,
count: usize,
},
Peek {
queue: String,
count: usize,
},
Len {
queue: String,
},
Purge {
queue: String,
},
GroupCreate {
queue: String,
group: String,
},
GroupRead {
queue: String,
group: Option<String>,
consumer: String,
count: usize,
},
Pending {
queue: String,
group: String,
},
Claim {
queue: String,
group: String,
consumer: String,
min_idle_ms: u64,
},
Ack {
queue: String,
group: String,
message_id: String,
},
Nack {
queue: String,
group: String,
message_id: String,
},
Move {
source: String,
destination: String,
filter: Option<Filter>,
limit: usize,
},
}
#[derive(Debug, Clone)]
pub struct TreeNodeSpec {
pub label: String,
pub node_type: Option<String>,
pub properties: Vec<(String, Value)>,
pub metadata: Vec<(String, Value)>,
pub max_children: Option<usize>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TreePosition {
First,
Last,
Index(usize),
}
#[derive(Debug, Clone)]
pub struct CreateTreeQuery {
pub collection: String,
pub name: String,
pub root: TreeNodeSpec,
pub default_max_children: usize,
pub if_not_exists: bool,
}
#[derive(Debug, Clone)]
pub struct DropTreeQuery {
pub collection: String,
pub name: String,
pub if_exists: bool,
}
#[derive(Debug, Clone)]
pub enum TreeCommand {
Insert {
collection: String,
tree_name: String,
parent_id: u64,
node: TreeNodeSpec,
position: TreePosition,
},
Move {
collection: String,
tree_name: String,
node_id: u64,
parent_id: u64,
position: TreePosition,
},
Delete {
collection: String,
tree_name: String,
node_id: u64,
},
Validate {
collection: String,
tree_name: String,
},
Rebalance {
collection: String,
tree_name: String,
dry_run: bool,
},
}
#[derive(Debug, Clone)]
pub enum KvCommand {
Put {
model: CollectionModel,
collection: String,
key: String,
value: Value,
ttl_ms: Option<u64>,
tags: Vec<String>,
if_not_exists: bool,
},
InvalidateTags {
collection: String,
tags: Vec<String>,
},
Get {
model: CollectionModel,
collection: String,
key: String,
},
Unseal {
collection: String,
key: String,
version: Option<i64>,
},
Rotate {
collection: String,
key: String,
value: Value,
tags: Vec<String>,
},
History {
collection: String,
key: String,
},
List {
model: CollectionModel,
collection: String,
prefix: Option<String>,
limit: Option<usize>,
offset: usize,
},
Purge {
collection: String,
key: String,
},
Watch {
model: CollectionModel,
collection: String,
key: String,
prefix: bool,
from_lsn: Option<u64>,
},
Delete {
model: CollectionModel,
collection: String,
key: String,
},
Incr {
model: CollectionModel,
collection: String,
key: String,
by: i64,
ttl_ms: Option<u64>,
},
Cas {
model: CollectionModel,
collection: String,
key: String,
expected: Option<Value>,
new_value: Value,
ttl_ms: Option<u64>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigValueType {
Bool,
Int,
String,
Url,
Object,
Array,
}
impl ConfigValueType {
pub fn as_str(self) -> &'static str {
match self {
Self::Bool => "bool",
Self::Int => "int",
Self::String => "string",
Self::Url => "url",
Self::Object => "object",
Self::Array => "array",
}
}
pub fn parse(input: &str) -> Option<Self> {
match input.to_ascii_lowercase().as_str() {
"bool" | "boolean" => Some(Self::Bool),
"int" | "integer" => Some(Self::Int),
"string" | "str" | "text" => Some(Self::String),
"url" => Some(Self::Url),
"object" | "json_object" => Some(Self::Object),
"array" | "list" => Some(Self::Array),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub enum ConfigCommand {
Put {
collection: String,
key: String,
value: Value,
value_type: Option<ConfigValueType>,
tags: Vec<String>,
},
Get {
collection: String,
key: String,
},
Resolve {
collection: String,
key: String,
},
Rotate {
collection: String,
key: String,
value: Value,
value_type: Option<ConfigValueType>,
tags: Vec<String>,
},
Delete {
collection: String,
key: String,
},
History {
collection: String,
key: String,
},
List {
collection: String,
prefix: Option<String>,
limit: Option<usize>,
offset: usize,
},
Watch {
collection: String,
key: String,
prefix: bool,
from_lsn: Option<u64>,
},
InvalidVolatileOperation {
operation: String,
collection: String,
key: Option<String>,
},
}