/
noria_connector.rs
1906 lines (1721 loc) · 67.3 KB
/
noria_connector.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
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::sync::{atomic, Arc};
use itertools::Itertools;
use nom_sql::analysis::visit::Visitor;
use nom_sql::{
self, ColumnConstraint, DeleteStatement, Expr, InsertStatement, Literal, Relation,
SelectStatement, SqlIdentifier, SqlQuery, UnaryOperator, UpdateStatement,
};
use readyset_client::consensus::{Authority, AuthorityControl};
use readyset_client::consistency::Timestamp;
use readyset_client::internal::LocalNodeIndex;
use readyset_client::recipe::changelist::{Change, ChangeList, IntoChanges};
use readyset_client::results::{ResultIterator, Results};
use readyset_client::{
ColumnSchema, ReadQuery, ReaderAddress, ReaderHandle, ReadySetHandle, SchemaType, Table,
TableOperation, View, ViewCreateRequest, ViewQuery,
};
use readyset_data::{DfType, DfValue, Dialect};
use readyset_errors::ReadySetError::{self, PreparedStatementMissing};
use readyset_errors::{
internal, internal_err, invalid_query, invariant_eq, table_err, unsupported, unsupported_err,
ReadySetResult,
};
use readyset_server::worker::readers::{CallResult, ReadRequestHandler};
use readyset_util::redacted::Sensitive;
use tokio::sync::RwLock;
use tracing::{error, info, instrument, trace, warn};
use crate::backend::SelectSchema;
use crate::rewrite::{self, ProcessedQueryParams};
use crate::utils;
type StatementID = u32;
#[derive(Clone)]
// Due to differences in data type sizes, the large_enum_variant Clippy warning was being emitted
// for this type, but only when compiling for aarch64 targets.
#[cfg_attr(target_arch = "aarch64", allow(clippy::large_enum_variant))]
pub(crate) enum PreparedStatement {
Select(PreparedSelectStatement),
Insert(nom_sql::InsertStatement),
Update(nom_sql::UpdateStatement),
Delete(DeleteStatement),
}
#[derive(Clone)]
pub(crate) struct PreparedSelectStatement {
name: Relation,
processed_query_params: ProcessedQueryParams,
}
impl fmt::Debug for PreparedStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
// FIXME(REA-2168): Use correct dialect.
match self {
PreparedStatement::Select(PreparedSelectStatement { name, .. }) => {
write!(f, "{}", name.display(nom_sql::Dialect::MySQL),)
}
PreparedStatement::Insert(s) => write!(f, "{}", s.display(nom_sql::Dialect::MySQL)),
PreparedStatement::Update(s) => write!(f, "{}", s.display(nom_sql::Dialect::MySQL)),
PreparedStatement::Delete(s) => write!(f, "{}", s.display(nom_sql::Dialect::MySQL)),
}
}
}
/// Wrapper around a NoriaBackendInner which may not have been successfully
/// created. When this is the case, this wrapper allows returning an error
/// from any call that requires NoriaBackendInner through an error
/// returned by `get_mut`.
pub struct NoriaBackend {
inner: Option<NoriaBackendInner>,
}
impl NoriaBackend {
fn get_mut(&mut self) -> ReadySetResult<&mut NoriaBackendInner> {
// TODO(ENG-707): Support retrying to create a backend in the future.
self.inner
.as_mut()
.ok_or_else(|| internal_err!("Failed to create a Noria backend."))
}
}
pub struct NoriaBackendInner {
noria: ReadySetHandle,
tables: BTreeMap<Relation, Table>,
views: BTreeMap<Relation, View>,
/// The server can handle (non-parameterized) LIMITs and (parameterized) OFFSETs in the
/// dataflow graph
server_supports_pagination: bool,
}
macro_rules! noria_await {
($self:expr, $fut:expr) => {{
let noria = &mut $self.noria;
futures_util::future::poll_fn(|cx| noria.poll_ready(cx)).await?;
$fut.await
}};
}
impl NoriaBackendInner {
async fn new(ch: ReadySetHandle, server_supports_pagination: bool) -> Self {
NoriaBackendInner {
tables: BTreeMap::new(),
views: BTreeMap::new(),
noria: ch,
server_supports_pagination,
}
}
async fn get_noria_table(&mut self, table: &Relation) -> ReadySetResult<&mut Table> {
if !self.tables.contains_key(table) {
let t = noria_await!(self, self.noria.table(table.clone()))?;
self.tables.insert(table.to_owned(), t);
}
Ok(self.tables.get_mut(table).unwrap())
}
/// If `invalidate_cache` is passed, the view cache, `views` will be ignored and a view will be
/// retrieved from noria.
async fn get_noria_view<'a>(
&'a mut self,
view: &Relation,
invalidate_cache: bool,
) -> ReadySetResult<&'a mut View> {
if invalidate_cache {
self.views.remove(view);
}
if !self.views.contains_key(view) {
let vh = noria_await!(self, self.noria.view(view.clone()))?;
self.views.insert(view.to_owned(), vh);
}
Ok(self.views.get_mut(view).unwrap())
}
}
#[derive(Debug, Clone)]
pub struct SelectPrepareResultInner {
pub statement_id: StatementID,
pub params: Vec<ColumnSchema>,
pub schema: Vec<ColumnSchema>,
}
/// Result of preparing a statement against ReadySet
#[derive(Debug, Clone)]
pub enum SelectPrepareResult {
/// Statement can be executed against ReadySet but we do not know the schema because it does
/// not exist in dataflow. This variant is not useful without an upstream connection.
///
/// This variant will be returned when the statement we are preparing reuses the cache of
/// another query. We cannot return a prepared statement response to the client using this
/// variant by itself, because we cannot determine the correct parameter and returned column
/// metadata (since the query itself is not cached in dataflow). Instead, we must form the
/// prepared statement response by retrieving the correct metadata from the upstream
/// prepared statement response.
NoSchema(StatementID),
/// The statement is cached in dataflow and we have the schema.
Schema(SelectPrepareResultInner),
}
#[derive(Debug, Clone)]
pub enum PrepareResult {
Select(SelectPrepareResult),
Insert {
statement_id: StatementID,
params: Vec<ColumnSchema>,
schema: Vec<ColumnSchema>,
},
Update {
statement_id: StatementID,
params: Vec<ColumnSchema>,
},
Delete {
statement_id: StatementID,
params: Vec<ColumnSchema>,
},
}
impl PrepareResult {
/// Get the noria statement id for this statement
pub fn statement_id(&self) -> StatementID {
match self {
PrepareResult::Select(SelectPrepareResult::Schema(SelectPrepareResultInner {
statement_id,
..
}))
| PrepareResult::Select(SelectPrepareResult::NoSchema(statement_id))
| PrepareResult::Insert { statement_id, .. }
| PrepareResult::Delete { statement_id, .. }
| PrepareResult::Update { statement_id, .. } => *statement_id,
}
}
}
/// A single row in the variable table associated with [`QueryResult::MetaVariables`].
#[derive(Debug)]
pub struct MetaVariable {
/// The variable name.
pub name: SqlIdentifier,
/// The value associated with the variable.
pub value: String,
}
impl<N: Into<SqlIdentifier>, V: Into<String>> From<(N, V)> for MetaVariable {
fn from((name, value): (N, V)) -> Self {
MetaVariable {
name: name.into(),
value: value.into(),
}
}
}
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum QueryResult<'a> {
Empty,
Insert {
num_rows_inserted: u64,
first_inserted_id: u64,
},
Select {
rows: ResultIterator,
schema: SelectSchema<'a>,
},
Update {
num_rows_updated: u64,
last_inserted_id: u64,
},
Delete {
num_rows_deleted: u64,
},
/// A metadata table returned as a response to eg an EXPLAIN query. Unlike
/// [`QueryResult::MetaVariables`] it will format the output as a table with a single row,
/// where the columns names correspond to the [`MetaVariable`] names.
Meta(Vec<MetaVariable>),
/// A table of variables returned as a response to a SHOW READYSET STATUS query.
MetaVariables(Vec<MetaVariable>),
/// A table of variables returned as a response to a SHOW READYSET STATUS query.
/// The first MetaVariable serves as the column headers
MetaWithHeader(Vec<MetaVariable>),
}
impl<'a> QueryResult<'a> {
pub fn from_owned(schema: SelectSchema<'a>, data: Vec<Results>) -> Self {
QueryResult::Select {
schema,
rows: ResultIterator::owned(data),
}
}
pub fn empty(schema: SelectSchema<'a>) -> Self {
QueryResult::Select {
schema,
rows: ResultIterator::owned(vec![]),
}
}
pub fn from_iter(schema: SelectSchema<'a>, rows: ResultIterator) -> Self {
QueryResult::Select { schema, rows }
}
#[inline]
pub fn into_owned(self) -> QueryResult<'static> {
match self {
QueryResult::Select { schema, rows } => QueryResult::Select {
schema: schema.into_owned(),
rows,
},
// Have to manually pass each variant to convince rustc that the
// returned type is really owned
QueryResult::Empty => QueryResult::Empty,
QueryResult::Insert {
num_rows_inserted,
first_inserted_id,
} => QueryResult::Insert {
num_rows_inserted,
first_inserted_id,
},
QueryResult::Update {
num_rows_updated,
last_inserted_id,
} => QueryResult::Update {
num_rows_updated,
last_inserted_id,
},
QueryResult::Delete { num_rows_deleted } => QueryResult::Delete { num_rows_deleted },
QueryResult::Meta(meta) => QueryResult::Meta(meta),
QueryResult::MetaVariables(vec) => QueryResult::MetaVariables(vec),
QueryResult::MetaWithHeader(vec) => QueryResult::MetaWithHeader(vec),
}
}
}
#[derive(Clone)]
/// Global and thread-local cache of view endpoints and prepared statements.
pub struct ViewCache {
/// Global cache of view endpoints and prepared statements.
global: Arc<RwLock<HashMap<ViewCreateRequest, Relation>>>,
/// Thread-local version of global cache (consulted first).
local: HashMap<ViewCreateRequest, Relation>,
}
impl ViewCache {
/// Construct a new ViewCache with a passed in global view cache.
pub fn new(global_cache: Arc<RwLock<HashMap<ViewCreateRequest, Relation>>>) -> ViewCache {
ViewCache {
global: global_cache,
local: HashMap::new(),
}
}
/// Registers a statement with the provided name into both the local and global view caches.
pub async fn register_statement(&mut self, name: &Relation, view_request: ViewCreateRequest) {
self.local
.entry(view_request.clone())
.or_insert_with(|| name.clone());
self.global
.write()
.await
.entry(view_request)
.or_insert_with(|| name.clone());
}
/// Retrieves the name for the provided statement if it's in the cache. We first check local
/// cache, and if it's not there we check global cache. If it's in global but not local, we
/// backfill local cache before returning the result.
pub async fn statement_name(&mut self, view_request: &ViewCreateRequest) -> Option<Relation> {
let maybe_name = if let Some(name) = self.local.get(view_request) {
return Some(name.clone());
} else {
// Didn't find it in local, so let's check global.
let gc = self.global.read().await;
gc.get(view_request).cloned()
};
maybe_name.map(|n| {
// Backfill into local before we return.
self.local.insert(view_request.clone(), n.clone());
n
})
}
/// Removes the statement with the given name from both the global and local caches.
pub async fn remove_statement(&mut self, name: &Relation) {
self.local.retain(|_, v| v != name);
self.global.write().await.retain(|_, v| v != name);
}
/// Clears all statements from all caches
async fn clear(&mut self) {
self.local.clear();
self.global.write().await.clear();
}
/// Returns the original view create request based on a provided name if it exists in either the
/// local or global caches.
pub async fn view_create_request_from_name(
&self,
name: &Relation,
) -> Option<ViewCreateRequest> {
if let Some((v, _)) = self.local.iter().find(|(_, n)| *n == name) {
return Some(v.clone());
}
let gc = self.global.read().await;
gc.iter().find(|(_, n)| *n == name).map(|(v, _)| v.clone())
}
}
pub struct NoriaConnector {
inner: NoriaBackend,
auto_increments: Arc<RwLock<HashMap<Relation, atomic::AtomicUsize>>>,
/// Global and thread-local cache of view endpoints and prepared statements.
view_cache: ViewCache,
prepared_statement_cache: HashMap<StatementID, PreparedStatement>,
/// Set of views that have failed on previous requests. Separate from the backend
/// to allow returning references to schemas from views all the way to mysql-srv,
/// but on subsequent requests, do not use a failed view.
failed_views: HashSet<Relation>,
/// How to handle issuing reads against ReadySet. See [`ReadBehavior`].
read_behavior: ReadBehavior,
/// A read request handler that may be used to service reads from readers
/// on the same server.
read_request_handler: request_handler::LocalReadHandler,
/// SQL Dialect to pass to ReadySet as part of all migration requests
dialect: Dialect,
/// Dialect to use to parse and format all SQL strings
parse_dialect: nom_sql::Dialect,
/// Currently configured search path for schemas.
///
/// Note that the terminology used here is maximally general - while only PostgreSQL truly
/// supports a multi-element schema search path, the concept of "currently connected database"
/// in MySQL can be thought of as a schema search path that only has one element.
schema_search_path: Vec<SqlIdentifier>,
}
mod request_handler {
use readyset_server::worker::readers::ReadRequestHandler;
/// Since [`ReadRequestHandler`] contains some fields that aren't [`Sync`], this is a workaround
/// wrapper to make it safely [`Sync`], by ensuring that all accesses to the underlying
/// [`ReadRequestHandler`] are exclusive. This effectively makes sure that no references are
/// shared between threads ever. This is implemented in a submodule so that the private fields
/// are not accidentally accessed without an exclusive reference.
#[derive(Clone)]
#[repr(transparent)]
pub(super) struct LocalReadHandler(Option<ReadRequestHandler>);
impl LocalReadHandler {
pub(super) fn new(handler: Option<ReadRequestHandler>) -> Self {
LocalReadHandler(handler)
}
#[inline]
pub(super) fn as_mut(&mut self) -> Option<&mut ReadRequestHandler> {
self.0.as_mut()
}
}
/// SAFETY: since all accesses to the inner field are exclusive, no references are ever shared
/// between threads.
unsafe impl Sync for LocalReadHandler {}
}
/// The read behavior used when executing a read against ReadySet.
#[derive(Clone, Copy)]
pub enum ReadBehavior {
/// If ReadySet is unable to immediately service the read due to a cache miss, block on the
/// response.
Blocking,
/// If ReadySet is unable to immediately service the read, return an error.
NonBlocking,
}
impl ReadBehavior {
fn is_blocking(&self) -> bool {
matches!(self, Self::Blocking)
}
}
/// Provides the necessary context to execute a select statement against noria, either for a
/// prepared or an ad-hoc query
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub(crate) enum ExecuteSelectContext<'ctx> {
Prepared {
q_id: u32,
params: &'ctx [DfValue],
},
AdHoc {
statement: nom_sql::SelectStatement,
create_if_missing: bool,
},
}
impl NoriaConnector {
#[allow(clippy::too_many_arguments)]
pub async fn new(
ch: ReadySetHandle,
auto_increments: Arc<RwLock<HashMap<Relation, atomic::AtomicUsize>>>,
query_cache: Arc<RwLock<HashMap<ViewCreateRequest, Relation>>>,
read_behavior: ReadBehavior,
dialect: Dialect,
parse_dialect: nom_sql::Dialect,
schema_search_path: Vec<SqlIdentifier>,
server_supports_pagination: bool,
) -> Self {
NoriaConnector::new_with_local_reads(
ch,
auto_increments,
query_cache,
read_behavior,
None,
dialect,
parse_dialect,
schema_search_path,
server_supports_pagination,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn new_with_local_reads(
ch: ReadySetHandle,
auto_increments: Arc<RwLock<HashMap<Relation, atomic::AtomicUsize>>>,
query_cache: Arc<RwLock<HashMap<ViewCreateRequest, Relation>>>,
read_behavior: ReadBehavior,
read_request_handler: Option<ReadRequestHandler>,
dialect: Dialect,
parse_dialect: nom_sql::Dialect,
schema_search_path: Vec<SqlIdentifier>,
server_supports_pagination: bool,
) -> Self {
let backend = NoriaBackendInner::new(ch, server_supports_pagination).await;
NoriaConnector {
inner: NoriaBackend {
inner: Some(backend),
},
auto_increments,
view_cache: ViewCache::new(query_cache),
prepared_statement_cache: HashMap::new(),
failed_views: HashSet::new(),
read_behavior,
read_request_handler: request_handler::LocalReadHandler::new(read_request_handler),
dialect,
parse_dialect,
schema_search_path,
}
}
pub(crate) async fn graphviz(
&mut self,
simplified: bool,
) -> ReadySetResult<QueryResult<'static>> {
let noria = &mut self.inner.get_mut()?.noria;
let (label, graphviz) = if simplified {
("SIMPLIFIED GRAPHVIZ", noria.simple_graphviz().await?)
} else {
("GRAPHVIZ", noria.graphviz().await?)
};
Ok(QueryResult::Meta(vec![(label, graphviz).into()]))
}
pub(crate) async fn explain_domains(&mut self) -> ReadySetResult<QueryResult<'static>> {
let domains = self.inner.get_mut()?.noria.domains().await?;
let schema = SelectSchema {
schema: Cow::Owned(vec![
ColumnSchema {
column: nom_sql::Column {
name: "domain".into(),
table: None,
},
column_type: DfType::DEFAULT_TEXT,
base: None,
},
ColumnSchema {
column: nom_sql::Column {
name: "worker".into(),
table: None,
},
column_type: DfType::DEFAULT_TEXT,
base: None,
},
]),
columns: Cow::Owned(vec!["domain".into(), "worker".into()]),
};
let mut data = domains
.into_iter()
.flat_map(|(di, shards)| {
shards
.into_iter()
.enumerate()
.flat_map(move |(shard, replicas)| {
replicas
.into_iter()
.enumerate()
.map(move |(replica, worker)| {
vec![
DfValue::from(format!("{di}.{shard}.{replica}")),
DfValue::from(
worker.map(|w| w.to_string()).unwrap_or_default(),
),
]
})
})
})
.collect::<Vec<_>>();
data.sort_by(|r1, r2| r1[1].cmp(&r2[1]));
Ok(QueryResult::from_owned(schema, vec![Results::new(data)]))
}
pub(crate) async fn list_create_cache_stmts(&mut self) -> ReadySetResult<Vec<String>> {
let noria = &mut self.inner.get_mut()?.noria;
Ok(noria
.verbose_views()
.await?
.into_iter()
.map(|stmt| stmt.display(self.parse_dialect).to_string())
.collect())
}
pub(crate) fn server_supports_pagination(&self) -> bool {
self.inner
.inner
.as_ref()
.map(|v| v.server_supports_pagination)
.unwrap_or(false)
}
// TODO(andrew): Allow client to map table names to NodeIndexes without having to query ReadySet
// repeatedly. Eventually, this will be responsibility of the TimestampService.
pub async fn node_index_of(&mut self, table_name: &str) -> ReadySetResult<LocalNodeIndex> {
let table_handle = self.inner.get_mut()?.noria.table(table_name).await?;
Ok(table_handle.node)
}
pub async fn handle_insert(
&mut self,
q: &nom_sql::InsertStatement,
) -> ReadySetResult<QueryResult<'_>> {
let table = &q.table;
// create a mutator if we don't have one for this table already
trace!(table = %table.display_unquoted(), "query::insert::access mutator");
let putter = self.inner.get_mut()?.get_noria_table(table).await?;
trace!("query::insert::extract schema");
let schema = putter
.schema()
.ok_or_else(|| internal_err!("no schema for table {}", table.display_unquoted()))?;
// set column names (insert schema) if not set
let q = match q.fields {
Some(_) => Cow::Borrowed(q),
None => {
let mut query = q.clone();
query.fields = Some(schema.fields.iter().map(|cs| cs.column.clone()).collect());
Cow::Owned(query)
}
};
let data: Vec<Vec<DfValue>> = q
.data
.iter()
.map(|row| {
row.iter()
.map(|expr| match expr {
Expr::Literal(lit) => DfValue::try_from(lit),
// Ad-hoc handle unary negation (for logictests, to allow them to insert
// negative values)
Expr::UnaryOp {
op: UnaryOperator::Neg,
rhs: box Expr::Literal(lit),
} => {
let val = DfValue::try_from(lit)?;
&val * &(-1).into()
}
_ => unsupported!("Only literal values are supported in expressions"),
})
.collect::<Result<Vec<_>, _>>()
})
.collect::<Result<Vec<_>, _>>()?;
self.do_insert(&q, data).await
}
pub async fn prepare_insert(
&mut self,
mut q: nom_sql::InsertStatement,
statement_id: u32,
) -> ReadySetResult<PrepareResult> {
trace!(table = %q.table.name, "insert::access mutator");
let mutator = self.inner.get_mut()?.get_noria_table(&q.table).await?;
trace!("insert::extract schema");
let schema = mutator
.schema()
.ok_or_else(|| internal_err!("Could not find schema for table {}", q.table.name))?
.fields
.iter()
.map(|cs| ColumnSchema::from_base(cs.clone(), q.table.clone(), self.dialect))
.collect::<Result<Vec<_>, _>>()?;
if q.fields.is_none() {
q.fields = Some(
mutator
.schema()
.as_ref()
.unwrap()
.fields
.iter()
.map(|cs| cs.column.clone())
.collect(),
);
}
let params: Vec<_> = {
// extract parameter columns -- easy here, since they must all be in the same table
let param_cols = utils::insert_statement_parameter_columns(&q);
param_cols
.into_iter()
.map(|c| {
schema
.iter()
.cloned()
.find(|mc| c.name == mc.column.name)
.ok_or_else(|| {
internal_err!(
"column {} missing in mutator schema",
c.display_unquoted()
)
})
})
.collect::<ReadySetResult<Vec<_>>>()?
};
// nothing more to do for an insert
// register a new prepared statement
trace!(id = statement_id, "insert::registered");
self.prepared_statement_cache
.insert(statement_id, PreparedStatement::Insert(q));
Ok(PrepareResult::Insert {
statement_id,
params,
schema,
})
}
pub(crate) async fn execute_prepared_insert(
&mut self,
q_id: u32,
params: &[DfValue],
) -> ReadySetResult<QueryResult<'_>> {
let prep: PreparedStatement = self
.prepared_statement_cache
.get(&q_id)
.ok_or(PreparedStatementMissing { statement_id: q_id })?
.clone();
trace!("delegate");
match prep {
PreparedStatement::Insert(ref q) => {
let table = &q.table;
let putter = self.inner.get_mut()?.get_noria_table(table).await?;
trace!("insert::extract schema");
let schema = putter.schema().ok_or_else(|| {
internal_err!("no schema for table {}", table.display_unquoted())
})?;
let rows = utils::extract_insert(q, params, schema, self.dialect)?;
self.do_insert(q, rows).await
}
_ => {
internal!(
"Execute_prepared_insert is being called for a non insert prepared statement."
)
}
}
}
pub(crate) async fn handle_delete(
&mut self,
q: &nom_sql::DeleteStatement,
) -> ReadySetResult<QueryResult<'_>> {
let cond = q
.where_clause
.as_ref()
.ok_or_else(|| unsupported_err!("only supports DELETEs with WHERE-clauses"))?;
// create a mutator if we don't have one for this table already
trace!(table = %q.table.name, "delete::access mutator");
let mutator = self.inner.get_mut()?.get_noria_table(&q.table).await?;
trace!("delete::extract schema");
let pkey = if let Some(cts) = mutator.schema() {
utils::get_primary_key(cts)
.into_iter()
.map(|(_, c)| c)
.collect::<Vec<_>>()
} else {
unsupported!("cannot delete from view");
};
trace!("delete::flatten conditionals");
match utils::flatten_conditional(cond, &pkey)? {
None => Ok(QueryResult::Delete {
num_rows_deleted: 0_u64,
}),
Some(ref flattened) if flattened.is_empty() => {
unsupported!("DELETE only supports WHERE-clauses on primary keys")
}
Some(flattened) => {
let count = flattened.len() as u64;
trace!("delete::execute");
for key in flattened {
if let Err(e) = mutator.delete(key).await {
error!(error = %e, "failed");
return Err(e);
};
}
trace!("delete::done");
Ok(QueryResult::Delete {
num_rows_deleted: count,
})
}
}
}
pub(crate) async fn handle_update<'a>(
&'a mut self,
q: &nom_sql::UpdateStatement,
) -> ReadySetResult<QueryResult<'a>> {
self.do_update(Cow::Borrowed(q), None).await
}
pub(crate) async fn prepare_update(
&mut self,
q: nom_sql::UpdateStatement,
statement_id: u32,
) -> ReadySetResult<PrepareResult> {
// ensure that we have schemas and endpoints for the query
trace!(table = %q.table.name, "update::access mutator");
let mutator = self.inner.get_mut()?.get_noria_table(&q.table).await?;
trace!("update::extract schema");
let table_schema = mutator
.schema()
.ok_or_else(|| internal_err!("Could not find schema for table {}", q.table.name))?;
// extract parameter columns
let params = utils::update_statement_parameter_columns(&q)
.into_iter()
.map(|c| {
table_schema
.fields
.iter()
// We know that only one table is mentioned, so no need to match on both table
// and name - just check name here
.find(|f| f.column.name == c.name)
.cloned()
.map(|cs| ColumnSchema::from_base(cs, q.table.clone(), self.dialect))
.transpose()?
.ok_or_else(|| internal_err!("Unknown column {}", c.display_unquoted()))
})
.collect::<Result<Vec<_>, _>>()?;
trace!(id = statement_id, "update::registered");
self.prepared_statement_cache
.insert(statement_id, PreparedStatement::Update(q));
Ok(PrepareResult::Update {
statement_id,
params,
})
}
pub(crate) async fn execute_prepared_update(
&mut self,
q_id: u32,
params: &[DfValue],
) -> ReadySetResult<QueryResult<'_>> {
let prep: PreparedStatement = self
.prepared_statement_cache
.get(&q_id)
.ok_or(PreparedStatementMissing { statement_id: q_id })?
.clone();
trace!("delegate");
match prep {
PreparedStatement::Update(q) => self.do_update(Cow::Owned(q), Some(params)).await,
_ => internal!(),
}
}
pub(crate) async fn prepare_delete(
&mut self,
q: DeleteStatement,
statement_id: u32,
) -> ReadySetResult<PrepareResult> {
// ensure that we have schemas and endpoints for the query
trace!(table = %q.table.name, "delete::access mutator");
let mutator = self.inner.get_mut()?.get_noria_table(&q.table).await?;
trace!("delete::extract schema");
let table_schema = mutator
.schema()
.ok_or_else(|| internal_err!("Could not find schema for table {}", q.table.name))?;
// extract parameter columns
let params = utils::delete_statement_parameter_columns(&q)
.into_iter()
.map(|c| {
table_schema
.fields
.iter()
// We know that only one table is mentioned, so no need to match on both table
// and name - just check name here
.find(|f| f.column.name == c.name)
.cloned()
.map(|cs| ColumnSchema::from_base(cs, q.table.clone(), self.dialect))
.transpose()?
.ok_or_else(|| internal_err!("Unknown column {}", c.display_unquoted()))
})
.collect::<Result<Vec<_>, _>>()?;
trace!(id = statement_id, "delete::registered");
self.prepared_statement_cache
.insert(statement_id, PreparedStatement::Delete(q));
Ok(PrepareResult::Delete {
statement_id,
params,
})
}
pub(crate) async fn execute_prepared_delete(
&mut self,
q_id: u32,
params: &[DfValue],
) -> ReadySetResult<QueryResult<'_>> {
let prep: PreparedStatement = self
.prepared_statement_cache
.get(&q_id)
.ok_or(PreparedStatementMissing { statement_id: q_id })?
.clone();
trace!("delegate");
match prep {
PreparedStatement::Delete(q) => self.do_delete(Cow::Owned(q), Some(params)).await,
_ => internal!(),
}
}
/// Calls the `extend_recipe` endpoint on ReadySet with the given query.
pub(crate) async fn handle_table_operation<C>(
&mut self,
changes: C,
) -> ReadySetResult<QueryResult<'_>>
where
C: IntoChanges,
{
// TODO(malte): we should perhaps check our usual caches here, rather than just blindly
// doing a migration on ReadySet ever time. On the other hand, CREATE TABLE is rare...
noria_await!(
self.inner.get_mut()?,
self.inner.get_mut()?.noria.extend_recipe(
ChangeList::from_changes(changes, self.dialect)
.with_schema_search_path(self.schema_search_path.clone())
)
)?;
Ok(QueryResult::Empty)
}
/// Returns status provided by the Controller and persisted in the Authority. Also appends
/// additional_meta provided by the caller to the status.
pub(crate) async fn readyset_status(
&mut self,
authority: &Authority,
mut additional_meta: Vec<(String, String)>,
) -> ReadySetResult<QueryResult<'static>> {
let mut status =
match noria_await!(self.inner.get_mut()?, self.inner.get_mut()?.noria.status()) {
Ok(s) => <Vec<(String, String)>>::from(s),
Err(_) => vec![(
"ReadySet Controller Status".to_string(),
"Unavailable".to_string(),
)],
};
// Helper function for formatting
fn val_or_null<T: ToString>(val: Option<T>) -> String {
if let Some(v) = val {
v.to_string()
} else {
"NULL".to_string()
}
}
if let Ok(Some(stats)) = authority.persistent_stats().await {
status.push((
"Last started Controller".to_string(),
val_or_null(stats.last_controller_startup),
));
status.push((
"Last completed snapshot".to_string(),
val_or_null(stats.last_completed_snapshot),
));
status.push((
"Last started replication".to_string(),
val_or_null(stats.last_started_replication),
));
if let Some(err) = stats.last_replicator_error {
status.push(("Last replicator error".to_string(), err))
}
}
status.append(&mut additional_meta);
Ok(QueryResult::MetaVariables(
status.into_iter().map(MetaVariable::from).collect(),
))
}
/// Query the status of a pending migration identified by the given `migration_id`. Once the
/// function returns a result (completed or an error), calling again with the same id will lead
/// to undefined behavior.
pub(crate) async fn migration_status(
&mut self,
id: u64,
) -> ReadySetResult<QueryResult<'static>> {
let status = noria_await!(