prax-pgvector 0.11.1

pgvector integration for the Prax ORM — vector similarity search, embeddings, and index management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! High-level query builder for vector similarity search.
//!
//! This module provides a fluent builder API for constructing vector search queries
//! that integrate with the prax-postgres engine.
//!
//! # Examples
//!
//! ```rust
//! use prax_pgvector::query::VectorSearchBuilder;
//! use prax_pgvector::{Embedding, DistanceMetric};
//!
//! let query = VectorSearchBuilder::new("documents", "embedding")
//!     .query(Embedding::new(vec![0.1, 0.2, 0.3]))
//!     .metric(DistanceMetric::Cosine)
//!     .limit(10)
//!     .select(&["id", "title", "content"])
//!     .where_clause("category = 'tech'")
//!     .build();
//!
//! let sql = query.to_sql();
//! assert!(sql.contains("<=>")); // cosine distance operator
//! ```

use serde::{Deserialize, Serialize};

use prax_query::sql::is_valid_sql_identifier;

use crate::error::{VectorError, VectorResult};
use crate::ops::{DistanceMetric, SearchParams};
use crate::types::Embedding;

/// A fully constructed vector search query ready for execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorSearchQuery {
    /// The table to search.
    pub table: String,
    /// The vector column.
    pub column: String,
    /// The query vector.
    pub query_vector: Embedding,
    /// Distance metric.
    pub metric: DistanceMetric,
    /// Maximum number of results.
    pub limit: usize,
    /// Columns to select (empty = all).
    pub select_columns: Vec<String>,
    /// Additional WHERE conditions.
    pub where_clauses: Vec<String>,
    /// Whether to include the distance in results.
    pub include_distance: bool,
    /// Alias for the distance column.
    pub distance_alias: String,
    /// Maximum distance threshold (radius search).
    pub max_distance: Option<f64>,
    /// Minimum distance threshold.
    pub min_distance: Option<f64>,
    /// Additional ORDER BY clauses (after distance).
    pub extra_order_by: Vec<String>,
    /// Offset for pagination.
    pub offset: Option<usize>,
    /// Search parameters (probes, ef_search).
    pub search_params: SearchParams,
}

impl VectorSearchQuery {
    /// Generate the complete SQL query.
    ///
    /// The query vector should be passed as parameter `$1`.
    pub fn to_sql(&self) -> String {
        self.to_sql_with_param(1)
    }

    /// Generate the complete SQL query with a custom parameter index.
    pub fn to_sql_with_param(&self, param_index: usize) -> String {
        let param = format!("${param_index}");
        let distance_expr = format!("{} {} {}", self.column, self.metric.operator(), param);

        // SELECT clause
        let select = if self.select_columns.is_empty() {
            "*".to_string()
        } else {
            self.select_columns.join(", ")
        };

        let distance_select = if self.include_distance {
            format!(", {} AS {}", distance_expr, self.distance_alias)
        } else {
            String::new()
        };

        // WHERE clause
        let mut where_parts = Vec::new();

        if let Some(max) = self.max_distance {
            where_parts.push(format!("{distance_expr} < {max}"));
        }
        if let Some(min) = self.min_distance {
            where_parts.push(format!("{distance_expr} >= {min}"));
        }
        where_parts.extend(self.where_clauses.clone());

        let where_clause = if where_parts.is_empty() {
            String::new()
        } else {
            format!(" WHERE {}", where_parts.join(" AND "))
        };

        // ORDER BY clause
        let order_by_main = if self.include_distance {
            self.distance_alias.clone()
        } else {
            distance_expr
        };

        let order_by = if self.extra_order_by.is_empty() {
            order_by_main
        } else {
            let mut parts = vec![order_by_main];
            parts.extend(self.extra_order_by.clone());
            parts.join(", ")
        };

        // LIMIT and OFFSET
        let limit = format!(" LIMIT {}", self.limit);
        let offset = self
            .offset
            .map(|o| format!(" OFFSET {o}"))
            .unwrap_or_default();

        format!(
            "SELECT {}{} FROM {}{}  ORDER BY {}{}{}",
            select, distance_select, self.table, where_clause, order_by, limit, offset
        )
    }

    /// Generate SET commands for search parameters.
    ///
    /// These should be executed before the search query to tune index scan behavior.
    pub fn param_set_sql(&self) -> Vec<String> {
        self.search_params.to_set_sql()
    }
}

/// Fluent builder for vector search queries.
///
/// # Examples
///
/// ```rust
/// use prax_pgvector::query::VectorSearchBuilder;
/// use prax_pgvector::{Embedding, DistanceMetric};
///
/// let query = VectorSearchBuilder::new("documents", "embedding")
///     .query(Embedding::new(vec![0.1, 0.2, 0.3]))
///     .metric(DistanceMetric::Cosine)
///     .limit(10)
///     .ef_search(200)
///     .build();
/// ```
pub struct VectorSearchBuilder {
    table: String,
    column: String,
    query_vector: Option<Embedding>,
    metric: DistanceMetric,
    limit: usize,
    select_columns: Vec<String>,
    where_clauses: Vec<String>,
    include_distance: bool,
    distance_alias: String,
    max_distance: Option<f64>,
    min_distance: Option<f64>,
    extra_order_by: Vec<String>,
    offset: Option<usize>,
    search_params: SearchParams,
}

impl VectorSearchBuilder {
    /// Create a new search builder for a table and vector column.
    pub fn new(table: impl Into<String>, column: impl Into<String>) -> Self {
        Self {
            table: table.into(),
            column: column.into(),
            query_vector: None,
            metric: DistanceMetric::L2,
            limit: 10,
            select_columns: Vec::new(),
            where_clauses: Vec::new(),
            include_distance: true,
            distance_alias: "distance".to_string(),
            max_distance: None,
            min_distance: None,
            extra_order_by: Vec::new(),
            offset: None,
            search_params: SearchParams::new(),
        }
    }

    /// Set the query vector.
    pub fn query(mut self, embedding: Embedding) -> Self {
        self.query_vector = Some(embedding);
        self
    }

    /// Set the distance metric.
    pub fn metric(mut self, metric: DistanceMetric) -> Self {
        self.metric = metric;
        self
    }

    /// Set the result limit.
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }

    /// Set specific columns to select.
    pub fn select(mut self, columns: &[&str]) -> Self {
        self.select_columns = columns.iter().map(|c| (*c).to_string()).collect();
        self
    }

    /// Add a WHERE condition.
    pub fn where_clause(mut self, condition: impl Into<String>) -> Self {
        self.where_clauses.push(condition.into());
        self
    }

    /// Set the maximum distance (radius search).
    pub fn max_distance(mut self, distance: f64) -> Self {
        self.max_distance = Some(distance);
        self
    }

    /// Set the minimum distance.
    pub fn min_distance(mut self, distance: f64) -> Self {
        self.min_distance = Some(distance);
        self
    }

    /// Don't include the distance in the results.
    pub fn without_distance(mut self) -> Self {
        self.include_distance = false;
        self
    }

    /// Set a custom distance column alias.
    pub fn distance_alias(mut self, alias: impl Into<String>) -> Self {
        self.distance_alias = alias.into();
        self
    }

    /// Add an additional ORDER BY clause (after distance).
    pub fn then_order_by(mut self, clause: impl Into<String>) -> Self {
        self.extra_order_by.push(clause.into());
        self
    }

    /// Set the offset for pagination.
    pub fn offset(mut self, offset: usize) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Set the IVFFlat probes parameter.
    pub fn probes(mut self, probes: usize) -> Self {
        self.search_params = self.search_params.probes(probes);
        self
    }

    /// Set the HNSW ef_search parameter.
    pub fn ef_search(mut self, ef: usize) -> Self {
        self.search_params = self.search_params.ef_search(ef);
        self
    }

    /// Build the vector search query.
    ///
    /// # Panics
    ///
    /// Panics if no query vector has been set. Use [`Self::try_build`] for
    /// a non-panicking alternative.
    pub fn build(self) -> VectorSearchQuery {
        self.try_build()
            .expect("query vector must be set before building")
    }

    /// Try to build the vector search query.
    ///
    /// Returns `None` if no query vector has been set.
    pub fn try_build(self) -> Option<VectorSearchQuery> {
        let query_vector = self.query_vector?;

        Some(VectorSearchQuery {
            table: self.table,
            column: self.column,
            query_vector,
            metric: self.metric,
            limit: self.limit,
            select_columns: self.select_columns,
            where_clauses: self.where_clauses,
            include_distance: self.include_distance,
            distance_alias: self.distance_alias,
            max_distance: self.max_distance,
            min_distance: self.min_distance,
            extra_order_by: self.extra_order_by,
            offset: self.offset,
            search_params: self.search_params,
        })
    }
}

/// Returns `true` if `name` is a valid PostgreSQL text search configuration
/// name — a simple identifier matching `^[A-Za-z_][A-Za-z0-9_]*$`.
fn is_valid_ts_config_name(name: &str) -> bool {
    is_valid_sql_identifier(name)
}

/// Builder for hybrid search queries that combine vector similarity with full-text search.
///
/// This generates queries that use both pgvector distance operators and
/// PostgreSQL tsvector/tsquery for combined similarity scoring.
///
/// # Examples
///
/// ```rust
/// use prax_pgvector::query::HybridSearchBuilder;
/// use prax_pgvector::{Embedding, DistanceMetric};
///
/// let query = HybridSearchBuilder::new("documents")
///     .vector_column("embedding")
///     .text_column("content")
///     .query_vector(Embedding::new(vec![0.1, 0.2, 0.3]))
///     .query_text("machine learning")
///     .metric(DistanceMetric::Cosine)
///     .vector_weight(0.7)
///     .text_weight(0.3)
///     .limit(10)
///     .build();
///
/// let sql = query.to_sql();
/// ```
pub struct HybridSearchBuilder {
    table: String,
    vector_column: Option<String>,
    text_column: Option<String>,
    query_vector: Option<Embedding>,
    query_text: Option<String>,
    metric: DistanceMetric,
    vector_weight: f64,
    text_weight: f64,
    limit: usize,
    language: String,
    where_clauses: Vec<String>,
}

impl HybridSearchBuilder {
    /// Create a new hybrid search builder.
    pub fn new(table: impl Into<String>) -> Self {
        Self {
            table: table.into(),
            vector_column: None,
            text_column: None,
            query_vector: None,
            query_text: None,
            metric: DistanceMetric::Cosine,
            vector_weight: 0.5,
            text_weight: 0.5,
            limit: 10,
            language: "english".to_string(),
            where_clauses: Vec::new(),
        }
    }

    /// Set the vector column name.
    pub fn vector_column(mut self, column: impl Into<String>) -> Self {
        self.vector_column = Some(column.into());
        self
    }

    /// Set the text column name.
    pub fn text_column(mut self, column: impl Into<String>) -> Self {
        self.text_column = Some(column.into());
        self
    }

    /// Set the query vector.
    pub fn query_vector(mut self, embedding: Embedding) -> Self {
        self.query_vector = Some(embedding);
        self
    }

    /// Set the text query.
    pub fn query_text(mut self, text: impl Into<String>) -> Self {
        self.query_text = Some(text.into());
        self
    }

    /// Set the vector distance metric.
    pub fn metric(mut self, metric: DistanceMetric) -> Self {
        self.metric = metric;
        self
    }

    /// Set the weight for the vector similarity component (0.0 to 1.0).
    pub fn vector_weight(mut self, weight: f64) -> Self {
        self.vector_weight = weight;
        self
    }

    /// Set the weight for the text relevance component (0.0 to 1.0).
    pub fn text_weight(mut self, weight: f64) -> Self {
        self.text_weight = weight;
        self
    }

    /// Set the result limit.
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }

    /// Set the text search language.
    ///
    /// The language is interpolated into SQL string literals, so it must be a
    /// valid PostgreSQL text search configuration name: a simple identifier
    /// matching `^[A-Za-z_][A-Za-z0-9_]*$` (e.g. `english`, `simple`).
    ///
    /// This is the panicking convenience for trusted, hardcoded values;
    /// prefer [`try_language`](Self::try_language) when the language comes
    /// from untrusted (e.g. request-influenced) input.
    ///
    /// # Panics
    ///
    /// Panics if `language` is not a valid configuration name.
    pub fn language(mut self, language: impl Into<String>) -> Self {
        let language = language.into();
        assert!(
            is_valid_ts_config_name(&language),
            "invalid text search language {language:?}: must match ^[A-Za-z_][A-Za-z0-9_]*$"
        );
        self.language = language;
        self
    }

    /// Set the text search language, returning an error for invalid names.
    ///
    /// Fallible counterpart to [`language`](Self::language) — use this when
    /// the language is influenced by untrusted input so an invalid name is
    /// a recoverable error instead of a panic.
    pub fn try_language(mut self, language: impl Into<String>) -> VectorResult<Self> {
        let language = language.into();
        if !is_valid_ts_config_name(&language) {
            return Err(VectorError::config(format!(
                "invalid text search language {language:?}: must match ^[A-Za-z_][A-Za-z0-9_]*$"
            )));
        }
        self.language = language;
        Ok(self)
    }

    /// Add a WHERE condition.
    pub fn where_clause(mut self, condition: impl Into<String>) -> Self {
        self.where_clauses.push(condition.into());
        self
    }

    /// Build the hybrid search query.
    pub fn build(self) -> HybridSearchQuery {
        HybridSearchQuery {
            table: self.table,
            vector_column: self
                .vector_column
                .unwrap_or_else(|| "embedding".to_string()),
            text_column: self.text_column.unwrap_or_else(|| "content".to_string()),
            query_vector: self.query_vector,
            query_text: self.query_text,
            metric: self.metric,
            vector_weight: self.vector_weight,
            text_weight: self.text_weight,
            limit: self.limit,
            language: self.language,
            where_clauses: self.where_clauses,
        }
    }
}

/// A hybrid search query combining vector similarity and full-text search.
///
/// **Result shape:** the SQL from [`to_sql`](Self::to_sql) returns two columns —
/// an anonymous composite named `coalesce` (the merged matched row) and
/// `rrf_score`. The composite's fields cannot be expanded or selected in SQL;
/// see [`to_sql`](Self::to_sql) for how to consume it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HybridSearchQuery {
    /// Table name.
    pub table: String,
    /// Vector column.
    pub vector_column: String,
    /// Text column.
    pub text_column: String,
    /// Query vector.
    pub query_vector: Option<Embedding>,
    /// Text query.
    pub query_text: Option<String>,
    /// Distance metric.
    pub metric: DistanceMetric,
    /// Weight for vector similarity (0.0-1.0).
    pub vector_weight: f64,
    /// Weight for text relevance (0.0-1.0).
    pub text_weight: f64,
    /// Result limit.
    pub limit: usize,
    /// Text search language.
    pub language: String,
    /// Additional WHERE conditions.
    pub where_clauses: Vec<String>,
}

impl HybridSearchQuery {
    /// Generate the SQL query using Reciprocal Rank Fusion (RRF).
    ///
    /// RRF combines rankings from multiple retrieval methods:
    /// `score = sum(1 / (k + rank_i))` where k is a constant (typically 60).
    ///
    /// The query vector should be `$1` and the text query should be `$2`.
    ///
    /// # Result shape
    ///
    /// The final SELECT returns **two columns**: an anonymous composite named
    /// `coalesce` — the whole matched row from `vector_results` (when both
    /// sides match, the vector side wins) or `text_results` — plus `rrf_score`.
    /// The composite's record type is never registered, so PostgreSQL rejects
    /// both `(coalesce).*` expansion and per-field access like `(coalesce).id`
    /// with "record type has not been registered". Consumers must either
    /// decode the composite value client-side or wrap the query and project
    /// `row_to_json(coalesce)` (or `to_json(coalesce)`). The composite also
    /// carries the matching side's rank column (`vec_rank` or `text_rank`) in
    /// addition to the base table columns, so its shape is not fixed.
    pub fn to_sql(&self) -> String {
        // The builder validates `language`, but these fields are public, so
        // escape single quotes as defense-in-depth before interpolating into
        // SQL string literals.
        let lang = self.language.replace('\'', "''");
        let vec_distance = format!("{} {} $1", self.vector_column, self.metric.operator());
        let text_rank = format!(
            "ts_rank(to_tsvector('{lang}', {}), plainto_tsquery('{lang}', $2))",
            self.text_column
        );
        let fts_match = format!(
            "to_tsvector('{lang}', {}) @@ plainto_tsquery('{lang}', $2)",
            self.text_column
        );

        let where_clause = if self.where_clauses.is_empty() {
            String::new()
        } else {
            format!(" WHERE {}", self.where_clauses.join(" AND "))
        };

        // text_results already filters on the FTS match, so user filters must
        // be AND-joined to it — a second WHERE keyword would be invalid SQL.
        let text_where = if self.where_clauses.is_empty() {
            format!(" WHERE {fts_match}")
        } else {
            format!("{where_clause} AND {fts_match}")
        };

        // Use RRF scoring: combine vector and text rankings
        format!(
            "WITH vector_results AS (\
                SELECT *, ROW_NUMBER() OVER (ORDER BY {vec_distance}) AS vec_rank \
                FROM {table}{where_clause} \
                ORDER BY {vec_distance} \
                LIMIT {fetch_limit}\
            ), \
            text_results AS (\
                SELECT *, ROW_NUMBER() OVER (ORDER BY {text_rank} DESC) AS text_rank \
                FROM {table}{text_where} \
                ORDER BY {text_rank} DESC \
                LIMIT {fetch_limit}\
            ) \
            SELECT COALESCE(v.*, t.*), \
                ({vec_weight} / (60.0 + COALESCE(v.vec_rank, 1000))) + \
                ({text_weight} / (60.0 + COALESCE(t.text_rank, 1000))) AS rrf_score \
            FROM vector_results v \
            FULL OUTER JOIN text_results t ON v.id = t.id \
            ORDER BY rrf_score DESC \
            LIMIT {limit}",
            table = self.table,
            where_clause = where_clause,
            text_where = text_where,
            fetch_limit = self.limit * 3, // Fetch more for fusion
            vec_weight = self.vector_weight,
            text_weight = self.text_weight,
            limit = self.limit,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_embedding() -> Embedding {
        Embedding::new(vec![0.1, 0.2, 0.3])
    }

    #[test]
    fn test_basic_search_query() {
        let query = VectorSearchBuilder::new("documents", "embedding")
            .query(test_embedding())
            .metric(DistanceMetric::Cosine)
            .limit(10)
            .build();

        let sql = query.to_sql();
        assert!(sql.contains("SELECT *"));
        assert!(sql.contains("AS distance"));
        assert!(sql.contains("<=>"));
        assert!(sql.contains("$1"));
        assert!(sql.contains("FROM documents"));
        assert!(sql.contains("LIMIT 10"));
    }

    #[test]
    fn test_search_with_select() {
        let query = VectorSearchBuilder::new("documents", "embedding")
            .query(test_embedding())
            .select(&["id", "title"])
            .build();

        let sql = query.to_sql();
        assert!(sql.contains("SELECT id, title"));
    }

    #[test]
    fn test_search_with_where() {
        let query = VectorSearchBuilder::new("documents", "embedding")
            .query(test_embedding())
            .where_clause("category = 'tech'")
            .where_clause("published = true")
            .build();

        let sql = query.to_sql();
        assert!(sql.contains("WHERE"));
        assert!(sql.contains("category = 'tech'"));
        assert!(sql.contains("published = true"));
        assert!(sql.contains("AND"));
    }

    #[test]
    fn test_search_with_max_distance() {
        let query = VectorSearchBuilder::new("documents", "embedding")
            .query(test_embedding())
            .metric(DistanceMetric::L2)
            .max_distance(0.5)
            .build();

        let sql = query.to_sql();
        assert!(sql.contains("< 0.5"));
    }

    #[test]
    fn test_search_with_distance_range() {
        let query = VectorSearchBuilder::new("documents", "embedding")
            .query(test_embedding())
            .min_distance(0.1)
            .max_distance(0.5)
            .build();

        let sql = query.to_sql();
        assert!(sql.contains("< 0.5"));
        assert!(sql.contains(">= 0.1"));
    }

    #[test]
    fn test_search_without_distance() {
        let query = VectorSearchBuilder::new("documents", "embedding")
            .query(test_embedding())
            .without_distance()
            .build();

        let sql = query.to_sql();
        assert!(!sql.contains("AS distance"));
    }

    #[test]
    fn test_search_custom_alias() {
        let query = VectorSearchBuilder::new("documents", "embedding")
            .query(test_embedding())
            .distance_alias("similarity")
            .build();

        let sql = query.to_sql();
        assert!(sql.contains("AS similarity"));
    }

    #[test]
    fn test_search_with_pagination() {
        let query = VectorSearchBuilder::new("documents", "embedding")
            .query(test_embedding())
            .limit(10)
            .offset(20)
            .build();

        let sql = query.to_sql();
        assert!(sql.contains("LIMIT 10"));
        assert!(sql.contains("OFFSET 20"));
    }

    #[test]
    fn test_search_with_extra_order_by() {
        let query = VectorSearchBuilder::new("documents", "embedding")
            .query(test_embedding())
            .then_order_by("created_at DESC")
            .build();

        let sql = query.to_sql();
        assert!(sql.contains("ORDER BY distance, created_at DESC"));
    }

    #[test]
    fn test_search_params() {
        let query = VectorSearchBuilder::new("documents", "embedding")
            .query(test_embedding())
            .probes(10)
            .ef_search(200)
            .build();

        let set_sql = query.param_set_sql();
        assert_eq!(set_sql.len(), 2);
        assert!(set_sql[0].contains("ivfflat.probes = 10"));
        assert!(set_sql[1].contains("hnsw.ef_search = 200"));
    }

    #[test]
    fn test_try_build_without_vector() {
        let result = VectorSearchBuilder::new("documents", "embedding").try_build();
        assert!(result.is_none());
    }

    #[test]
    fn test_custom_param_index() {
        let query = VectorSearchBuilder::new("documents", "embedding")
            .query(test_embedding())
            .build();

        let sql = query.to_sql_with_param(3);
        assert!(sql.contains("$3"));
    }

    #[test]
    fn test_hybrid_search() {
        let query = HybridSearchBuilder::new("documents")
            .vector_column("embedding")
            .text_column("content")
            .query_vector(test_embedding())
            .query_text("machine learning")
            .metric(DistanceMetric::Cosine)
            .vector_weight(0.7)
            .text_weight(0.3)
            .limit(10)
            .build();

        let sql = query.to_sql();
        assert!(sql.contains("vector_results"));
        assert!(sql.contains("text_results"));
        assert!(sql.contains("rrf_score"));
        assert!(sql.contains("<=>"));
        assert!(sql.contains("ts_rank"));
        assert!(sql.contains("FULL OUTER JOIN"));
    }

    #[test]
    fn test_hybrid_search_with_where_clause_single_where() {
        let query = HybridSearchBuilder::new("documents")
            .vector_column("embedding")
            .text_column("content")
            .query_vector(test_embedding())
            .query_text("machine learning")
            .where_clause("category = 'tech'")
            .build();

        let sql = query.to_sql();
        // One WHERE per CTE: the FTS predicate must be AND-joined to the user
        // filter in text_results, not emitted as a second WHERE keyword.
        assert_eq!(sql.matches("WHERE").count(), 2);
        assert!(sql.contains(
            "WHERE category = 'tech' AND to_tsvector('english', content) @@ plainto_tsquery('english', $2)"
        ));
    }

    #[test]
    #[should_panic(expected = "invalid text search language")]
    fn test_hybrid_language_rejects_invalid() {
        let _ = HybridSearchBuilder::new("documents").language("english'); DROP TABLE users; --");
    }

    #[test]
    fn test_hybrid_try_language_returns_error_instead_of_panicking() {
        let result =
            HybridSearchBuilder::new("documents").try_language("english'); DROP TABLE users; --");
        assert!(result.is_err(), "invalid language should be an error");

        let builder = HybridSearchBuilder::new("documents")
            .try_language("spanish")
            .expect("valid language should build");
        assert_eq!(builder.build().language, "spanish");
    }

    #[test]
    fn test_hybrid_language_escaped_when_constructed_directly() {
        // HybridSearchQuery's fields are public, so to_sql must still escape
        // single quotes as defense-in-depth.
        let mut query = HybridSearchBuilder::new("documents").build();
        query.language = "english'); DROP TABLE users; --".to_string();
        let sql = query.to_sql();
        assert!(sql.contains("'english''); DROP TABLE users; --'"));
        assert!(!sql.contains("'english');"));
    }

    #[test]
    fn test_all_metrics_produce_valid_sql() {
        for metric in [
            DistanceMetric::L2,
            DistanceMetric::InnerProduct,
            DistanceMetric::Cosine,
            DistanceMetric::L1,
        ] {
            let query = VectorSearchBuilder::new("t", "c")
                .query(test_embedding())
                .metric(metric)
                .build();
            let sql = query.to_sql();
            assert!(sql.contains(metric.operator()), "failed for {metric}");
        }
    }
}