-
Notifications
You must be signed in to change notification settings - Fork 176
/
_api.py
1358 lines (1194 loc) · 49.3 KB
/
_api.py
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 file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2024 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
# We often have one-arg-per column, so these checks aren't so useful.
# pylint: disable=too-many-arguments,too-many-public-methods,too-many-lines
# SQLAlchemy queries require "column == None", not "column is None" due to operator overloading:
# pylint: disable=singleton-comparison
"""
Persistence API implementation for postgres.
"""
import datetime
import logging
import uuid # noqa: F401
from typing import Iterable, Any
from typing import cast as type_cast
from sqlalchemy import cast, String, Label, Table, FromClause
from sqlalchemy import delete, column, values
from sqlalchemy import select, text, bindparam, and_, or_, func, literal, distinct
from sqlalchemy.dialects.postgresql import INTERVAL
from sqlalchemy.dialects.postgresql import JSONB, insert, UUID
from sqlalchemy.exc import IntegrityError
from sqlalchemy.engine import Row
from deprecat import deprecat
from datacube.index.exceptions import MissingRecordError
from datacube.index.fields import Field, Expression, OrExpression
from datacube.model import Range
from datacube.utils.uris import split_uri
from datacube.migration import ODC2DeprecationWarning
from . import _core
from . import _dynamic as dynamic
from ._fields import parse_fields, PgField, PgExpression, DateRangeDocField # noqa: F401
from ._fields import NativeField, DateDocField, SimpleDocField
from ._schema import DATASET, DATASET_SOURCE, METADATA_TYPE, DATASET_LOCATION, PRODUCT
from .sql import escape_pg_identifier
PGCODE_FOREIGN_KEY_VIOLATION = '23503'
_LOG = logging.getLogger(__name__)
def _dataset_uri_field(table):
return table.c.uri_scheme + ':' + table.c.uri_body
# Fields for selecting dataset with uris
# Need to alias the table, as queries may join the location table for filtering.
SELECTED_DATASET_LOCATION = DATASET_LOCATION.alias('selected_dataset_location')
_DATASET_SELECT_FIELDS = (
DATASET,
# All active URIs, from newest to oldest
func.array(
select(
_dataset_uri_field(SELECTED_DATASET_LOCATION)
).where(
and_(
SELECTED_DATASET_LOCATION.c.dataset_ref == DATASET.c.id,
SELECTED_DATASET_LOCATION.c.archived == None
)
).order_by(
SELECTED_DATASET_LOCATION.c.added.desc(),
SELECTED_DATASET_LOCATION.c.id.desc()
).label('uris')
).label('uris')
)
_DATASET_BULK_SELECT_FIELDS = (
PRODUCT.c.name,
DATASET.c.metadata,
# All active URIs, from newest to oldest
func.array(
select(
_dataset_uri_field(SELECTED_DATASET_LOCATION)
).where(
and_(
SELECTED_DATASET_LOCATION.c.dataset_ref == DATASET.c.id,
SELECTED_DATASET_LOCATION.c.archived == None
)
).order_by(
SELECTED_DATASET_LOCATION.c.added.desc(),
SELECTED_DATASET_LOCATION.c.id.desc()
).label('uris')
).label('uris')
)
def get_native_fields() -> dict[str, NativeField]:
# Native fields (hard-coded into the schema)
fields = {
'id': NativeField(
'id',
'Dataset UUID',
DATASET.c.id
),
'indexed_time': NativeField(
'indexed_time',
'When dataset was indexed',
DATASET.c.added
),
'indexed_by': NativeField(
'indexed_by',
'User who indexed the dataset',
DATASET.c.added_by
),
'product': NativeField(
'product',
'Product name',
PRODUCT.c.name
),
'product_id': NativeField(
'product_id',
'ID of a product',
DATASET.c.dataset_type_ref
),
'metadata_type': NativeField(
'metadata_type',
'Metadata type name of dataset',
METADATA_TYPE.c.name
),
'metadata_type_id': NativeField(
'metadata_type_id',
'ID of a metadata type',
DATASET.c.metadata_type_ref
),
'metadata_doc': NativeField(
'metadata_doc',
'Full metadata document',
DATASET.c.metadata
),
# Fields that can affect row selection
# Note that this field is a single uri: selecting it will result in one-result per uri.
# (ie. duplicate datasets if multiple uris, no dataset if no uris)
'uri': NativeField(
'uri',
"Dataset URI",
DATASET_LOCATION.c.uri_body,
alchemy_expression=_dataset_uri_field(DATASET_LOCATION),
affects_row_selection=True
),
}
return fields
def get_dataset_fields(metadata_type_definition):
dataset_section = metadata_type_definition['dataset']
fields = get_native_fields()
# "Fixed fields" (not dynamic: defined in metadata type schema)
fields.update(dict(
creation_time=DateDocField(
'creation_time',
'Time when dataset was created (processed)',
DATASET.c.metadata,
False,
offset=dataset_section.get('creation_dt') or ['creation_dt']
),
format=SimpleDocField(
'format',
'File format (GeoTiff, NetCDF)',
DATASET.c.metadata,
False,
offset=dataset_section.get('format') or ['format', 'name']
),
label=SimpleDocField(
'label',
'Label',
DATASET.c.metadata,
False,
offset=dataset_section.get('label') or ['label']
),
))
# noinspection PyTypeChecker
fields.update(
parse_fields(
dataset_section['search_fields'],
DATASET.c.metadata
)
)
return fields
class PostgresDbAPI(object):
def __init__(self, connection):
self._connection = connection
self._sqla_txn = None
@property
def in_transaction(self):
return self._connection.in_transaction()
def begin(self):
self._connection.execution_options(isolation_level="REPEATABLE READ")
self._sqla_txn = self._connection.begin()
def _end_transaction(self):
self._sqla_txn = None
self._connection.execution_options(isolation_level="AUTOCOMMIT")
def commit(self):
self._sqla_txn.commit()
self._end_transaction()
def rollback(self):
self._sqla_txn.rollback()
self._end_transaction()
def execute(self, command):
return self._connection.execute(command)
def insert_dataset(self, metadata_doc, dataset_id, product_id):
"""
Insert dataset if not already indexed.
:type metadata_doc: dict
:type dataset_id: str or uuid.UUID
:type product_id: int
:return: whether it was inserted
:rtype: bool
"""
dataset_type_ref = bindparam('dataset_type_ref')
ret = self._connection.execute(
insert(DATASET).from_select(
['id', 'dataset_type_ref', 'metadata_type_ref', 'metadata'],
select(
bindparam('id'), dataset_type_ref,
select(
PRODUCT.c.metadata_type_ref
).where(
PRODUCT.c.id == dataset_type_ref
).label('metadata_type_ref'),
bindparam('metadata', type_=JSONB)
)
).on_conflict_do_nothing(
index_elements=['id']
),
{
"id": dataset_id,
"dataset_type_ref": product_id,
"metadata": metadata_doc
}
)
return ret.rowcount > 0
def insert_dataset_bulk(self, values):
requested = len(values)
res = self._connection.execute(
insert(DATASET), values
)
return res.rowcount, requested - res.rowcount
def update_dataset(self, metadata_doc, dataset_id, product_id):
"""
Update dataset
:type metadata_doc: dict
:type dataset_id: str or uuid.UUID
:type product_id: int
"""
res = self._connection.execute(
DATASET.update().returning(DATASET.c.id).where(
and_(
DATASET.c.id == dataset_id,
DATASET.c.dataset_type_ref == product_id
)
).values(
metadata=metadata_doc
)
)
return res.rowcount > 0
def insert_dataset_location(self, dataset_id, uri):
"""
Add a location to a dataset if it is not already recorded.
Returns True if success, False if this location already existed
:type dataset_id: str or uuid.UUID
:type uri: str
:rtype bool:
"""
scheme, body = split_uri(uri)
r = self._connection.execute(
insert(DATASET_LOCATION).on_conflict_do_nothing(
index_elements=['uri_scheme', 'uri_body', 'dataset_ref']
),
{
"dataset_ref": dataset_id,
"uri_scheme": scheme,
"uri_body": body,
}
)
return r.rowcount > 0
def insert_dataset_location_bulk(self, values):
requested = len(values)
res = self._connection.execute(insert(DATASET_LOCATION), values)
return res.rowcount, requested - res.rowcount
def contains_dataset(self, dataset_id):
return bool(
self._connection.execute(
select(
DATASET.c.id
).where(
DATASET.c.id == dataset_id
)
).fetchone()
)
def datasets_intersection(self, dataset_ids):
""" Compute set intersection: db_dataset_ids & dataset_ids
"""
return [r[0]
for r in self._connection.execute(select(
DATASET.c.id
).where(
DATASET.c.id.in_(dataset_ids)
)).fetchall()]
def get_datasets_for_location(self, uri, mode=None):
scheme, body = split_uri(uri)
if mode is None:
mode = 'exact' if body.count('#') > 0 else 'prefix'
if mode == 'exact':
body_query = DATASET_LOCATION.c.uri_body == body
elif mode == 'prefix':
body_query = DATASET_LOCATION.c.uri_body.startswith(body)
else:
raise ValueError('Unsupported query mode {}'.format(mode))
return self._connection.execute(
select(
*_DATASET_SELECT_FIELDS
).select_from(
DATASET_LOCATION.join(DATASET)
).where(
and_(DATASET_LOCATION.c.uri_scheme == scheme, body_query)
)
).fetchall()
def all_dataset_ids(self, archived: bool | None = False):
query = select(
DATASET.c.id # type: ignore[arg-type]
).select_from(
DATASET
)
if archived:
query = query.where(
DATASET.c.archived.is_not(None)
)
elif archived is not None:
query = query.where(
DATASET.c.archived.is_(None)
)
return self._connection.execute(query).fetchall()
def insert_dataset_source(self, classifier, dataset_id, source_dataset_id):
try:
r = self._connection.execute(
insert(DATASET_SOURCE).on_conflict_do_nothing(
index_elements=['classifier', 'dataset_ref']
),
{
"classifier": classifier,
"dataset_ref": dataset_id,
"source_dataset_ref": source_dataset_id
}
)
return r.rowcount > 0
except IntegrityError as e:
if e.orig.pgcode == PGCODE_FOREIGN_KEY_VIOLATION:
raise MissingRecordError("Referenced source dataset doesn't exist")
raise
def archive_dataset(self, dataset_id):
self._connection.execute(
DATASET.update().where(
DATASET.c.id == dataset_id
).where(
DATASET.c.archived == None
).values(
archived=func.now()
)
)
def restore_dataset(self, dataset_id):
self._connection.execute(
DATASET.update().where(
DATASET.c.id == dataset_id
).values(
archived=None
)
)
def delete_dataset(self, dataset_id):
self._connection.execute(
DATASET_LOCATION.delete().where(
DATASET_LOCATION.c.dataset_ref == dataset_id
)
)
self._connection.execute(
DATASET_SOURCE.delete().where(
DATASET_SOURCE.c.dataset_ref == dataset_id
)
)
self._connection.execute(
DATASET.delete().where(
DATASET.c.id == dataset_id
)
)
def get_dataset(self, dataset_id):
return self._connection.execute(
select(*_DATASET_SELECT_FIELDS).where(DATASET.c.id == dataset_id)
).first()
def get_datasets(self, dataset_ids):
return self._connection.execute(
select(*_DATASET_SELECT_FIELDS).where(DATASET.c.id.in_(dataset_ids))
).fetchall()
def get_derived_datasets(self, dataset_id):
return self._connection.execute(
select(
*_DATASET_SELECT_FIELDS
).select_from(
DATASET.join(DATASET_SOURCE, DATASET.c.id == DATASET_SOURCE.c.dataset_ref)
).where(
DATASET_SOURCE.c.source_dataset_ref == dataset_id
)
).fetchall()
def get_dataset_sources(self, dataset_id):
# recursively build the list of (dataset_ref, source_dataset_ref) pairs starting from dataset_id
# include (dataset_ref, NULL) [hence the left join]
sources = select(
DATASET.c.id.label('dataset_ref'),
DATASET_SOURCE.c.source_dataset_ref,
DATASET_SOURCE.c.classifier
).select_from(
DATASET.join(DATASET_SOURCE,
DATASET.c.id == DATASET_SOURCE.c.dataset_ref,
isouter=True)
).where(
DATASET.c.id == dataset_id
).cte(name="sources", recursive=True)
sources = sources.union_all(
select(
sources.c.source_dataset_ref.label('dataset_ref'),
DATASET_SOURCE.c.source_dataset_ref,
DATASET_SOURCE.c.classifier
).select_from(
sources.join(DATASET_SOURCE,
sources.c.source_dataset_ref == DATASET_SOURCE.c.dataset_ref,
isouter=True)
).where(sources.c.source_dataset_ref != None))
# turn the list of pairs into adjacency list (dataset_ref, [source_dataset_ref, ...])
# some source_dataset_ref's will be NULL
aggd = select(
sources.c.dataset_ref,
func.array_agg(sources.c.source_dataset_ref).label('sources'),
func.array_agg(sources.c.classifier).label('classes')
).group_by(sources.c.dataset_ref).alias('aggd')
# join the adjacency list with datasets table
select_fields = _DATASET_SELECT_FIELDS + (aggd.c.sources, aggd.c.classes)
query = select(*select_fields).select_from(aggd.join(DATASET, DATASET.c.id == aggd.c.dataset_ref))
return self._connection.execute(query).fetchall()
def search_datasets_by_metadata(self, metadata, archived: bool | None = False):
"""
Find any datasets that have the given metadata.
:type metadata: dict
:rtype: dict
"""
# Find any storage types whose 'dataset_metadata' document is a subset of the metadata.
where_clause = DATASET.c.metadata.contains(metadata)
if archived:
where_clause = and_(where_clause, DATASET.c.archived.is_not(None))
elif archived is not None:
where_clause = and_(where_clause, DATASET.c.archived.is_(None))
query = select(*_DATASET_SELECT_FIELDS).where(where_clause)
return self._connection.execute(query).fetchall()
def search_products_by_metadata(self, metadata):
"""
Find any products that have the given metadata.
:type metadata: dict
:rtype: dict
"""
# Find any products types whose metadata document contains the passed in metadata
return self._connection.execute(
PRODUCT.select().where(PRODUCT.c.metadata.contains(metadata))
).fetchall()
@staticmethod
def _alchemify_expressions(expressions):
def raw_expr(expression):
if isinstance(expression, OrExpression):
return or_(raw_expr(expr) for expr in expression.exprs)
return expression.alchemy_expression
return [raw_expr(expression) for expression in expressions]
@staticmethod
def search_datasets_query(expressions, source_exprs=None,
select_fields=None, with_source_ids=False, limit=None,
archived: bool | None = False):
"""
:type expressions: tuple[Expression]
:type source_exprs: tuple[Expression]
:type select_fields: Iterable[PgField]
:type with_source_ids: bool
:type limit: int
:rtype: sqlalchemy.Expression
"""
if select_fields:
# Expand select fields, inserting placeholder columns selections for fields that aren't defined for
# this product query.
select_columns = tuple(
f.alchemy_expression.label(f.name) if f is not None else None
for f in select_fields
)
else:
select_columns = _DATASET_SELECT_FIELDS
if with_source_ids:
# Include the IDs of source datasets
select_columns += (
select(
func.array_agg(DATASET_SOURCE.c.source_dataset_ref)
).select_from(
DATASET_SOURCE
).where(
DATASET_SOURCE.c.dataset_ref == DATASET.c.id
).group_by(
DATASET_SOURCE.c.dataset_ref
).label('dataset_refs'),
)
raw_expressions = PostgresDbAPI._alchemify_expressions(expressions)
from_expression = PostgresDbAPI._from_expression(DATASET, expressions, select_fields)
if archived:
# True: Archived datasets only:
where_expr = and_(DATASET.c.archived.is_not(None), *raw_expressions)
elif archived is not None:
# False/default: Active datasets only:
where_expr = and_(DATASET.c.archived.is_(None), *raw_expressions)
else:
# None: both active and archived datasets
where_expr = and_(*raw_expressions)
if not source_exprs:
return (
select(
*select_columns
).select_from(
from_expression
).where(
where_expr
).limit(
limit
)
)
select_fields = select_columns + (
DATASET_SOURCE.c.source_dataset_ref,
literal(1).label('distance'),
DATASET_SOURCE.c.classifier.label('path')
)
base_query = (
select(
*select_fields
).select_from(
from_expression.join(DATASET_SOURCE, DATASET.c.id == DATASET_SOURCE.c.dataset_ref)
).where(
where_expr
)
).cte(name="base_query", recursive=True)
rq_select_cols = [
col
for col in base_query.columns
if col.name not in ['source_dataset_ref', 'distance', 'path']
] + [
DATASET_SOURCE.c.source_dataset_ref,
(base_query.c.distance + 1).label('distance'),
(base_query.c.path + '.' + DATASET_SOURCE.c.classifier).label('path')
]
recursive_query = base_query.union_all(
select(
*rq_select_cols
).select_from(
base_query.join(
DATASET_SOURCE, base_query.c.source_dataset_ref == DATASET_SOURCE.c.dataset_ref
)
)
)
if archived:
where_expr = and_(DATASET.c.archived.is_not(None), *PostgresDbAPI._alchemify_expressions(source_exprs))
elif archived is not None:
where_expr = and_(DATASET.c.archived.is_(None), *PostgresDbAPI._alchemify_expressions(source_exprs))
else:
where_expr = and_(*PostgresDbAPI._alchemify_expressions(source_exprs))
return (
select(
distinct(recursive_query.c.id),
*[
col for col in recursive_query.columns
if col.name not in ['id', 'source_dataset_ref', 'distance', 'path']
]
).select_from(
recursive_query.join(DATASET, DATASET.c.id == recursive_query.c.source_dataset_ref)
).where(
where_expr
).limit(
limit
)
)
def search_datasets(self, expressions,
source_exprs=None, select_fields=None,
with_source_ids=False, limit=None,
archived: bool | None = False):
"""
:type with_source_ids: bool
:type select_fields: tuple[datacube.drivers.postgres._fields.PgField]
:type expressions: tuple[datacube.drivers.postgres._fields.PgExpression]
"""
select_query = self.search_datasets_query(expressions, source_exprs,
select_fields, with_source_ids, limit,
archived=archived)
return self._connection.execute(select_query)
def bulk_simple_dataset_search(self, products=None, batch_size=0):
"""
Perform bulk database reads (e.g. for index cloning)
:param products: Optional iterable of product names. Only fetch nominated products.
:param batch_size: Number of streamed rows to fetch from database at once.
Defaults to zero, which means no streaming.
Note streaming is only supported inside a transaction.
:return: Iterable of tuples of:
* Product name
* Dataset metadata document
* array of uris
"""
if batch_size > 0 and not self.in_transaction:
raise ValueError("Postgresql bulk reads must occur within a transaction.")
if products:
query = select(PRODUCT.c.id).select_from(PRODUCT).where(PRODUCT.c.name.in_(products))
products = [row[0] for row in self._connection.execute(query)]
if not products:
return []
else:
products = None
query = select(
*_DATASET_BULK_SELECT_FIELDS
).select_from(DATASET).join(PRODUCT).where(
DATASET.c.archived == None
)
if products:
query = query.where(DATASET.c.dataset_type_ref.in_(products))
return self._connection.execution_options(stream_results=True, yield_per=batch_size).execute(query)
def get_all_lineage(self, batch_size: int):
"""
Stream all lineage data in bulk (e.g. for index cloning)
:param batch_size: The number of lineage records to return at once.
:return: Streamable SQLAlchemy result object.
"""
if batch_size > 0 and not self.in_transaction:
raise ValueError("Postgresql bulk reads must occur within a transaction.")
query = select(DATASET_SOURCE.c.dataset_ref, DATASET_SOURCE.c.classifier, DATASET_SOURCE.c.source_dataset_ref)
return self._connection.execution_options(stream_results=True, yield_per=batch_size).execute(query)
def insert_lineage_bulk(self, vals):
"""
Insert bulk lineage records (e.g. for index cloning)
:param values: An array of values dicts for bulk inser
:return: tuple[count of rows loaded, count of rows skipped]
"""
requested = len(vals)
# Wrap values in SQLAlchemy Values object
sqla_vals = values(
column("dataset_ref", UUID),
column("classifier", String),
column("source_dataset_ref", UUID),
name="batch_data"
).data(vals)
# Join Values object against the dataset table, via both FK relations to
# filter out external lineage that cannot be loaded into a legacy lineage index driver
derived_ds = DATASET.alias("derived")
source_ds = DATASET
sel_query = sqla_vals.select().where(
derived_ds.select().where(derived_ds.c.id == sqla_vals.c.dataset_ref).exists(),
source_ds.select().where(source_ds.c.id == sqla_vals.c.source_dataset_ref).exists(),
)
query = insert(
DATASET_SOURCE
).from_select(
['dataset_ref', 'classifier', 'source_dataset_ref'],
sel_query
).on_conflict_do_nothing(
index_elements=['classifier', 'dataset_ref']
)
res = self._connection.execute(query)
return res.rowcount, requested - res.rowcount
@staticmethod
def search_unique_datasets_query(expressions, select_fields, limit, archived: bool | None = False):
"""
'unique' here refer to that the query results do not contain datasets
having the same 'id' more than once.
We are not dealing with dataset_source table here and we are not joining
dataset table with dataset_location table. We are aggregating stuff
in dataset_location per dataset basis if required. It returns the construted
query.
"""
# expressions involving DATASET_SOURCE cannot not done for now
for expression in expressions:
assert expression.field.required_alchemy_table != DATASET_SOURCE, \
'Joins with dataset_source cannot be done for this query'
# expressions involving 'uri' and 'uris' will be handled different
expressions = [expression for expression in expressions
if expression.field.required_alchemy_table != DATASET_LOCATION]
if select_fields:
select_columns: list[Label[Any] | Table] = []
for field in select_fields:
if field.name in {'uri', 'uris'}:
# All active URIs, from newest to oldest
uris_field = func.array(
select(
_dataset_uri_field(SELECTED_DATASET_LOCATION)
).where(
and_(
SELECTED_DATASET_LOCATION.c.dataset_ref == DATASET.c.id,
SELECTED_DATASET_LOCATION.c.archived == None
)
).order_by(
SELECTED_DATASET_LOCATION.c.added.desc(),
SELECTED_DATASET_LOCATION.c.id.desc()
).label('uris')
).label('uris')
select_columns.append(uris_field)
else:
select_columns.append(field.alchemy_expression.label(field.name))
else:
select_columns = list(_DATASET_SELECT_FIELDS)
raw_expressions = PostgresDbAPI._alchemify_expressions(expressions)
# We don't need 'DATASET_LOCATION table in the from expression
select_fields_ = [field for field in select_fields if field.name not in {'uri', 'uris'}]
from_expression = PostgresDbAPI._from_expression(DATASET, expressions, select_fields_)
if archived:
where_expr = and_(DATASET.c.archived.is_not(None), *raw_expressions)
elif archived is not None:
where_expr = and_(DATASET.c.archived.is_(None), *raw_expressions)
if archived:
where_expr = and_(*raw_expressions)
return (
select(
*select_columns
).select_from(
from_expression
).where(
where_expr
).limit(
limit
)
)
@deprecat(
reason="This method is unnecessary as multiple locations have been deprecated. Use search_datasets instead.",
version='1.9.0',
category=ODC2DeprecationWarning)
def search_unique_datasets(self, expressions, select_fields=None, limit=None, archived: bool | None = False):
"""
Processes a search query without duplicating datasets.
'unique' here refer to that the results do not contain datasets having the same 'id'
more than once. we achieve this by not allowing dataset table to join with
dataset_location or dataset_source tables. Joining with other tables would not
result in multiple records per dataset due to the direction of cardinality.
"""
select_query = self.search_unique_datasets_query(expressions, select_fields, limit, archived=archived)
return self._connection.execute(select_query)
def get_duplicates(self, match_fields: Iterable[Field], expressions: Iterable[Expression]) -> Iterable[Row]:
if "time" in [f.name for f in match_fields]:
return self.get_duplicates_with_time(match_fields, expressions)
group_expressions = tuple(type_cast(PgField, f).alchemy_expression for f in match_fields)
select_query = select(
func.array_agg(DATASET.c.id).label('ids'),
*group_expressions
).select_from(
PostgresDbAPI._from_expression(DATASET, expressions, match_fields)
).where(
and_(DATASET.c.archived == None, *(PostgresDbAPI._alchemify_expressions(expressions)))
).group_by(
*group_expressions
).having(
func.count(DATASET.c.id) > 1
)
return self._connection.execute(select_query)
def get_duplicates_with_time(
self, match_fields: Iterable[Field], expressions: Iterable[Expression]
) -> Iterable[Row]:
"""
If considering time when searching for duplicates, we need to grant some amount of leniency
in case timestamps are not exactly the same.
From the set of datasets that are active and have the correct product (candidates),
find all those whose extended timestamp range overlap (overlapping),
then group them by the other fields.
"""
fields = []
time_field: Label[Any] | None = None
for f in match_fields:
if f.name == "time":
time_field = type_cast(DateRangeDocField, f).expression_with_leniency
else:
fields.append(type_cast(PgField, f).alchemy_expression)
if time_field is None:
raise Exception("No timme field in duplicates query")
candidates_table = select(
DATASET.c.id,
time_field.label('time'),
*fields
).select_from(
PostgresDbAPI._from_expression(DATASET, expressions, match_fields)
).where(
and_(DATASET.c.archived == None, *(PostgresDbAPI._alchemify_expressions(expressions)))
)
t1 = candidates_table.alias("t1")
t2 = candidates_table.alias("t2")
overlapping = select(
t1.c.id,
text("t1.time * t2.time as time_intersect"),
*fields
).select_from(
t1.join(
t2,
and_(t1.c.time.overlaps(t2.c.time), t1.c.id != t2.c.id)
)
)
final_query = select(
func.array_agg(func.distinct(overlapping.c.id)).label("ids"),
*fields,
text("(lower(time_intersect) at time zone 'UTC', upper(time_intersect) at time zone 'UTC') as time")
).select_from(
type_cast(FromClause, overlapping)
).group_by(
*fields, text("time_intersect")
).having(
func.count(overlapping.c.id) > 1
)
return self._connection.execute(final_query)
def count_datasets(self, expressions, archived: bool | None = False):
"""
:type expressions: tuple[datacube.drivers.postgres._fields.PgExpression]
:rtype: int
"""
raw_expressions = self._alchemify_expressions(expressions)
if archived:
where_exprs = and_(DATASET.c.archived.is_not(None), *raw_expressions)
elif archived is not None:
where_exprs = and_(DATASET.c.archived.is_(None), *raw_expressions)
else:
where_exprs = and_(*raw_expressions)
select_query = (
select(
func.count()
).select_from(
self._from_expression(DATASET, expressions)
).where(
where_exprs
)
)
return self._connection.scalar(select_query)
def count_datasets_through_time(self, start, end, period, time_field, expressions):
"""
:type period: str
:type start: datetime.datetime
:type end: datetime.datetime
:type expressions: tuple[datacube.drivers.postgres._fields.PgExpression]
:rtype: list[((datetime.datetime, datetime.datetime), int)]
"""
results = self._connection.execute(
self.count_datasets_through_time_query(start, end, period, time_field, expressions)
)
for time_period, dataset_count in results:
# if not time_period.upper_inf:
yield Range(time_period.lower, time_period.upper), dataset_count
def count_datasets_through_time_query(self, start, end, period, time_field, expressions):
raw_expressions = self._alchemify_expressions(expressions)
start_times = select(
func.generate_series(start, end, cast(period, INTERVAL)).label('start_time'),
).alias('start_times')
time_range_select = (
select(
func.tstzrange(
start_times.c.start_time,
func.lead(start_times.c.start_time).over()
).label('time_period'),
)
).alias('all_time_ranges')
# Exclude the trailing (end time to infinite) row. Is there a simpler way?
time_ranges = (
select(
time_range_select,
).where(
~func.upper_inf(time_range_select.c.time_period)
)
).alias('time_ranges')
count_query = (
select(
func.count('*')
).select_from(
self._from_expression(DATASET, expressions)
).where(
and_(
time_field.alchemy_expression.overlaps(time_ranges.c.time_period),
DATASET.c.archived == None,
*raw_expressions
)
)
)
return select(time_ranges.c.time_period, count_query.label('dataset_count'))
@staticmethod
def _from_expression(source_table, expressions=None, fields=None):
join_tables = set()
if expressions:
join_tables.update(expression.field.required_alchemy_table for expression in expressions)
if fields:
# Ignore placeholder columns
join_tables.update(field.required_alchemy_table for field in fields if field)
join_tables.discard(source_table)
table_order_hack = [DATASET_SOURCE, DATASET_LOCATION, DATASET, PRODUCT, METADATA_TYPE]
from_expression = source_table
for table in table_order_hack:
if table in join_tables:
from_expression = from_expression.join(table)
return from_expression
def get_product(self, id_):
return self._connection.execute(
PRODUCT.select().where(PRODUCT.c.id == id_)
).first()