-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathrelational_queries.rs
3619 lines (3308 loc) · 126 KB
/
relational_queries.rs
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///! This module contains the gory details of using Diesel to query
///! a database schema that is not known at compile time. The code in this
///! module is mostly concerned with constructing SQL queries and some
///! helpers for serializing and deserializing entities.
///!
///! Code in this module works very hard to minimize the number of allocations
///! that it performs
use diesel::pg::{Pg, PgConnection};
use diesel::query_builder::{AstPass, QueryFragment, QueryId};
use diesel::query_dsl::{LoadQuery, RunQueryDsl};
use diesel::result::{Error as DieselError, QueryResult};
use diesel::sql_types::{Array, BigInt, Binary, Bool, Integer, Jsonb, Text};
use diesel::Connection;
use graph::components::store::EntityKey;
use graph::data::value::Word;
use graph::prelude::{
anyhow, r, serde_json, Attribute, BlockNumber, ChildMultiplicity, Entity, EntityCollection,
EntityFilter, EntityLink, EntityOrder, EntityRange, EntityWindow, ParentLink,
QueryExecutionError, StoreError, Value, ENV_VARS,
};
use graph::{
components::store::{AttributeNames, EntityType},
data::{schema::FulltextAlgorithm, store::scalar},
};
use itertools::Itertools;
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::convert::TryFrom;
use std::fmt::{self, Display};
use std::iter::FromIterator;
use std::str::FromStr;
use crate::relational::{
Column, ColumnType, IdType, Layout, SqlName, Table, BYTE_ARRAY_PREFIX_SIZE, PRIMARY_KEY_COLUMN,
STRING_PREFIX_SIZE,
};
use crate::sql_value::SqlValue;
use crate::{
block_range::{
BlockRangeColumn, BlockRangeLowerBoundClause, BlockRangeUpperBoundClause, BLOCK_COLUMN,
BLOCK_RANGE_COLUMN, BLOCK_RANGE_CURRENT,
},
primary::{Namespace, Site},
};
/// Those are columns that we always want to fetch from the database.
const BASE_SQL_COLUMNS: [&'static str; 2] = ["id", "vid"];
#[derive(Debug)]
pub(crate) struct UnsupportedFilter {
pub filter: String,
pub value: Value,
}
impl Display for UnsupportedFilter {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(
f,
"unsupported filter `{}` for value `{}`",
self.filter, self.value
)
}
}
impl std::error::Error for UnsupportedFilter {}
impl From<UnsupportedFilter> for diesel::result::Error {
fn from(error: UnsupportedFilter) -> Self {
diesel::result::Error::QueryBuilderError(Box::new(error))
}
}
// Similar to graph::prelude::constraint_violation, but returns a Diesel
// error for use in the guts of query generation
macro_rules! constraint_violation {
($msg:expr) => {{
diesel::result::Error::QueryBuilderError(anyhow!("{}", $msg).into())
}};
($fmt:expr, $($arg:tt)*) => {{
diesel::result::Error::QueryBuilderError(anyhow!($fmt, $($arg)*).into())
}}
}
fn str_as_bytes(id: &str) -> QueryResult<scalar::Bytes> {
scalar::Bytes::from_str(id).map_err(|e| DieselError::SerializationError(Box::new(e)))
}
/// Convert Postgres string representation of bytes "\xdeadbeef"
/// to ours of just "deadbeef".
fn bytes_as_str(id: &str) -> String {
id.trim_start_matches("\\x").to_owned()
}
impl IdType {
/// Add `ids` as a bind variable to `out`, using the right SQL type
fn bind_ids<S>(&self, ids: &[S], out: &mut AstPass<Pg>) -> QueryResult<()>
where
S: AsRef<str> + diesel::serialize::ToSql<Text, Pg>,
{
match self {
IdType::String => out.push_bind_param::<Array<Text>, _>(&ids)?,
IdType::Bytes => {
let ids = ids
.iter()
.map(|id| str_as_bytes(id.as_ref()))
.collect::<Result<Vec<scalar::Bytes>, _>>()?;
let id_slices = ids.iter().map(|id| id.as_slice()).collect::<Vec<_>>();
out.push_bind_param::<Array<Binary>, _>(&id_slices)?;
}
}
// Generate '::text[]' or '::bytea[]'
out.push_sql("::");
out.push_sql(self.sql_type());
out.push_sql("[]");
Ok(())
}
}
/// Conveniences for handling foreign keys depending on whether we are using
/// `IdType::Bytes` or `IdType::String` as the primary key
///
/// This trait adds some capabilities to `Column` that are very specific to
/// how we generate SQL queries. Using a method like `bind_ids` from this
/// trait on a given column means "send these values to the database in a form
/// that can later be used for comparisons with that column"
trait ForeignKeyClauses {
/// The type of the column
fn column_type(&self) -> &ColumnType;
/// The name of the column
fn name(&self) -> &str;
/// Add `id` as a bind variable to `out`, using the right SQL type
fn bind_id(&self, id: &str, out: &mut AstPass<Pg>) -> QueryResult<()> {
match self.column_type().id_type() {
IdType::String => out.push_bind_param::<Text, _>(&id)?,
IdType::Bytes => out.push_bind_param::<Binary, _>(&str_as_bytes(id)?.as_slice())?,
}
// Generate '::text' or '::bytea'
out.push_sql("::");
out.push_sql(self.column_type().sql_type());
Ok(())
}
/// Add `ids` as a bind variable to `out`, using the right SQL type
fn bind_ids<S>(&self, ids: &[S], out: &mut AstPass<Pg>) -> QueryResult<()>
where
S: AsRef<str> + diesel::serialize::ToSql<Text, Pg>,
{
self.column_type().id_type().bind_ids(ids, out)
}
/// Generate a clause `{name()} = $id` using the right types to bind `$id`
/// into `out`
fn eq(&self, id: &str, out: &mut AstPass<Pg>) -> QueryResult<()> {
out.push_sql(self.name());
out.push_sql(" = ");
self.bind_id(id, out)
}
/// Generate a clause
/// `exists (select 1 from unnest($ids) as p(g$id) where id = p.g$id)`
/// using the right types to bind `$ids` into `out`
fn is_in<S>(&self, ids: &[S], out: &mut AstPass<Pg>) -> QueryResult<()>
where
S: AsRef<str> + diesel::serialize::ToSql<Text, Pg>,
{
out.push_sql("exists (select 1 from unnest(");
self.bind_ids(ids, out)?;
out.push_sql(") as p(g$id) where id = p.g$id)");
Ok(())
}
/// Generate an array of arrays as literal SQL. The `ids` must form a
/// valid matrix, i.e. the same numbe of entries in each row. This can
/// be achieved by padding them with `None` values. Diesel does not support
/// arrays of arrays as bind variables, nor arrays containing nulls, so
/// we have to manually serialize the `ids` as literal SQL.
fn push_matrix(
&self,
matrix: &[Vec<Option<SafeString>>],
out: &mut AstPass<Pg>,
) -> QueryResult<()> {
out.push_sql("array[");
if matrix.is_empty() {
// If there are no ids, make sure we are producing an
// empty array of arrays
out.push_sql("array[null]");
} else {
for (i, ids) in matrix.iter().enumerate() {
if i > 0 {
out.push_sql(", ");
}
out.push_sql("array[");
for (j, id) in ids.iter().enumerate() {
if j > 0 {
out.push_sql(", ");
}
match id {
None => out.push_sql("null"),
Some(id) => match self.column_type().id_type() {
IdType::String => {
out.push_sql("'");
out.push_sql(&id.0);
out.push_sql("'");
}
IdType::Bytes => {
out.push_sql("'\\x");
out.push_sql(id.0.trim_start_matches("0x"));
out.push_sql("'");
}
},
}
}
out.push_sql("]");
}
}
// Generate '::text[][]' or '::bytea[][]'
out.push_sql("]::");
out.push_sql(self.column_type().sql_type());
out.push_sql("[][]");
Ok(())
}
}
impl ForeignKeyClauses for Column {
fn column_type(&self) -> &ColumnType {
&self.column_type
}
fn name(&self) -> &str {
self.name.as_str()
}
}
pub trait FromEntityData: std::fmt::Debug + std::default::Default {
type Value: FromColumnValue;
fn new_entity(typename: String) -> Self;
fn insert_entity_data(&mut self, key: String, v: Self::Value);
}
impl FromEntityData for Entity {
type Value = graph::prelude::Value;
fn new_entity(typename: String) -> Self {
let mut entity = Entity::new();
entity.insert("__typename".to_string(), Self::Value::String(typename));
entity
}
fn insert_entity_data(&mut self, key: String, v: Self::Value) {
self.insert(key, v);
}
}
impl FromEntityData for BTreeMap<Word, r::Value> {
type Value = r::Value;
fn new_entity(typename: String) -> Self {
let mut map = BTreeMap::new();
map.insert("__typename".into(), Self::Value::from_string(typename));
map
}
fn insert_entity_data(&mut self, key: String, v: Self::Value) {
self.insert(Word::from(key), v);
}
}
pub trait FromColumnValue: Sized + std::fmt::Debug {
fn is_null(&self) -> bool;
fn null() -> Self;
fn from_string(s: String) -> Self;
fn from_bool(b: bool) -> Self;
fn from_i32(i: i32) -> Self;
fn from_big_decimal(d: scalar::BigDecimal) -> Self;
fn from_big_int(i: serde_json::Number) -> Result<Self, StoreError>;
// The string returned by the DB, without the leading '\x'
fn from_bytes(i: &str) -> Result<Self, StoreError>;
fn from_vec(v: Vec<Self>) -> Self;
fn from_column_value(
column_type: &ColumnType,
json: serde_json::Value,
) -> Result<Self, StoreError> {
use serde_json::Value as j;
// Many possible conversion errors are already caught by how
// we define the schema; for example, we can only get a NULL for
// a column that is actually nullable
match (json, column_type) {
(j::Null, _) => Ok(Self::null()),
(j::Bool(b), _) => Ok(Self::from_bool(b)),
(j::Number(number), ColumnType::Int) => match number.as_i64() {
Some(i) => i32::try_from(i).map(Self::from_i32).map_err(|e| {
StoreError::Unknown(anyhow!("failed to convert {} to Int: {}", number, e))
}),
None => Err(StoreError::Unknown(anyhow!(
"failed to convert {} to Int",
number
))),
},
(j::Number(number), ColumnType::BigDecimal) => {
let s = number.to_string();
scalar::BigDecimal::from_str(s.as_str())
.map(Self::from_big_decimal)
.map_err(|e| {
StoreError::Unknown(anyhow!(
"failed to convert {} to BigDecimal: {}",
number,
e
))
})
}
(j::Number(number), ColumnType::BigInt) => Self::from_big_int(number),
(j::Number(number), column_type) => Err(StoreError::Unknown(anyhow!(
"can not convert number {} to {:?}",
number,
column_type
))),
(j::String(s), ColumnType::String) | (j::String(s), ColumnType::Enum(_)) => {
Ok(Self::from_string(s))
}
(j::String(s), ColumnType::Bytes) => Self::from_bytes(s.trim_start_matches("\\x")),
(j::String(s), column_type) => Err(StoreError::Unknown(anyhow!(
"can not convert string {} to {:?}",
s,
column_type
))),
(j::Array(values), _) => Ok(Self::from_vec(
values
.into_iter()
.map(|v| Self::from_column_value(column_type, v))
.collect::<Result<Vec<_>, _>>()?,
)),
(j::Object(_), _) => {
unimplemented!("objects as entity attributes are not needed/supported")
}
}
}
}
impl FromColumnValue for r::Value {
fn is_null(&self) -> bool {
matches!(self, r::Value::Null)
}
fn null() -> Self {
Self::Null
}
fn from_string(s: String) -> Self {
r::Value::String(s)
}
fn from_bool(b: bool) -> Self {
r::Value::Boolean(b)
}
fn from_i32(i: i32) -> Self {
r::Value::Int(i.into())
}
fn from_big_decimal(d: scalar::BigDecimal) -> Self {
r::Value::String(d.to_string())
}
fn from_big_int(i: serde_json::Number) -> Result<Self, StoreError> {
Ok(r::Value::String(i.to_string()))
}
fn from_bytes(b: &str) -> Result<Self, StoreError> {
// In some cases, we pass strings as parent_id's through the
// database; those are already prefixed with '0x' and we need to
// avoid double-prefixing
if b.starts_with("0x") {
Ok(r::Value::String(b.to_string()))
} else {
Ok(r::Value::String(format!("0x{}", b)))
}
}
fn from_vec(v: Vec<Self>) -> Self {
r::Value::List(v)
}
}
impl FromColumnValue for graph::prelude::Value {
fn is_null(&self) -> bool {
self == &Value::Null
}
fn null() -> Self {
Self::Null
}
fn from_string(s: String) -> Self {
graph::prelude::Value::String(s)
}
fn from_bool(b: bool) -> Self {
graph::prelude::Value::Bool(b)
}
fn from_i32(i: i32) -> Self {
graph::prelude::Value::Int(i)
}
fn from_big_decimal(d: scalar::BigDecimal) -> Self {
graph::prelude::Value::BigDecimal(d)
}
fn from_big_int(i: serde_json::Number) -> Result<Self, StoreError> {
scalar::BigInt::from_str(&i.to_string())
.map(graph::prelude::Value::BigInt)
.map_err(|e| StoreError::Unknown(anyhow!("failed to convert {} to BigInt: {}", i, e)))
}
fn from_bytes(b: &str) -> Result<Self, StoreError> {
scalar::Bytes::from_str(b)
.map(graph::prelude::Value::Bytes)
.map_err(|e| StoreError::Unknown(anyhow!("failed to convert {} to Bytes: {}", b, e)))
}
fn from_vec(v: Vec<Self>) -> Self {
graph::prelude::Value::List(v)
}
}
/// A [`diesel`] utility `struct` for fetching only [`EntityType`] and entity's
/// ID. Unlike [`EntityData`], we don't really care about attributes here.
#[derive(QueryableByName)]
pub struct EntityDeletion {
#[sql_type = "Text"]
entity: String,
#[sql_type = "Text"]
id: String,
}
impl EntityDeletion {
pub fn entity_type(&self) -> EntityType {
EntityType::new(self.entity.clone())
}
pub fn id(&self) -> &str {
&self.id
}
}
/// Helper struct for retrieving entities from the database. With diesel, we
/// can only run queries that return columns whose number and type are known
/// at compile time. Because of that, we retrieve the actual data for an
/// entity as Jsonb by converting the row containing the entity using the
/// `to_jsonb` function.
#[derive(QueryableByName, Debug)]
pub struct EntityData {
#[sql_type = "Text"]
entity: String,
#[sql_type = "Jsonb"]
data: serde_json::Value,
}
impl EntityData {
pub fn entity_type(&self) -> EntityType {
EntityType::new(self.entity.clone())
}
/// Map the `EntityData` using the schema information in `Layout`
pub fn deserialize_with_layout<T: FromEntityData>(
self,
layout: &Layout,
parent_type: Option<&ColumnType>,
remove_typename: bool,
) -> Result<T, StoreError> {
let entity_type = EntityType::new(self.entity);
let table = layout.table_for_entity(&entity_type)?;
use serde_json::Value as j;
match self.data {
j::Object(map) => {
let mut out = if !remove_typename {
T::new_entity(entity_type.into_string())
} else {
T::default()
};
for (key, json) in map {
// Simply ignore keys that do not have an underlying table
// column; those will be things like the block_range that
// is used internally for versioning
if key == "g$parent_id" {
match &parent_type {
None => {
// A query that does not have parents
// somehow returned parent ids. We have no
// idea how to deserialize that
return Err(graph::constraint_violation!(
"query unexpectedly produces parent ids"
));
}
Some(parent_type) => {
let value = T::Value::from_column_value(parent_type, json)?;
out.insert_entity_data("g$parent_id".to_owned(), value);
}
}
} else if let Some(column) = table.column(&SqlName::verbatim(key)) {
let value = T::Value::from_column_value(&column.column_type, json)?;
if !value.is_null() {
out.insert_entity_data(column.field.clone(), value);
}
}
}
Ok(out)
}
_ => unreachable!(
"we use `to_json` in our queries, and will therefore always get an object back"
),
}
}
}
/// A `QueryValue` makes it possible to bind a `Value` into a SQL query
/// using the metadata from Column
struct QueryValue<'a>(&'a Value, &'a ColumnType);
impl<'a> QueryFragment<Pg> for QueryValue<'a> {
fn walk_ast(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
out.unsafe_to_cache_prepared();
let column_type = self.1;
match self.0 {
Value::String(s) => match &column_type {
ColumnType::String => out.push_bind_param::<Text, _>(s),
ColumnType::Enum(enum_type) => {
out.push_bind_param::<Text, _>(s)?;
out.push_sql("::");
out.push_sql(enum_type.name.as_str());
Ok(())
}
ColumnType::TSVector(_) => {
out.push_sql("to_tsquery(");
out.push_bind_param::<Text, _>(s)?;
out.push_sql(")");
Ok(())
}
ColumnType::Bytes => {
let bytes = scalar::Bytes::from_str(s)
.map_err(|e| DieselError::SerializationError(Box::new(e)))?;
out.push_bind_param::<Binary, _>(&bytes.as_slice())
}
_ => unreachable!(
"only string, enum and tsvector columns have values of type string"
),
},
Value::Int(i) => out.push_bind_param::<Integer, _>(i),
Value::BigDecimal(d) => {
out.push_bind_param::<Text, _>(&d.to_string())?;
out.push_sql("::numeric");
Ok(())
}
Value::Bool(b) => out.push_bind_param::<Bool, _>(b),
Value::List(values) => {
let sql_values = SqlValue::new_array(values.clone());
match &column_type {
ColumnType::BigDecimal | ColumnType::BigInt => {
let text_values: Vec<_> = values.iter().map(|v| v.to_string()).collect();
out.push_bind_param::<Array<Text>, _>(&text_values)?;
out.push_sql("::numeric[]");
Ok(())
}
ColumnType::Boolean => out.push_bind_param::<Array<Bool>, _>(&sql_values),
ColumnType::Bytes => out.push_bind_param::<Array<Binary>, _>(&sql_values),
ColumnType::Int => out.push_bind_param::<Array<Integer>, _>(&sql_values),
ColumnType::String => out.push_bind_param::<Array<Text>, _>(&sql_values),
ColumnType::Enum(enum_type) => {
out.push_bind_param::<Array<Text>, _>(&sql_values)?;
out.push_sql("::");
out.push_sql(enum_type.name.as_str());
out.push_sql("[]");
Ok(())
}
// TSVector will only be in a Value::List() for inserts so "to_tsvector" can always be used here
ColumnType::TSVector(config) => {
if sql_values.is_empty() {
out.push_sql("''::tsvector");
} else {
out.push_sql("(");
for (i, value) in sql_values.iter().enumerate() {
if i > 0 {
out.push_sql(") || ");
}
out.push_sql("to_tsvector(");
out.push_bind_param::<Text, _>(
&config.language.as_str().to_string(),
)?;
out.push_sql("::regconfig, ");
out.push_bind_param::<Text, _>(&value)?;
}
out.push_sql("))");
}
Ok(())
}
}
}
Value::Null => {
out.push_sql("null");
Ok(())
}
Value::Bytes(b) => out.push_bind_param::<Binary, _>(&b.as_slice()),
Value::BigInt(i) => {
out.push_bind_param::<Text, _>(&i.to_string())?;
out.push_sql("::numeric");
Ok(())
}
}
}
}
#[derive(Copy, Clone, PartialEq)]
enum Comparison {
Less,
LessOrEqual,
Equal,
NotEqual,
GreaterOrEqual,
Greater,
Match,
}
impl Comparison {
fn as_str(&self) -> &str {
use Comparison::*;
match self {
Less => " < ",
LessOrEqual => " <= ",
Equal => " = ",
NotEqual => " != ",
GreaterOrEqual => " >= ",
Greater => " > ",
Match => " @@ ",
}
}
}
enum PrefixType<'a> {
String(&'a Column),
Bytes(&'a Column),
}
impl<'a> PrefixType<'a> {
fn new(column: &'a Column) -> QueryResult<Self> {
match column.column_type {
ColumnType::String => Ok(PrefixType::String(column)),
ColumnType::Bytes => Ok(PrefixType::Bytes(column)),
_ => Err(constraint_violation!(
"cannot setup prefix comparison for column {} of type {}",
column.name(),
column.column_type().sql_type()
)),
}
}
/// Push the SQL expression for a prefix of values in our column. That
/// should be the same expression that we used when creating an index
/// for the column
fn push_column_prefix(&self, out: &mut AstPass<Pg>) -> QueryResult<()> {
match self {
PrefixType::String(column) => {
out.push_sql("left(");
out.push_identifier(column.name.as_str())?;
out.push_sql(", ");
out.push_sql(&STRING_PREFIX_SIZE.to_string());
out.push_sql(")");
}
PrefixType::Bytes(column) => {
out.push_sql("substring(");
out.push_identifier(column.name.as_str())?;
out.push_sql(", 1, ");
out.push_sql(&BYTE_ARRAY_PREFIX_SIZE.to_string());
out.push_sql(")");
}
}
Ok(())
}
fn is_large(&self, value: &Value) -> Result<bool, ()> {
match (self, value) {
(PrefixType::String(_), Value::String(s)) => Ok(s.len() > STRING_PREFIX_SIZE - 1),
(PrefixType::Bytes(_), Value::Bytes(b)) => Ok(b.len() > BYTE_ARRAY_PREFIX_SIZE - 1),
(PrefixType::Bytes(_), Value::String(s)) => {
let len = if s.starts_with("0x") {
(s.len() - 2) / 2
} else {
s.len() / 2
};
Ok(len > BYTE_ARRAY_PREFIX_SIZE - 1)
}
_ => Err(()),
}
}
}
/// Produce a comparison between the string column `column` and the string
/// value `text` that makes it obvious to Postgres' optimizer that it can
/// first consult the partial index on `left(column, STRING_PREFIX_SIZE)`
/// instead of going straight to a sequential scan of the underlying table.
/// We do this by writing the comparison `column op text` in a way that
/// involves `left(column, STRING_PREFIX_SIZE)`
struct PrefixComparison<'a> {
op: Comparison,
kind: PrefixType<'a>,
column: &'a Column,
text: &'a Value,
}
impl<'a> PrefixComparison<'a> {
fn new(op: Comparison, column: &'a Column, text: &'a Value) -> QueryResult<Self> {
let kind = PrefixType::new(column)?;
Ok(Self {
op,
kind,
column,
text,
})
}
fn push_value_prefix(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
match self.kind {
PrefixType::String(column) => {
out.push_sql("left(");
QueryValue(self.text, &column.column_type).walk_ast(out.reborrow())?;
out.push_sql(", ");
out.push_sql(&STRING_PREFIX_SIZE.to_string());
out.push_sql(")");
}
PrefixType::Bytes(column) => {
out.push_sql("substring(");
QueryValue(self.text, &column.column_type).walk_ast(out.reborrow())?;
out.push_sql(", 1, ");
out.push_sql(&BYTE_ARRAY_PREFIX_SIZE.to_string());
out.push_sql(")");
}
}
Ok(())
}
fn push_prefix_cmp(&self, op: Comparison, mut out: AstPass<Pg>) -> QueryResult<()> {
self.kind.push_column_prefix(&mut out)?;
out.push_sql(op.as_str());
self.push_value_prefix(out.reborrow())
}
fn push_full_cmp(&self, op: Comparison, mut out: AstPass<Pg>) -> QueryResult<()> {
out.push_identifier(self.column.name.as_str())?;
out.push_sql(op.as_str());
QueryValue(self.text, &self.column.column_type).walk_ast(out)
}
}
impl<'a> QueryFragment<Pg> for PrefixComparison<'a> {
fn walk_ast(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
use Comparison::*;
// For the various comparison operators, we want to write the condition
// `column op text` in a way that lets Postgres use the index on
// `left(column, STRING_PREFIX_SIZE)`. If at all possible, we also want
// the condition in a form that only uses the index, or if that's not
// possible, in a form where Postgres can first reduce the number of
// rows where a full comparison between `column` and `text` is needed
// by consulting the index.
//
// To ease notation, let `N = STRING_PREFIX_SIZE` and write a string stored in
// `column` as `uv` where `len(u) <= N`; that means that `v` is only
// nonempty if `len(uv) > N`. We similarly split `text` into `st` where
// `len(s) <= N`. In other words, `u = left(column, N)` and
// `s = left(text, N)`
//
// In all these comparisons, if `len(st) <= N - 1`, we can reduce
// checking `uv op st` to `u op s`, since in that case `t` is the empty
// string, we have `uv op s`. If `len(uv) <= N - 1`, then `v` will
// also be the empty string. If `len(uv) >= N`, then `len(u) = N`,
// and since `u` will be one character longer than `s`, that character
// will decide the outcome of `u op s`, even if `u` and `s` agree on
// the first `N-1` characters.
//
// For equality, we can expand `uv = st` into `u = s && uv = st` which
// lets Postgres use the index for the first comparison, and `uv = st`
// only needs to be checked for rows that pass the check on the index.
//
// For inequality, we can write `uv != st` as `u != s || uv != st`,
// but that doesn't buy us much since Postgres always needs to check
// `uv != st`, for which the index is of little help.
//
// For `op` either `<` or `>`, we have
// uv op st <=> u op s || u = s && uv op st
//
// For `op` either `<=` or `>=`, we can write (using '<=' as an example)
// uv <= st <=> u < s || u = s && uv <= st
let large = self.kind.is_large(&self.text).map_err(|()| {
constraint_violation!(
"column {} has type {} and can't be compared with the value `{}` using {}",
self.column.name(),
self.column.column_type().sql_type(),
self.text,
self.op.as_str()
)
})?;
match self.op {
Equal => {
if large {
out.push_sql("(");
self.push_prefix_cmp(self.op, out.reborrow())?;
out.push_sql(" and ");
self.push_full_cmp(self.op, out.reborrow())?;
out.push_sql(")");
} else {
self.push_prefix_cmp(self.op, out.reborrow())?;
}
}
Match => {
self.push_full_cmp(self.op, out.reborrow())?;
}
NotEqual => {
if large {
self.push_full_cmp(self.op, out.reborrow())?;
} else {
self.push_prefix_cmp(self.op, out.reborrow())?;
}
}
LessOrEqual | Less | GreaterOrEqual | Greater => {
let prefix_op = match self.op {
LessOrEqual => Less,
GreaterOrEqual => Greater,
op => op,
};
if large {
out.push_sql("(");
self.push_prefix_cmp(prefix_op, out.reborrow())?;
out.push_sql(" or (");
self.push_prefix_cmp(Equal, out.reborrow())?;
out.push_sql(" and ");
self.push_full_cmp(self.op, out.reborrow())?;
out.push_sql("))");
} else {
self.push_prefix_cmp(self.op, out.reborrow())?;
}
}
}
Ok(())
}
}
/// A `QueryFilter` adds the conditions represented by the `filter` to
/// the `where` clause of a SQL query. The attributes mentioned in
/// the `filter` must all come from the given `table`, which is used to
/// map GraphQL names to column names, and to determine the type of the
/// column an attribute refers to
#[derive(Debug, Clone)]
pub struct QueryFilter<'a> {
filter: &'a EntityFilter,
layout: &'a Layout,
table: &'a Table,
table_prefix: &'a str,
block: BlockNumber,
}
/// String representation that is useful for debugging when `walk_ast` fails
impl<'a> fmt::Display for QueryFilter<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.filter)
}
}
impl<'a> QueryFilter<'a> {
pub fn new(
filter: &'a EntityFilter,
table: &'a Table,
layout: &'a Layout,
block: BlockNumber,
) -> Result<Self, StoreError> {
Self::valid_attributes(filter, table, layout, false)?;
Ok(QueryFilter {
filter,
table,
layout,
block,
table_prefix: "c.",
})
}
fn valid_attributes(
filter: &'a EntityFilter,
table: &'a Table,
layout: &'a Layout,
child_filter_ancestor: bool,
) -> Result<(), StoreError> {
use EntityFilter::*;
match filter {
And(filters) | Or(filters) => {
for filter in filters {
Self::valid_attributes(filter, table, layout, child_filter_ancestor)?;
}
}
Child(child) => {
if child_filter_ancestor {
return Err(StoreError::QueryExecutionError(
"Child filters can not be nested".to_string(),
));
}
if child.derived {
let derived_table = layout.table_for_entity(&child.entity_type)?;
// Make sure that the attribute name is valid for the given table
derived_table.column_for_field(child.attr.as_str())?;
Self::valid_attributes(&child.filter, derived_table, layout, true)?;
} else {
// Make sure that the attribute name is valid for the given table
table.column_for_field(child.attr.as_str())?;
Self::valid_attributes(
&child.filter,
layout.table_for_entity(&child.entity_type)?,
layout,
true,
)?;
}
}
// This is a special case since we want to allow passing "block" column filter, but we dont
// want to fail/error when this is passed here, since this column is not really an entity column.
ChangeBlockGte(..) => {}
Contains(attr, _)
| ContainsNoCase(attr, _)
| NotContains(attr, _)
| NotContainsNoCase(attr, _)
| Equal(attr, _)
| Not(attr, _)
| GreaterThan(attr, _)
| LessThan(attr, _)
| GreaterOrEqual(attr, _)
| LessOrEqual(attr, _)
| In(attr, _)
| NotIn(attr, _)
| StartsWith(attr, _)
| StartsWithNoCase(attr, _)
| NotStartsWith(attr, _)
| NotStartsWithNoCase(attr, _)
| EndsWith(attr, _)
| EndsWithNoCase(attr, _)
| NotEndsWith(attr, _)
| NotEndsWithNoCase(attr, _) => {
table.column_for_field(attr)?;
}
}
Ok(())
}
fn with(&self, filter: &'a EntityFilter) -> Self {
QueryFilter {
filter,
table: self.table,
layout: self.layout,
block: self.block,
table_prefix: self.table_prefix.clone(),
}
}
fn child(
&self,
attribute: &Attribute,
entity_type: &'a EntityType,
filter: &'a EntityFilter,
derived: bool,
mut out: AstPass<Pg>,
) -> QueryResult<()> {
let child_table = self
.layout
.table_for_entity(entity_type)
.expect("Table for child entity not found");
let child_prefix = "i.";
let parent_prefix = "c.";
out.push_sql("exists (select 1 from ");
out.push_sql(child_table.qualified_name.as_str());
out.push_sql(" as i");
out.push_sql(" where ");