-
Notifications
You must be signed in to change notification settings - Fork 380
Expand file tree
/
Copy pathsnapshot.py
More file actions
758 lines (660 loc) · 27.7 KB
/
snapshot.py
File metadata and controls
758 lines (660 loc) · 27.7 KB
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
from __future__ import annotations
import typing as t
import json
import logging
from pathlib import Path
from collections import defaultdict
from sqlglot import exp
from sqlmesh.core.engine_adapter import EngineAdapter
from sqlmesh.core.state_sync.db.utils import (
snapshot_name_filter,
snapshot_name_version_filter,
snapshot_id_filter,
fetchone,
fetchall,
create_batches,
)
from sqlmesh.core.environment import Environment
from sqlmesh.core.model import SeedModel, ModelKindName
from sqlmesh.core.snapshot.cache import SnapshotCache
from sqlmesh.core.snapshot import (
SnapshotIdLike,
SnapshotNameVersionLike,
SnapshotTableCleanupTask,
SnapshotNameVersion,
SnapshotInfoLike,
Snapshot,
SnapshotIdAndVersion,
SnapshotId,
SnapshotFingerprint,
)
from sqlmesh.utils.migration import index_text_type, blob_text_type
from sqlmesh.utils.date import now_timestamp, TimeLike, to_timestamp
from sqlmesh.utils import unique
if t.TYPE_CHECKING:
import pandas as pd
logger = logging.getLogger(__name__)
class SnapshotState:
SNAPSHOT_BATCH_SIZE = 1000
# Use a smaller batch size for expired snapshots to account for fetching
# of all snapshots that share the same version.
EXPIRED_SNAPSHOT_BATCH_SIZE = 200
def __init__(
self,
engine_adapter: EngineAdapter,
schema: t.Optional[str] = None,
cache_dir: Path = Path(),
):
self.engine_adapter = engine_adapter
self.snapshots_table = exp.table_("_snapshots", db=schema)
self.auto_restatements_table = exp.table_("_auto_restatements", db=schema)
index_type = index_text_type(engine_adapter.dialect)
blob_type = blob_text_type(engine_adapter.dialect)
self._snapshot_columns_to_types = {
"name": exp.DataType.build(index_type),
"identifier": exp.DataType.build(index_type),
"version": exp.DataType.build(index_type),
"dev_version": exp.DataType.build(index_type),
"snapshot": exp.DataType.build(blob_type),
"kind_name": exp.DataType.build("text"),
"updated_ts": exp.DataType.build("bigint"),
"unpaused_ts": exp.DataType.build("bigint"),
"ttl_ms": exp.DataType.build("bigint"),
"unrestorable": exp.DataType.build("boolean"),
"forward_only": exp.DataType.build("boolean"),
"fingerprint": exp.DataType.build(blob_type),
}
self._auto_restatement_columns_to_types = {
"snapshot_name": exp.DataType.build(index_type),
"snapshot_version": exp.DataType.build(index_type),
"next_auto_restatement_ts": exp.DataType.build("bigint"),
}
self._snapshot_cache = SnapshotCache(cache_dir)
def push_snapshots(self, snapshots: t.Iterable[Snapshot], overwrite: bool = False) -> None:
"""Pushes snapshots to the state store.
Args:
snapshots: The snapshots to push.
overwrite: Whether to overwrite existing snapshots.
"""
if overwrite:
snapshots = tuple(snapshots)
self.delete_snapshots(snapshots)
snapshots_to_store = []
for snapshot in snapshots:
if isinstance(snapshot.node, SeedModel):
seed_model = t.cast(SeedModel, snapshot.node)
snapshot = snapshot.copy(update={"node": seed_model.to_dehydrated()})
snapshots_to_store.append(snapshot)
self.engine_adapter.insert_append(
self.snapshots_table,
_snapshots_to_df(snapshots_to_store),
target_columns_to_types=self._snapshot_columns_to_types,
track_rows_processed=False,
)
for snapshot in snapshots:
self._snapshot_cache.put(snapshot)
def unpause_snapshots(
self,
snapshots: t.Collection[SnapshotInfoLike],
unpaused_dt: TimeLike,
) -> None:
unrestorable_snapshots_by_forward_only: t.Dict[bool, t.List[SnapshotNameVersion]] = (
defaultdict(list)
)
for snapshot in snapshots:
# We need to mark all other snapshots that have forward-only opposite to the target snapshot as unrestorable
unrestorable_snapshots_by_forward_only[not snapshot.is_forward_only].append(
snapshot.name_version
)
updated_ts = now_timestamp()
unpaused_ts = to_timestamp(unpaused_dt)
# Pause all snapshots with target names first
for where in snapshot_name_filter(
[s.name for s in snapshots],
batch_size=self.SNAPSHOT_BATCH_SIZE,
):
self.engine_adapter.update_table(
self.snapshots_table,
{"unpaused_ts": None, "updated_ts": updated_ts},
where=where,
)
# Now unpause the target snapshots
self._update_snapshots(
[s.snapshot_id for s in snapshots],
unpaused_ts=unpaused_ts,
updated_ts=updated_ts,
)
# Mark unrestorable snapshots
for forward_only, snapshot_name_versions in unrestorable_snapshots_by_forward_only.items():
forward_only_exp = exp.column("forward_only").is_(exp.convert(forward_only))
for where in snapshot_name_version_filter(
self.engine_adapter,
snapshot_name_versions,
batch_size=self.SNAPSHOT_BATCH_SIZE,
alias=None,
):
self.engine_adapter.update_table(
self.snapshots_table,
{"unrestorable": True, "updated_ts": updated_ts},
where=forward_only_exp.and_(where),
)
def get_expired_snapshots(
self,
environments: t.Iterable[Environment],
current_ts: int,
ignore_ttl: bool = False,
) -> t.List[SnapshotTableCleanupTask]:
"""Aggregates the id's of the expired snapshots and creates a list of table cleanup tasks.
Expired snapshots are snapshots that have exceeded their time-to-live
and are no longer in use within an environment.
Returns:
The set of expired snapshot ids.
The list of table cleanup tasks.
"""
all_cleanup_targets = []
for _, cleanup_targets in self._get_expired_snapshots(
environments=environments,
current_ts=current_ts,
ignore_ttl=ignore_ttl,
):
all_cleanup_targets.extend(cleanup_targets)
return all_cleanup_targets
def _get_expired_snapshots(
self,
environments: t.Iterable[Environment],
current_ts: int,
ignore_ttl: bool = False,
) -> t.Iterator[t.Tuple[t.Set[SnapshotId], t.List[SnapshotTableCleanupTask]]]:
expired_query = exp.select("name", "identifier", "version").from_(self.snapshots_table)
if not ignore_ttl:
expired_query = expired_query.where(
(exp.column("updated_ts") + exp.column("ttl_ms")) <= current_ts
)
expired_candidates = {
SnapshotId(name=name, identifier=identifier): SnapshotNameVersion(
name=name, version=version
)
for name, identifier, version in fetchall(self.engine_adapter, expired_query)
}
if not expired_candidates:
return
promoted_snapshot_ids = {
snapshot.snapshot_id
for environment in environments
for snapshot in environment.snapshots
}
def _is_snapshot_used(snapshot: SnapshotIdAndVersion) -> bool:
return (
snapshot.snapshot_id in promoted_snapshot_ids
or snapshot.snapshot_id not in expired_candidates
)
unique_expired_versions = unique(expired_candidates.values())
version_batches = create_batches(
unique_expired_versions, batch_size=self.EXPIRED_SNAPSHOT_BATCH_SIZE
)
for versions_batch in version_batches:
snapshots = self._get_snapshots_with_same_version(versions_batch)
snapshots_by_version = defaultdict(set)
snapshots_by_dev_version = defaultdict(set)
for s in snapshots:
snapshots_by_version[(s.name, s.version)].add(s.snapshot_id)
snapshots_by_dev_version[(s.name, s.dev_version)].add(s.snapshot_id)
expired_snapshots = [s for s in snapshots if not _is_snapshot_used(s)]
all_expired_snapshot_ids = {s.snapshot_id for s in expired_snapshots}
cleanup_targets: t.List[t.Tuple[SnapshotId, bool]] = []
for snapshot in expired_snapshots:
shared_version_snapshots = snapshots_by_version[(snapshot.name, snapshot.version)]
shared_version_snapshots.discard(snapshot.snapshot_id)
shared_dev_version_snapshots = snapshots_by_dev_version[
(snapshot.name, snapshot.dev_version)
]
shared_dev_version_snapshots.discard(snapshot.snapshot_id)
if not shared_dev_version_snapshots:
dev_table_only = bool(shared_version_snapshots)
cleanup_targets.append((snapshot.snapshot_id, dev_table_only))
snapshot_ids_to_cleanup = [snapshot_id for snapshot_id, _ in cleanup_targets]
for snapshot_id_batch in create_batches(
snapshot_ids_to_cleanup, batch_size=self.SNAPSHOT_BATCH_SIZE
):
snapshot_id_batch_set = set(snapshot_id_batch)
full_snapshots = self._get_snapshots(snapshot_id_batch_set)
cleanup_tasks = [
SnapshotTableCleanupTask(
snapshot=full_snapshots[snapshot_id].table_info,
dev_table_only=dev_table_only,
)
for snapshot_id, dev_table_only in cleanup_targets
if snapshot_id in full_snapshots
]
all_expired_snapshot_ids -= snapshot_id_batch_set
yield snapshot_id_batch_set, cleanup_tasks
if all_expired_snapshot_ids:
# Remaining expired snapshots for which there are no tables
# to cleanup
yield all_expired_snapshot_ids, []
def delete_snapshots(self, snapshot_ids: t.Iterable[SnapshotIdLike]) -> None:
"""Deletes snapshots.
Args:
snapshot_ids: The snapshot IDs to delete.
"""
if not snapshot_ids:
return
for where in snapshot_id_filter(
self.engine_adapter, snapshot_ids, batch_size=self.SNAPSHOT_BATCH_SIZE
):
self.engine_adapter.delete_from(self.snapshots_table, where=where)
def touch_snapshots(self, snapshot_ids: t.Iterable[SnapshotIdLike]) -> None:
"""Touch snapshots to set their updated_ts to the current timestamp.
Args:
snapshot_ids: The snapshot IDs to touch.
"""
self._update_snapshots(snapshot_ids)
def get_snapshots(
self,
snapshot_ids: t.Iterable[SnapshotIdLike],
) -> t.Dict[SnapshotId, Snapshot]:
"""Fetches snapshots.
Args:
snapshot_ids: The snapshot IDs to fetch.
Returns:
A dictionary of snapshot IDs to snapshots.
"""
return self._get_snapshots(snapshot_ids)
def get_snapshots_by_names(
self,
snapshot_names: t.Iterable[str],
current_ts: t.Optional[int] = None,
exclude_expired: bool = True,
) -> t.Set[SnapshotIdAndVersion]:
"""Return the snapshot records for all versions of the specified snapshot names.
Args:
snapshot_names: Iterable of snapshot names to fetch all snapshot records for
current_ts: Sets the current time for identifying which snapshots have expired so they can be excluded (only relevant if :exclude_expired=True)
exclude_expired: Whether or not to return the snapshot id's of expired snapshots in the result
Returns:
A set containing all the matched snapshot records. To fetch full snapshots, pass it into StateSync.get_snapshots()
"""
if not snapshot_names:
return set()
if exclude_expired:
current_ts = current_ts or now_timestamp()
unexpired_expr = (exp.column("updated_ts") + exp.column("ttl_ms")) > current_ts
else:
unexpired_expr = None
return {
SnapshotIdAndVersion(
name=name,
identifier=identifier,
version=version,
dev_version=dev_version,
fingerprint=fingerprint,
)
for where in snapshot_name_filter(
snapshot_names=snapshot_names,
batch_size=self.SNAPSHOT_BATCH_SIZE,
)
for name, identifier, version, dev_version, fingerprint in fetchall(
self.engine_adapter,
exp.select("name", "identifier", "version", "dev_version", "fingerprint")
.from_(self.snapshots_table)
.where(where)
.and_(unexpired_expr),
)
}
def snapshots_exist(self, snapshot_ids: t.Iterable[SnapshotIdLike]) -> t.Set[SnapshotId]:
"""Checks if snapshots exist.
Args:
snapshot_ids: The snapshot IDs to check.
Returns:
A set of snapshot IDs to check for existence.
"""
return {
SnapshotId(name=name, identifier=identifier)
for where in snapshot_id_filter(
self.engine_adapter, snapshot_ids, batch_size=self.SNAPSHOT_BATCH_SIZE
)
for name, identifier in fetchall(
self.engine_adapter,
exp.select("name", "identifier").from_(self.snapshots_table).where(where),
)
}
def nodes_exist(self, names: t.Iterable[str], exclude_external: bool = False) -> t.Set[str]:
"""Checks if nodes with given names exist.
Args:
names: The node names to check.
exclude_external: Whether to exclude external nodes.
Returns:
A set of node names that exist.
"""
names = set(names)
if not names:
return names
query = (
exp.select("name")
.from_(self.snapshots_table)
.where(exp.column("name").isin(*names))
.distinct()
)
if exclude_external:
query = query.where(exp.column("kind_name").neq(ModelKindName.EXTERNAL.value))
return {name for (name,) in fetchall(self.engine_adapter, query)}
def update_auto_restatements(
self, next_auto_restatement_ts: t.Dict[SnapshotNameVersion, t.Optional[int]]
) -> None:
"""Updates the auto restatement timestamps.
Args:
next_auto_restatement_ts: A dictionary of snapshot name version to the next auto restatement timestamp.
"""
next_auto_restatement_ts_deleted = []
next_auto_restatement_ts_filtered = {}
for k, v in next_auto_restatement_ts.items():
if v is None:
next_auto_restatement_ts_deleted.append(k)
else:
next_auto_restatement_ts_filtered[k] = v
for where in snapshot_name_version_filter(
self.engine_adapter,
next_auto_restatement_ts_deleted,
column_prefix="snapshot",
alias=None,
batch_size=self.SNAPSHOT_BATCH_SIZE,
):
self.engine_adapter.delete_from(self.auto_restatements_table, where=where)
if not next_auto_restatement_ts_filtered:
return
self.engine_adapter.merge(
self.auto_restatements_table,
_auto_restatements_to_df(next_auto_restatement_ts_filtered),
target_columns_to_types=self._auto_restatement_columns_to_types,
unique_key=(exp.column("snapshot_name"), exp.column("snapshot_version")),
)
def count(self) -> int:
"""Counts the number of snapshots in the state."""
result = fetchone(self.engine_adapter, exp.select("COUNT(*)").from_(self.snapshots_table))
return result[0] if result else 0
def clear_cache(self) -> None:
"""Clears the snapshot cache."""
self._snapshot_cache.clear()
def _update_snapshots(
self,
snapshots: t.Iterable[SnapshotIdLike],
**kwargs: t.Any,
) -> None:
properties = kwargs
if "updated_ts" not in properties:
properties["updated_ts"] = now_timestamp()
for where in snapshot_id_filter(
self.engine_adapter, snapshots, batch_size=self.SNAPSHOT_BATCH_SIZE
):
self.engine_adapter.update_table(
self.snapshots_table,
properties,
where=where,
)
def _push_snapshots(self, snapshots: t.Iterable[Snapshot]) -> None:
snapshots_to_store = []
for snapshot in snapshots:
if isinstance(snapshot.node, SeedModel):
seed_model = t.cast(SeedModel, snapshot.node)
snapshot = snapshot.copy(update={"node": seed_model.to_dehydrated()})
snapshots_to_store.append(snapshot)
self.engine_adapter.insert_append(
self.snapshots_table,
_snapshots_to_df(snapshots_to_store),
target_columns_to_types=self._snapshot_columns_to_types,
track_rows_processed=False,
)
def _get_snapshots(
self,
snapshot_ids: t.Iterable[SnapshotIdLike],
lock_for_update: bool = False,
) -> t.Dict[SnapshotId, Snapshot]:
"""Fetches specified snapshots or all snapshots.
Args:
snapshot_ids: The collection of snapshot like objects to fetch.
lock_for_update: Lock the snapshot rows for future update
Returns:
A dictionary of snapshot ids to snapshots for ones that could be found.
"""
duplicates: t.Dict[SnapshotId, Snapshot] = {}
def _loader(snapshot_ids_to_load: t.Set[SnapshotId]) -> t.Collection[Snapshot]:
fetched_snapshots: t.Dict[SnapshotId, Snapshot] = {}
for query in self._get_snapshots_expressions(snapshot_ids_to_load, lock_for_update):
for (
serialized_snapshot,
_,
_,
_,
updated_ts,
unpaused_ts,
unrestorable,
forward_only,
next_auto_restatement_ts,
) in fetchall(self.engine_adapter, query):
snapshot = parse_snapshot(
serialized_snapshot=serialized_snapshot,
updated_ts=updated_ts,
unpaused_ts=unpaused_ts,
unrestorable=unrestorable,
forward_only=forward_only,
next_auto_restatement_ts=next_auto_restatement_ts,
)
snapshot_id = snapshot.snapshot_id
if snapshot_id in fetched_snapshots:
other = duplicates.get(snapshot_id, fetched_snapshots[snapshot_id])
duplicates[snapshot_id] = (
snapshot if snapshot.updated_ts > other.updated_ts else other
)
fetched_snapshots[snapshot_id] = duplicates[snapshot_id]
else:
fetched_snapshots[snapshot_id] = snapshot
return fetched_snapshots.values()
snapshots, cached_snapshots = self._snapshot_cache.get_or_load(
{s.snapshot_id for s in snapshot_ids}, _loader
)
if cached_snapshots:
cached_snapshots_in_state: t.Set[SnapshotId] = set()
for where in snapshot_id_filter(
self.engine_adapter, cached_snapshots, batch_size=self.SNAPSHOT_BATCH_SIZE
):
query = (
exp.select(
"name",
"identifier",
"updated_ts",
"unpaused_ts",
"unrestorable",
"forward_only",
"next_auto_restatement_ts",
)
.from_(exp.to_table(self.snapshots_table).as_("snapshots"))
.join(
exp.to_table(self.auto_restatements_table).as_("auto_restatements"),
on=exp.and_(
exp.column("name", table="snapshots").eq(
exp.column("snapshot_name", table="auto_restatements")
),
exp.column("version", table="snapshots").eq(
exp.column("snapshot_version", table="auto_restatements")
),
),
join_type="left",
copy=False,
)
.where(where)
)
if lock_for_update:
query = query.lock(copy=False)
for (
name,
identifier,
updated_ts,
unpaused_ts,
unrestorable,
forward_only,
next_auto_restatement_ts,
) in fetchall(self.engine_adapter, query):
snapshot_id = SnapshotId(name=name, identifier=identifier)
snapshot = snapshots[snapshot_id]
snapshot.updated_ts = updated_ts
snapshot.unpaused_ts = unpaused_ts
snapshot.unrestorable = unrestorable
snapshot.forward_only = forward_only
snapshot.next_auto_restatement_ts = next_auto_restatement_ts
cached_snapshots_in_state.add(snapshot_id)
missing_cached_snapshots = cached_snapshots - cached_snapshots_in_state
for missing_cached_snapshot_id in missing_cached_snapshots:
snapshots.pop(missing_cached_snapshot_id, None)
if duplicates:
self.push_snapshots(duplicates.values(), overwrite=True)
logger.error("Found duplicate snapshots in the state store.")
return snapshots
def _get_snapshots_expressions(
self,
snapshot_ids: t.Iterable[SnapshotIdLike],
lock_for_update: bool = False,
) -> t.Iterator[exp.Expression]:
for where in snapshot_id_filter(
self.engine_adapter,
snapshot_ids,
alias="snapshots",
batch_size=self.SNAPSHOT_BATCH_SIZE,
):
query = (
exp.select(
"snapshots.snapshot",
"snapshots.name",
"snapshots.identifier",
"snapshots.version",
"snapshots.updated_ts",
"snapshots.unpaused_ts",
"snapshots.unrestorable",
"snapshots.forward_only",
"auto_restatements.next_auto_restatement_ts",
)
.from_(exp.to_table(self.snapshots_table).as_("snapshots"))
.join(
exp.to_table(self.auto_restatements_table).as_("auto_restatements"),
on=exp.and_(
exp.column("name", table="snapshots").eq(
exp.column("snapshot_name", table="auto_restatements")
),
exp.column("version", table="snapshots").eq(
exp.column("snapshot_version", table="auto_restatements")
),
),
join_type="left",
copy=False,
)
.where(where)
)
if lock_for_update:
query = query.lock(copy=False)
yield query
def _get_snapshots_with_same_version(
self,
snapshots: t.Collection[SnapshotNameVersionLike],
lock_for_update: bool = False,
) -> t.List[SnapshotIdAndVersion]:
"""Fetches all snapshots that share the same version as the snapshots.
The output includes the snapshots with the specified identifiers.
Args:
snapshots: The collection of target name / version pairs.
lock_for_update: Lock the snapshot rows for future update
Returns:
The list of Snapshot objects.
"""
if not snapshots:
return []
snapshot_rows = []
for where in snapshot_name_version_filter(
self.engine_adapter, snapshots, batch_size=self.SNAPSHOT_BATCH_SIZE
):
query = (
exp.select(
"name",
"identifier",
"version",
"dev_version",
"fingerprint",
)
.from_(exp.to_table(self.snapshots_table).as_("snapshots"))
.where(where)
)
if lock_for_update:
query = query.lock(copy=False)
snapshot_rows.extend(fetchall(self.engine_adapter, query))
return [
SnapshotIdAndVersion(
name=name,
identifier=identifier,
version=version,
dev_version=dev_version,
fingerprint=SnapshotFingerprint.parse_raw(fingerprint),
)
for name, identifier, version, dev_version, fingerprint in snapshot_rows
]
def parse_snapshot(
serialized_snapshot: str,
updated_ts: int,
unpaused_ts: t.Optional[int],
unrestorable: bool,
forward_only: bool,
next_auto_restatement_ts: t.Optional[int],
) -> Snapshot:
return Snapshot(
**{
**json.loads(serialized_snapshot),
"updated_ts": updated_ts,
"unpaused_ts": unpaused_ts,
"unrestorable": unrestorable,
"forward_only": forward_only,
"next_auto_restatement_ts": next_auto_restatement_ts,
}
)
def _snapshot_to_json(snapshot: Snapshot) -> str:
return snapshot.json(
exclude={
"intervals",
"dev_intervals",
"pending_restatement_intervals",
"updated_ts",
"unpaused_ts",
"unrestorable",
"forward_only",
"next_auto_restatement_ts",
}
)
def _snapshots_to_df(snapshots: t.Iterable[Snapshot]) -> pd.DataFrame:
import pandas as pd
return pd.DataFrame(
[
{
"name": snapshot.name,
"identifier": snapshot.identifier,
"version": snapshot.version,
"snapshot": _snapshot_to_json(snapshot),
"kind_name": snapshot.model_kind_name.value if snapshot.model_kind_name else None,
"updated_ts": snapshot.updated_ts,
"unpaused_ts": snapshot.unpaused_ts,
"ttl_ms": snapshot.ttl_ms,
"unrestorable": snapshot.unrestorable,
"forward_only": snapshot.forward_only,
"dev_version": snapshot.dev_version,
"fingerprint": snapshot.fingerprint.json(),
}
for snapshot in snapshots
]
)
def _auto_restatements_to_df(auto_restatements: t.Dict[SnapshotNameVersion, int]) -> pd.DataFrame:
import pandas as pd
return pd.DataFrame(
[
{
"snapshot_name": name_version.name,
"snapshot_version": name_version.version,
"next_auto_restatement_ts": ts,
}
for name_version, ts in auto_restatements.items()
]
)