-
Notifications
You must be signed in to change notification settings - Fork 112
/
snapshot.rs
1200 lines (1090 loc) · 43.2 KB
/
snapshot.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::convert::{TryFrom, TryInto};
use std::error::Error;
use std::fmt::{self, Display};
use std::future;
use std::time::Instant;
use futures::future::join_all;
use futures::{pin_mut, StreamExt, TryFutureExt};
use itertools::Itertools;
use metrics::register_gauge;
use nom_sql::{
parse_key_specification_string, parse_sql_type, Column, ColumnConstraint, ColumnSpecification,
CreateTableBody, CreateTableStatement, Dialect, Relation, SqlIdentifier, TableKey,
};
use postgres_types::{accepts, FromSql, Kind, Type};
use readyset_client::metrics::recorded;
use readyset_client::recipe::changelist::{Change, ChangeList};
use readyset_client::replication::ReplicationOffset;
use readyset_client::TableOperation;
use readyset_data::{DfType, DfValue, Dialect as DataDialect, PgEnumMetadata};
use readyset_errors::{internal, internal_err, unsupported, ReadySetError, ReadySetResult};
use tokio_postgres as pgsql;
use tracing::{debug, info, info_span, trace, warn, Instrument};
use super::connector::CreatedSlot;
use super::PostgresPosition;
use crate::db_util::CreateSchema;
use crate::table_filter::TableFilter;
const BATCH_SIZE: usize = 1024; // How many queries to buffer before pushing to ReadySet
macro_rules! get_transaction {
($self:expr) => {
$self
.transaction
.as_ref()
.expect("Using snapshot transaction after commit")
};
}
pub struct PostgresReplicator<'a> {
/// This is the underlying (regular) PostgreSQL transaction used for most queries.
pub(crate) transaction: Option<pgsql::Transaction<'a>>,
/// A pool to be used for parallelizing snapshot tasks.
pub(crate) pool: deadpool_postgres::Pool,
pub(crate) noria: &'a mut readyset_client::ReadySetHandle,
/// Filters out tables we are not interested in
pub(crate) table_filter: TableFilter,
}
#[derive(Debug)]
enum TableKind {
RegularTable,
View,
PartitionedTable,
}
#[derive(Debug, Clone)]
enum ConstraintKind {
PrimaryKey,
UniqueKey,
ForeignKey,
Other(u8),
}
#[derive(Debug)]
struct TableEntry {
schema: String,
name: String,
oid: u32,
}
#[derive(Debug, Clone)]
struct TableDescription {
name: Relation,
columns: Vec<ColumnEntry>,
constraints: Vec<ConstraintEntry>,
}
#[derive(Debug, Clone)]
struct ColumnEntry {
name: String,
sql_type: String,
not_null: bool,
/// The [`Type`] of this column
pg_type: Type,
}
#[derive(Debug, Clone)]
struct ConstraintEntry {
#[allow(dead_code)]
name: String,
definition: TableKey,
#[allow(dead_code)]
kind: Option<ConstraintKind>,
}
#[derive(Debug)]
struct EnumVariant {
#[allow(dead_code)]
oid: u32,
label: String,
}
#[derive(Clone, Debug)]
struct CustomTypeEntry {
oid: u32,
array_oid: u32,
name: String,
schema: String,
}
/// Newtype struct to allow converting TableKey from a SQL column in a way that lets us wrap the
/// error in a pgsql::Error
struct ConstraintDefinition(TableKey);
impl<'a> FromSql<'a> for ConstraintDefinition {
fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn Error + Sync + Send>> {
let s = String::from_sql(ty, raw)?;
Ok(ConstraintDefinition(parse_key_specification_string(
Dialect::PostgreSQL,
s,
)?))
}
accepts!(TEXT);
}
impl TryFrom<pgsql::Row> for ColumnEntry {
type Error = ReadySetError;
fn try_from(row: pgsql::Row) -> Result<Self, Self::Error> {
let type_oid = row.try_get(4 /* pg_type.oid */)?;
let typtype_to_kind = |typtype: i8| -> ReadySetResult<Kind> {
match typtype as u8 as char {
'b' => Ok(Kind::Simple),
'c' => unsupported!("Composite types are not supported"),
'd' => unsupported!("Domain types are not supported"),
'e' => Ok(Kind::Enum(row.try_get(12 /* array_agg(e.enumlabel)... */)?)),
'p' => Ok(Kind::Pseudo),
'r' => unsupported!("Range types are not supported"),
'm' => unsupported!("Multirange types are not supported"),
c => internal!("Unknown value '{c}' in pg_catalog.pg_type.typtype"),
}
};
let pg_type = if let Some(t) = Type::from_oid(type_oid) {
t
} else {
let kind = if row.try_get(7 /* is_array */)? {
Kind::Array(Type::new(
row.try_get(8)?,
row.try_get(9)?,
typtype_to_kind(row.try_get(10)?)?,
row.try_get(11)?,
))
} else {
typtype_to_kind(row.try_get(5)?)?
};
Type::new(
row.try_get(3 /* pg_type.typname */)?,
type_oid,
kind,
row.try_get(6 /* pg_namespace.nspname */)?,
)
};
Ok(ColumnEntry {
name: row.try_get(0 /* pg_attribute.attname */)?,
not_null: row.try_get(1 /* pg_attribute.attnotnull */)?,
sql_type: row.try_get(3)?,
pg_type,
})
}
}
impl Display for ColumnEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} {}{}",
Dialect::PostgreSQL.quote_identifier(&self.name),
self.sql_type,
if self.not_null { " NOT NULL" } else { "" },
)
}
}
impl TryFrom<pgsql::Row> for ConstraintEntry {
type Error = pgsql::Error;
fn try_from(row: pgsql::Row) -> Result<Self, Self::Error> {
let ConstraintDefinition(definition) = row.try_get(1)?;
Ok(ConstraintEntry {
name: row.try_get(0)?,
definition,
kind: row.try_get::<_, Option<i8>>(2)?.map(|c| match c as u8 {
b'f' => ConstraintKind::ForeignKey,
b'p' => ConstraintKind::PrimaryKey,
b'u' => ConstraintKind::UniqueKey,
b => ConstraintKind::Other(b),
}),
})
}
}
impl Display for ConstraintEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.definition.display(Dialect::PostgreSQL))
}
}
impl TryFrom<pgsql::Row> for TableEntry {
type Error = pgsql::Error;
fn try_from(row: pgsql::Row) -> Result<Self, Self::Error> {
Ok(TableEntry {
schema: row.try_get(0)?,
oid: row.try_get(1)?,
name: row.try_get(2)?,
})
}
}
impl TryFrom<pgsql::Row> for CustomTypeEntry {
type Error = pgsql::Error;
fn try_from(row: pgsql::Row) -> Result<Self, Self::Error> {
let oid = row.try_get(0)?;
let array_oid = row.try_get(1)?;
let name = row.try_get(2)?;
let schema = row.try_get(3)?;
Ok(CustomTypeEntry {
oid,
array_oid,
name,
schema,
})
}
}
impl TryFrom<pgsql::Row> for EnumVariant {
type Error = pgsql::Error;
fn try_from(row: pgsql::Row) -> Result<Self, Self::Error> {
let oid = row.try_get(0)?;
let label = row.try_get(1)?;
Ok(EnumVariant { oid, label })
}
}
impl CustomTypeEntry {
async fn get_variants<'a>(
&self,
transaction: &'a pgsql::Transaction<'a>,
) -> Result<Vec<EnumVariant>, pgsql::Error> {
let query = r"
SELECT oid, enumlabel
FROM pg_enum
WHERE enumtypid = $1
ORDER BY enumsortorder ASC
";
let res = transaction.query(query, &[&self.oid]).await?;
res.into_iter().map(TryInto::try_into).collect()
}
pub(crate) fn into_relation(self) -> Relation {
Relation {
schema: Some(self.schema.into()),
name: self.name.into(),
}
}
}
impl TableEntry {
async fn get_columns<'a>(
oid: u32,
transaction: &'a pgsql::Transaction<'a>,
) -> Result<Vec<ColumnEntry>, ReadySetError> {
let query = r#"
SELECT
a.attname,
a.attnotnull,
t.typname,
CASE
WHEN t.typtype = 'e'
THEN format('"%s"."%s"', tn.nspname, t.typname)
WHEN member_t.oid IS NOT NULL AND member_t.typtype = 'e'
THEN format('"%s"."%s"[]', member_tn.nspname, member_t.typname)
ELSE pg_catalog.format_type(a.atttypid, a.atttypmod)
END AS sql_type,
t.oid,
t.typtype,
tn.nspname,
member_t.oid IS NOT NULL AS is_array,
member_t.typname,
member_t.oid,
member_t.typtype,
member_tn.nspname,
(SELECT array_agg(e.enumlabel ORDER BY e.enumsortorder ASC)
FROM pg_enum e
WHERE (member_t.oid IS NULL AND (e.enumtypid = t.oid)) OR e.enumtypid = member_t.oid)
FROM pg_catalog.pg_attribute a
JOIN pg_catalog.pg_type t ON a.atttypid = t.oid
JOIN pg_catalog.pg_namespace tn ON t.typnamespace = tn.oid
LEFT JOIN pg_catalog.pg_type member_t ON t.typelem = member_t.oid
LEFT JOIN pg_catalog.pg_namespace member_tn ON member_t.typnamespace = member_tn.oid
WHERE a.attrelid = $1 AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
"#;
let columns = transaction.query(query, &[&oid]).await?;
columns.into_iter().map(TryInto::try_into).collect()
}
async fn get_constraints<'a>(
oid: u32,
transaction: &'a pgsql::Transaction<'a>,
) -> Result<Vec<ConstraintEntry>, pgsql::Error> {
let query = r"
SELECT c2.relname, pg_catalog.pg_get_constraintdef(con.oid, true), contype
FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
LEFT JOIN pg_catalog.pg_constraint con ON (conrelid = i.indrelid AND conindid = i.indexrelid AND contype IN ('f','p','u'))
WHERE c.oid = $1
AND c.oid = i.indrelid
AND i.indexrelid = c2.oid
AND pg_catalog.pg_get_constraintdef(con.oid, true) IS NOT NULL
ORDER BY i.indisprimary DESC, c2.relname;
";
let constraints = transaction.query(query, &[&oid]).await?;
constraints.into_iter().map(TryInto::try_into).collect()
}
async fn get_table<'a>(
&self,
transaction: &'a pgsql::Transaction<'a>,
) -> Result<TableDescription, ReadySetError> {
let columns = Self::get_columns(self.oid, transaction)
.await
.map_err(|e| {
ReadySetError::TableError {
table: Relation {
schema: Some(self.schema.clone().into()),
name: self.name.clone().into(),
},
source: Box::new(e),
}
.context("when loading columns for the table")
})?;
let constraints = Self::get_constraints(self.oid, transaction)
.await
.map_err(|e| {
ReadySetError::TableError {
table: Relation {
schema: Some(self.schema.clone().into()),
name: self.name.clone().into(),
},
source: Box::new(ReadySetError::ReplicationFailed(e.to_string())),
}
.context("when loading constraints")
})?;
Ok(TableDescription {
name: Relation {
schema: Some(self.schema.clone().into()),
name: self.name.clone().into(),
},
columns,
constraints,
})
}
async fn get_create_view<'a>(
self,
transaction: &'a pgsql::Transaction<'a>,
) -> Result<String, pgsql::Error> {
let query = "SELECT definition FROM pg_catalog.pg_views WHERE viewname=$1";
let mut create_view = format!("CREATE VIEW \"{}\" AS", self.name);
for col in transaction.query(query, &[&self.name]).await? {
create_view.push_str(col.try_get(0)?);
}
Ok(create_view)
}
}
impl Display for TableDescription {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(
f,
"CREATE TABLE {} (",
self.name.display(Dialect::PostgreSQL)
)?;
write!(
f,
"{}",
itertools::join(
self.columns
.iter()
.map(ToString::to_string)
.chain(self.constraints.iter().map(ToString::to_string)),
",\n"
)
)?;
write!(f, ");")
}
}
impl TableDescription {
fn schema(&self) -> ReadySetResult<&SqlIdentifier> {
self.name
.schema
.as_ref()
.ok_or_else(|| internal_err!("All tables must have a schema in the replicator"))
}
fn try_into_change(self) -> ReadySetResult<Change> {
Ok(Change::CreateTable(CreateTableStatement {
if_not_exists: false,
table: self.name.clone(),
body: Ok(CreateTableBody {
fields: self
.columns
.into_iter()
.map(|c| {
Ok(ColumnSpecification {
column: Column {
name: c.name.into(),
table: Some(self.name.clone()),
},
sql_type: parse_sql_type(Dialect::PostgreSQL, c.sql_type)
.map_err(|e| internal_err!("Could not parse SQL type: {e}"))?,
constraints: if c.not_null {
vec![ColumnConstraint::NotNull]
} else {
vec![]
},
comment: None,
})
})
.collect::<ReadySetResult<_>>()?,
keys: if self.constraints.is_empty() {
None
} else {
Some(self.constraints.into_iter().map(|c| c.definition).collect())
},
}),
options: Ok(vec![]),
}))
}
/// Copy a table's contents from PostgreSQL to ReadySet
async fn dump<'a>(
&self,
transaction: &'a deadpool_postgres::Transaction<'a>,
mut noria_table: readyset_client::Table,
snapshot_report_interval_secs: u16,
wal_position: &ReplicationOffset,
) -> ReadySetResult<()> {
let mut cnt = 0;
let nrows = transaction
.query_one(
format!(
"SELECT count(*) AS nrows FROM \"{}\".\"{}\"",
self.schema()?,
&self.name.name,
)
.as_str(),
&[],
)
.await?
.try_get::<_, i64>("nrows")?;
// The most efficient way to copy an entire table is COPY BINARY
let query = format!(
"COPY \"{}\".\"{}\" TO stdout BINARY",
self.schema()?,
self.name.name
);
let rows = transaction.copy_out(query.as_str()).await?;
let type_map: Vec<_> = self.columns.iter().map(|c| c.pg_type.clone()).collect();
let binary_row_batches = pgsql::binary_copy::BinaryCopyOutStream::new(rows, &type_map)
.chunks(BATCH_SIZE)
.peekable();
pin_mut!(binary_row_batches);
info!(rows = %nrows, "Snapshotting started");
let progress_percentage_metric: metrics::Gauge = register_gauge!(
recorded::REPLICATOR_SNAPSHOT_PERCENT,
"schema" => self.schema()?.to_string(),
"name" => self.name.name.to_string()
);
let start_time = Instant::now();
let mut last_report_time = start_time;
let snapshot_report_interval_secs = snapshot_report_interval_secs as u64;
let mut set_replication_offset_and_snapshot_mode = false;
while let Some(batch) = binary_row_batches.as_mut().next().await {
let cnt_copy = cnt;
let batch_size = batch.len();
let noria_rows_iter = batch
.into_iter()
.enumerate()
.map(|(index_within_batch, row)| {
row.map_err(ReadySetError::from).and_then(|row| {
(0..type_map.len())
.map(|i| row.try_get::<DfValue>(i))
.collect::<Result<Vec<_>, _>>()
.map_err(|err| {
progress_percentage_metric.set(0.0);
ReadySetError::ReplicationFailed(format!(
"Failed converting to DfValue, table: {}, row: {}, err: {}",
noria_table.table_name().display(Dialect::PostgreSQL),
cnt_copy + index_within_batch,
err
))
})
})
});
cnt += batch_size;
if binary_row_batches.as_mut().peek().await.is_none() {
// This is the last batch of rows we're adding to the table, so batch the RPCs to
// set the replication offset and compact the table along with the insertion
let span = info_span!(
"Setting replication offset and compacting table",
table = %noria_table.table_name().display(Dialect::PostgreSQL),
%wal_position
);
let capacity = match noria_rows_iter.size_hint() {
(_, Some(high)) => high,
(low, None) => low,
} + 2;
let mut actions = Vec::with_capacity(capacity);
for row in noria_rows_iter {
actions.push(TableOperation::Insert(row?));
}
actions.push(TableOperation::SetReplicationOffset(wal_position.clone()));
actions.push(TableOperation::SetSnapshotMode(false));
noria_table.perform_all(actions).await?;
set_replication_offset_and_snapshot_mode = true;
span.in_scope(|| info!("Compacting finished"));
} else {
noria_table
.insert_many(noria_rows_iter.collect::<Result<Vec<_>, _>>()?)
.await
.map_err(|err| {
progress_percentage_metric.set(0.0);
err
})?;
}
if snapshot_report_interval_secs != 0
&& last_report_time.elapsed().as_secs() > snapshot_report_interval_secs
{
last_report_time = Instant::now();
let estimate =
crate::estimate_remaining_time(start_time.elapsed(), cnt as f64, nrows as f64);
let progress_percent = (cnt as f64 / nrows as f64) * 100.;
let progress = format!("{:.2}%", progress_percent);
info!(rows_replicated = %cnt, %progress, %estimate, "Snapshotting progress");
progress_percentage_metric.set(progress_percent);
}
}
// If the table was empty, we didn't set the replication offset or disable snapshot mode
// above, so we need to do it here
if !set_replication_offset_and_snapshot_mode {
noria_table
.perform_all([
TableOperation::SetReplicationOffset(wal_position.clone()),
TableOperation::SetSnapshotMode(false),
])
.await?;
}
info!(rows_replicated = %cnt, "Snapshotting finished");
progress_percentage_metric.set(100.0);
Ok(())
}
}
impl<'a> PostgresReplicator<'a> {
pub(crate) async fn new(
client: &'a mut pgsql::Client,
pool: deadpool_postgres::Pool,
noria: &'a mut readyset_client::ReadySetHandle,
table_filter: TableFilter,
) -> ReadySetResult<PostgresReplicator<'a>> {
let transaction = Some(
client
.build_transaction()
.deferrable(true)
.isolation_level(pgsql::IsolationLevel::RepeatableRead)
.start()
.await?,
);
Ok(PostgresReplicator {
transaction,
pool,
noria,
table_filter,
})
}
async fn snapshot_table(
pool: deadpool_postgres::Pool,
span: tracing::Span,
table: &TableDescription,
noria_table: readyset_client::Table,
snapshot_report_interval_secs: u16,
snapshot_name: String,
wal_position: &ReplicationOffset,
) -> ReadySetResult<()> {
let mut client = pool.get().await?;
let transaction = client
.build_transaction()
.deferrable(true)
.isolation_level(pgsql::IsolationLevel::RepeatableRead)
.read_only(true)
.start()
.await?;
// Ensure each table has a consistent view by using the same snapshot
let query = format!("SET TRANSACTION SNAPSHOT '{}'", snapshot_name);
transaction.query(query.as_str(), &[]).await?;
table
.dump(
&transaction,
noria_table,
snapshot_report_interval_secs,
wal_position,
)
.instrument(span.clone())
.await
.map_err(|e| ReadySetError::TableError {
table: table.name.clone(),
source: Box::new(e),
})
}
/// Snapshot the contents of the upstream database to ReadySet, starting with the DDL, followed
/// by each table's contents.
///
/// If `full_snapshot` is set to `true`, *all* tables will be snapshotted, even those that
/// already have replication offsets in ReadySet.
pub(crate) async fn snapshot_to_noria(
&mut self,
replication_slot: &CreatedSlot,
create_schema: &mut CreateSchema,
snapshot_report_interval_secs: u16,
full_snapshot: bool,
) -> ReadySetResult<()> {
let wal_position = PostgresPosition::from(replication_slot.consistent_point).into();
self.set_snapshot(&replication_slot.snapshot_name).await?;
let table_list = self.get_table_list(TableKind::RegularTable).await?;
let view_list = self.get_table_list(TableKind::View).await?;
let custom_types = self.get_custom_types().await?;
let (table_list, mut non_replicated) =
table_list.into_iter().partition::<Vec<_>, _>(|tbl| {
self.table_filter
.should_be_processed(tbl.schema.as_str(), tbl.name.as_str())
});
// We don't support partitioned tables (only the partitions themselves) so mark those as
// non-replicated as well
non_replicated.extend(self.get_table_list(TableKind::PartitionedTable).await?);
// We don't filter the view list by schemas since a view could be in schema 1 (that may not
// be replicated), but refer to only tables in schema 2 that are all replicated. If we try
// to process a view that points to unreplicated schemas, we will just fail and ignore that
// view.
// Similary, custom types may have cross-schema references and aren't filtered initally
trace!(?table_list, "Loaded table list");
trace!(?view_list, "Loaded view list");
trace!(?custom_types, "Loaded custom types");
self.set_replica_identity_for_tables(&table_list).await?;
self.noria
.extend_recipe_no_leader_ready(ChangeList::from_changes(
non_replicated
.into_iter()
.map(|te| {
Change::AddNonReplicatedRelation(Relation {
schema: Some(te.schema.into()),
name: te.name.into(),
})
})
.collect::<Vec<_>>(),
DataDialect::DEFAULT_POSTGRESQL,
))
.await?;
for ty in custom_types {
let variants = match ty.get_variants(get_transaction!(self)).await {
Ok(v) => v,
Err(error) => {
warn!(%error, custom_type=?ty, "Error looking up variants for custom type, type will not be used");
continue;
}
};
let changelist = ChangeList::from_change(
Change::CreateType {
ty: DfType::from_enum_variants(
variants.into_iter().map(|v| v.label),
Some(PgEnumMetadata {
name: ty.name.clone().into(),
schema: ty.schema.clone().into(),
oid: ty.oid,
array_oid: ty.array_oid,
}),
),
name: ty.clone().into_relation(),
},
DataDialect::DEFAULT_POSTGRESQL,
);
if let Err(error) = self.noria.extend_recipe_no_leader_ready(changelist).await {
warn!(%error, custom_type=?ty, "Error creating custom type, type will not be used");
}
}
self.drop_leftover_tables(&table_list, &view_list)
.await
.map_err(|e| e.context("Error while cleaning up leftover cache tables"))?;
// For each table, retrieve its structure
let mut tables = Vec::with_capacity(table_list.len());
for table in table_list {
let table_name = &table.name.clone().to_string();
match table
.get_table(get_transaction!(self))
.and_then(|create_table| {
future::ready(
create_table
.clone()
.try_into_change()
.map(move |change| (change, create_table)),
)
})
.and_then(|(change, create_table)| {
debug!(%create_table, "Extending recipe");
create_schema.add_table_create(
create_table.name.display(Dialect::PostgreSQL).to_string(),
create_table.to_string(),
);
let mut changes = if full_snapshot {
// If we're doing a full snapshot, drop the table before creating it, to
// clear out any old data.
vec![Change::Drop {
name: create_table.name.clone(),
if_exists: true,
}]
} else {
vec![]
};
changes.push(change);
self.noria
.extend_recipe_no_leader_ready(ChangeList::from_changes(
changes,
DataDialect::DEFAULT_POSTGRESQL,
))
.map_ok(|_| create_table)
})
.await
{
Ok(create_table) => {
tables.push(create_table);
}
Err(error) => {
warn!(%error, table=%table_name, "Error extending CREATE TABLE, table will not be used");
self.noria
.extend_recipe_no_leader_ready(ChangeList::from_change(
Change::AddNonReplicatedRelation(Relation {
schema: Some(table.schema.into()),
name: table.name.clone().into(),
}),
DataDialect::DEFAULT_POSTGRESQL,
))
.await?;
}
}
}
for view in view_list {
let view_name = view.name.clone();
let view_schema = view.schema.clone();
match view
.get_create_view(get_transaction!(self))
.map_err(|e| e.into())
.and_then(|create_view| {
create_schema.add_view_create(view_name.clone(), create_view.clone());
future::ready(
nom_sql::parse_create_view(Dialect::PostgreSQL, &create_view)
.map_err(|_| ReadySetError::UnparseableQuery { query: create_view }),
)
})
.and_then(|view| {
debug!(view = %view.display(nom_sql::Dialect::PostgreSQL), "Extending recipe");
self.noria.extend_recipe_no_leader_ready(
ChangeList::from_change(
Change::CreateView(view),
DataDialect::DEFAULT_POSTGRESQL,
)
.with_schema_search_path(vec![view_schema.clone().into()]),
)
})
.await
{
Ok(_) => {}
Err(error) => {
warn!(
%error,
view=%view_name,
"Error extending CREATE VIEW, view will not be used"
);
self.noria
.extend_recipe_no_leader_ready(ChangeList::from_change(
Change::AddNonReplicatedRelation(Relation {
schema: Some(view_schema.into()),
name: view_name.into(),
}),
DataDialect::DEFAULT_POSTGRESQL,
))
.await?;
}
}
}
let replication_offsets = self.noria.replication_offsets().await?;
let requires_catch_up = if !full_snapshot {
tables
.drain_filter(|t| replication_offsets.has_table(&t.name))
.for_each(|t| {
debug!(
table = %t.name.display(Dialect::PostgreSQL),
"Replication offset already exists for table, skipping snapshot"
)
});
!tables.is_empty()
} else {
true
};
// Skip setting the schema offset if this is not the first time ReadySet is deployed and
// there were no schema changes happening since the last time it was deployed.
// We do this as an optimization, in order to skip the catch up phase (if nothing changed,
// there's nothing to catch up to).
if requires_catch_up || replication_offsets.schema.is_none() {
// The current schema was replicated, assign the current position
debug!(
catch_up = requires_catch_up,
schema_offset = ?replication_offsets.schema,
"Setting schema replication offset"
);
self.noria
.set_schema_replication_offset(Some(&wal_position))
.await?;
} else {
debug!("Skipping schema offset update, since no catch up is required");
}
// Commit the transaction we were using to snapshot the schema. This is important since that
// transaction holds onto locks for tables which we now need to load data from.
self.transaction.take().unwrap().commit().await?;
// Finally copy each table into noria
let mut futs = Vec::with_capacity(tables.len());
for table in &tables {
let span =
info_span!("Snapshotting table", table = %table.name.display(Dialect::PostgreSQL));
span.in_scope(|| info!("Snapshotting table"));
let mut noria_table = self
.noria
.table(table.name.clone())
.instrument(span.clone())
.await?;
span.in_scope(|| trace!("Setting snapshot mode"));
noria_table.set_snapshot_mode(true).await?;
span.in_scope(|| trace!("Set snapshot mode"));
let pool = self.pool.clone();
let snapshot_name = replication_slot.snapshot_name.clone();
futs.push(Self::snapshot_table(
pool,
span,
table,
noria_table,
snapshot_report_interval_secs,
snapshot_name,
&wal_position,
))
}
// Remove from the set of tables any that failed to snapshot,
// and add them as non-replicated relations.
// Propagate any non-TableErrors.
for res in join_all(futs).await {
if let Err(e) = res {
match e {
ReadySetError::TableError { ref table, .. } => {
warn!(%e, table=%table.display(Dialect::PostgreSQL), "Error snapshotting, table will not be used");
tables.retain(|t| t.name != *table);
self.noria
.extend_recipe_no_leader_ready(ChangeList::from_changes(
vec![
Change::Drop {
name: table.clone(),
if_exists: false,
},
Change::AddNonReplicatedRelation(table.clone()),
],
DataDialect::DEFAULT_POSTGRESQL,
))
.await?;
}
_ => Err(e)?,
}
}
}
Ok(())
}
/// Retrieve a list of tables of the specified kind in the specified schema
async fn get_table_list(&mut self, kind: TableKind) -> Result<Vec<TableEntry>, pgsql::Error> {
let kind_code = match kind {
TableKind::RegularTable => 'r',
TableKind::View => 'v',
TableKind::PartitionedTable => 'p',
} as i8;
// We filter out tables that have any generated columns (pgcatalog.pg_attribute.attgenerated
// <> '') because they are currently unsupported and will cause issues
// with replication when the column count on an insert doesnt match the column count
// of the table.
let query = r"
SELECT n.nspname, c.oid, c.relname, c.relkind
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n
ON n.oid = c.relnamespace
WHERE c.relkind IN ($1) AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
AND n.nspname !~ '^pg_toast'
AND c.oid NOT IN(
SELECT c.oid
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_attribute a
ON a.attrelid = c.oid
WHERE attgenerated <> ''
)
";
let tables = get_transaction!(self).query(query, &[&kind_code]).await?;
tables.into_iter().map(TryInto::try_into).collect()
}
/// Retrieve a list of custom types
///
/// Currently this is limited to enum types since that's all we support, but in the future this
/// can be extended to support composite types and ranges as well
async fn get_custom_types(&mut self) -> Result<Vec<CustomTypeEntry>, pgsql::Error> {
let query = r"
SELECT t.oid, t.typarray, t.typname, tn.nspname
FROM pg_type t
JOIN pg_catalog.pg_namespace tn ON t.typnamespace = tn.oid
WHERE typtype = 'e'
";
let res = get_transaction!(self).query(query, &[]).await?;
res.into_iter().map(TryInto::try_into).collect()
}
/// Assign the specific snapshot to the underlying transaction