-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathinterface.py
650 lines (562 loc) · 21 KB
/
interface.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
import logging
import os
import uuid
from datetime import datetime, timezone
from functools import wraps
from sqlalchemy import create_engine, desc, func, inspect, select, text
from sqlalchemy.exc import NoResultFound
from sqlalchemy.orm import aliased, scoped_session, sessionmaker
from harvester.utils.general_utils import query_filter_builder
from .models import (
HarvestJob,
HarvestJobError,
HarvestRecord,
HarvestRecordError,
HarvestSource,
HarvestUser,
Organization,
)
DATABASE_URI = os.getenv("DATABASE_URI")
PAGINATE_ENTRIES_PER_PAGE = 20
PAGINATE_START_PAGE = 0
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
def paginate(fn):
@wraps(fn)
def _impl(self, *args, **kwargs):
query = fn(self, *args, **kwargs)
if kwargs.get("count") is True:
return query
elif kwargs.get("paginate") is False:
return query.all()
else:
per_page = kwargs.get("per_page") or PAGINATE_ENTRIES_PER_PAGE
page = kwargs.get("page") or PAGINATE_START_PAGE
query = query.limit(per_page)
query = query.offset(page * per_page)
return query.all()
return _impl
# notes on the flag `maintain_column_froms`:
# https://github.com/sqlalchemy/sqlalchemy/discussions/6807#discussioncomment-1043732
# docs: https://docs.sqlalchemy.org/en/14/core/selectable.html#sqlalchemy.sql.expression.Select.with_only_columns.params.maintain_column_froms
#
def count(fn):
@wraps(fn)
def _impl(self, *args, **kwargs):
query = fn(self, *args, **kwargs)
if kwargs.get("count") is True:
count_q = query.statement.with_only_columns(
func.count(), maintain_column_froms=True
).order_by(None)
return query.session.execute(count_q).scalar()
else:
return query
return _impl
def count_wrapper(fn):
"""A wrapper that enables non-paginated functions to use the count decorater"""
@wraps(fn)
def _impl(self, *args, **kwargs):
query = fn(self, *args, **kwargs)
if kwargs.get("count") is True:
return query
else:
return query.all()
return _impl
class HarvesterDBInterface:
def __init__(self, session=None):
if session is None:
engine = create_engine(
DATABASE_URI,
isolation_level="AUTOCOMMIT",
pool_size=10,
max_overflow=20,
pool_timeout=60,
pool_recycle=1800,
)
session_factory = sessionmaker(bind=engine, autoflush=True)
self.db = scoped_session(session_factory)
else:
self.db = session
@staticmethod
def _to_dict(obj):
def to_dict_helper(obj):
return {
c.key: getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs
}
if isinstance(obj, list):
return [to_dict_helper(x) for x in obj]
else:
return to_dict_helper(obj)
@staticmethod
def _to_list(obj):
def to_list_helper(obj):
return [getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs]
if isinstance(obj, list):
return [to_list_helper(x) for x in obj]
else:
return to_list_helper(obj)
## ORGANIZATIONS
def add_organization(self, org_data):
try:
new_org = Organization(**org_data)
self.db.add(new_org)
self.db.commit()
self.db.refresh(new_org)
return new_org
except Exception as e:
print("Error:", e)
self.db.rollback()
return None
def get_organization(self, org_id):
return self.db.query(Organization).filter_by(id=org_id).first()
def get_all_organizations(self):
orgs = self.db.query(Organization).all()
return [org for org in orgs]
def update_organization(self, org_id, updates):
try:
org = self.db.get(Organization, org_id)
for key, value in updates.items():
if hasattr(org, key):
setattr(org, key, value)
else:
print(f"Warning: non-existing field '{key}' in organization")
self.db.commit()
return org
except NoResultFound:
self.db.rollback()
return None
def delete_organization(self, org_id):
org = self.db.get(Organization, org_id)
if org is None:
return None
self.db.delete(org)
self.db.commit()
return "Organization deleted successfully"
## HARVEST SOURCES
def add_harvest_source(self, source_data):
try:
new_source = HarvestSource(**source_data)
self.db.add(new_source)
self.db.commit()
self.db.refresh(new_source)
return new_source
except Exception as e:
print("Error:", e)
self.db.rollback()
return None
def get_harvest_source(self, source_id):
result = self.db.query(HarvestSource).filter_by(id=source_id).first()
return result
def get_harvest_source_by_org(self, org_id):
harvest_source = (
self.db.query(HarvestSource).filter_by(organization_id=org_id).all()
)
return [src for src in harvest_source]
def get_harvest_source_by_jobid(self, jobid):
harvest_job = self.db.query(HarvestJob).filter_by(id=jobid).first()
if harvest_job is None:
return None
else:
return harvest_job.source
def get_all_harvest_sources(self):
harvest_sources = self.db.query(HarvestSource).all()
return [source for source in harvest_sources]
def update_harvest_source(self, source_id, updates):
try:
source = self.db.get(HarvestSource, source_id)
for key, value in updates.items():
if hasattr(source, key):
setattr(source, key, value)
else:
print(f"Warning: non-existing field '{key}' in HarvestSource")
self.db.commit()
return source
except NoResultFound:
self.db.rollback()
return None
def delete_harvest_source(self, source_id):
source = self.db.get(HarvestSource, source_id)
if source is None:
return "Harvest source not found"
records = (
self.db.query(HarvestRecord)
.filter(
HarvestRecord.harvest_source_id == source_id,
HarvestRecord.ckan_id.isnot(None),
)
.all()
)
if len(records) == 0:
self.db.delete(source)
self.db.commit()
return "Harvest source deleted successfully"
else:
return (
f"Failed: {len(records)} records in the Harvest source, "
"please Clear it first."
)
## HARVEST JOB
def add_harvest_job(self, job_data):
try:
new_job = HarvestJob(**job_data)
self.db.add(new_job)
self.db.commit()
self.db.refresh(new_job)
return new_job
except Exception as e:
print("Error:", e)
self.db.rollback()
return None
def get_harvest_job(self, job_id):
return self.db.query(HarvestJob).filter_by(id=job_id).first()
def get_first_harvest_job_by_filter(self, filter):
harvest_job = (
self.db.query(HarvestJob)
.filter_by(**filter)
.order_by(HarvestJob.date_created.desc())
.first()
)
return harvest_job
def get_harvest_jobs_by_source_id(self, source_id):
"""used by follow-up job helper"""
harvest_jobs = (
self.db.query(HarvestJob)
.filter_by(harvest_source_id=source_id)
.order_by(HarvestJob.date_created.desc())
.limit(2)
.all()
)
return harvest_jobs
def get_new_harvest_jobs_in_past(self):
harvest_jobs = (
self.db.query(HarvestJob)
.filter(
HarvestJob.date_created < datetime.now(timezone.utc),
HarvestJob.status == "new",
)
.all()
)
return [job for job in harvest_jobs]
def get_new_harvest_jobs_by_source_in_future(self, source_id):
harvest_jobs = (
self.db.query(HarvestJob)
.filter(
HarvestJob.date_created > datetime.now(timezone.utc),
HarvestJob.harvest_source_id == source_id,
HarvestJob.status == "new",
)
.all()
)
return [job for job in harvest_jobs or []]
def update_harvest_job(self, job_id, updates):
try:
job = self.db.get(HarvestJob, job_id)
for key, value in updates.items():
if hasattr(job, key):
setattr(job, key, value)
else:
print(f"Warning: non-existing field '{key}' in HarvestJob")
self.db.commit()
return job
except NoResultFound:
self.db.rollback()
return None
def delete_harvest_job(self, job_id):
job = self.db.get(HarvestJob, job_id)
if job is None:
return f"Harvest job {job_id} not found"
self.db.delete(job)
self.db.commit()
return "Harvest job deleted successfully"
## HARVEST ERROR
def add_harvest_job_error(self, error_data: dict):
try:
new_error = HarvestJobError(**error_data)
self.db.add(new_error)
self.db.commit()
self.db.refresh(new_error)
return new_error
except Exception as e:
print("Error:", e)
self.db.rollback()
return None
def add_harvest_record_error(self, error_data: dict):
try:
new_error = HarvestRecordError(**error_data)
self.db.add(new_error)
self.db.commit()
self.db.refresh(new_error)
return new_error
except Exception as e:
print("Error:", e)
self.db.rollback()
return None
def get_harvest_job_errors_by_job(self, job_id: str) -> list[dict]:
job = self.get_harvest_job(job_id)
return [error for error in job.errors or []]
@count
@paginate
def get_harvest_record_errors_by_job(self, job_id: str, **kwargs):
"""
Retrieves harvest record errors for a given job.
This function fetches all records where the harvest status is 'error' and
belongs to the specified job. The query returns a tuple containing:
- HarvestRecordError object
- identifier (retrieved from HarvestRecord)
- source_raw (retrieved from HarvestRecord, containing 'title')
Returns:
Query: A SQLAlchemy Query object that, when executed, yields tuples of:
(HarvestRecordError, identifier, source_raw).
"""
subquery = (
self.db.query(HarvestRecord.id)
.filter(HarvestRecord.status == "error")
.filter(HarvestRecord.harvest_job_id == job_id)
.subquery()
)
query = (
self.db.query(
HarvestRecordError, HarvestRecord.identifier, HarvestRecord.source_raw
)
.join(
HarvestRecord, HarvestRecord.id == HarvestRecordError.harvest_record_id
)
.filter(HarvestRecord.id.in_(select(subquery)))
)
return query
def get_harvest_error(self, error_id: str) -> dict:
job_query = self.db.query(HarvestJobError).filter_by(id=error_id).first()
record_query = self.db.query(HarvestRecordError).filter_by(id=error_id).first()
if job_query is not None:
return job_query
elif record_query is not None:
return record_query
else:
return None
def get_harvest_record_errors_by_record(self, record_id: str):
errors = self.db.query(HarvestRecordError).filter_by(
harvest_record_id=record_id
)
return [err for err in errors or []]
## HARVEST RECORD
def add_harvest_record(self, record_data):
try:
new_record = HarvestRecord(**record_data)
self.db.add(new_record)
self.db.commit()
self.db.refresh(new_record)
return new_record
except Exception as e:
print("Error:", e)
self.db.rollback()
return None
# TODO: should we delete this if it's not used in code.
def add_harvest_records(self, records_data: list) -> dict:
"""
Add many records at once
:param list records_data: List of records with unique UUIDs
:return dict id_lookup_table: identifiers -> ids
:raises Exception: if the records_data contains records with errors
"""
try:
id_lookup_table = {}
for i, record_data in enumerate(records_data):
new_record = HarvestRecord(id=str(uuid.uuid4()), **record_data)
id_lookup_table[new_record.identifier] = new_record.id
self.db.add(new_record)
if i % 1000 == 0:
self.db.flush()
self.db.commit()
return id_lookup_table
except Exception as e:
print("Error:", e)
self.db.rollback()
return None
def update_harvest_record(self, record_id, updates):
try:
source = self.db.get(HarvestRecord, record_id)
for key, value in updates.items():
if hasattr(source, key):
setattr(source, key, value)
else:
logger.error(f"Non-existing field '{key}' in HarvestRecord")
self.db.commit()
return source
except NoResultFound:
self.db.rollback()
return None
def delete_harvest_record(
self, identifier=None, record_id=None, harvest_source_id=None
):
try:
# delete all versions of the record within the given harvest source
if harvest_source_id is not None and identifier is not None:
records = (
self.db.query(HarvestRecord)
.filter_by(
identifier=identifier, harvest_source_id=harvest_source_id
)
.all()
)
# delete this exact one (used with cleaning)
if record_id is not None:
records = self.db.query(HarvestRecord).filter_by(id=record_id).all()
if len(records) == 0:
logger.warning(
f"Harvest records with identifier {identifier} or {record_id} "
"not found"
)
return
logger.info(
f"{len(records)} records with identifier {identifier} or {record_id}\
found in datagov-harvest-db"
)
for record in records:
self.db.delete(record)
self.db.commit()
return "Harvest record deleted successfully"
except: # noqa E722
self.db.rollback()
return None
def get_harvest_record(self, record_id):
return self.db.query(HarvestRecord).filter_by(id=record_id).first()
def get_all_outdated_records(self, days=365):
"""
gets all outdated versions of records older than [days] ago
for all harvest sources. "outdated" simply means not the latest
or the opposite of 'get_latest_harvest_records_by_source'
"""
old_records_query = self.db.query(HarvestRecord).filter(
func.extract("days", (func.now() - HarvestRecord.date_created)) > days
)
subq = (
self.db.query(HarvestRecord)
.filter(HarvestRecord.status == "success")
.order_by(
HarvestRecord.identifier,
HarvestRecord.harvest_source_id,
desc(HarvestRecord.date_created),
)
.distinct(HarvestRecord.identifier, HarvestRecord.harvest_source_id)
.subquery()
)
sq_alias = aliased(HarvestRecord, subq)
latest_successful_records_query = self.db.query(sq_alias).filter(
sq_alias.action != "delete"
)
return old_records_query.except_all(latest_successful_records_query).all()
@count_wrapper
@count
def get_latest_harvest_records_by_source_orm(self, source_id, **kwargs):
# datetimes are returned as datetime objs not strs
subq = (
self.db.query(HarvestRecord)
.filter(
HarvestRecord.status == "success",
HarvestRecord.harvest_source_id == source_id,
)
.order_by(HarvestRecord.identifier, desc(HarvestRecord.date_created))
.distinct(HarvestRecord.identifier)
.subquery()
)
sq_alias = aliased(HarvestRecord, subq)
return self.db.query(sq_alias).filter(sq_alias.action != "delete")
def get_latest_harvest_records_by_source(self, source_id):
return self._to_dict(self.get_latest_harvest_records_by_source_orm(source_id))
def close(self):
if hasattr(self.db, "remove"):
self.db.remove()
elif hasattr(self.db, "close"):
self.db.close()
# User management
def add_user(self, usr_data):
try:
if not usr_data["email"].endswith(".gov"):
return False, "Error: Email address must be a .gov address."
existing_user = (
self.db.query(HarvestUser).filter_by(email=usr_data["email"]).first()
)
if existing_user:
return False, "User with this email already exists."
new_user = HarvestUser(**usr_data)
self.db.add(new_user)
self.db.commit()
self.db.refresh(new_user)
return True, new_user
except Exception as e:
print("Error:", e)
self.db.rollback()
return False, "An error occurred while adding the user."
def list_users(self):
try:
return self.db.query(HarvestUser).all()
except Exception as e:
print("Error:", e)
return []
def remove_user(self, email):
try:
user = self.db.query(HarvestUser).filter_by(email=email).first()
if user:
self.db.delete(user)
self.db.commit()
return True
return False
except Exception as e:
print("Error:", e)
self.db.rollback()
return False
def verify_user(self, usr_data):
try:
user_by_ssoid = (
self.db.query(HarvestUser).filter_by(ssoid=usr_data["ssoid"]).first()
)
if user_by_ssoid:
if user_by_ssoid.email == usr_data["email"]:
return True
else:
return False
else:
user_by_email = (
self.db.query(HarvestUser)
.filter_by(email=usr_data["email"])
.first()
)
if user_by_email:
user_by_email.ssoid = usr_data["ssoid"]
self.db.commit()
self.db.refresh(user_by_email)
return True
return False
except Exception as e:
print("Error:", e)
return False
#### PAGINATED QUERIES ####
@count
@paginate
def pget_harvest_jobs(self, facets="", **kwargs):
facet_string = query_filter_builder(None, facets)
return self.db.query(HarvestJob).filter(text(facet_string))
@count
@paginate
def pget_harvest_records(self, facets="", **kwargs):
facet_string = query_filter_builder(None, facets)
return self.db.query(HarvestRecord).filter(text(facet_string))
@count
@paginate
def pget_harvest_job_errors(self, facets="", **kwargs):
facet_string = query_filter_builder(None, facets)
return self.db.query(HarvestJobError).filter(text(facet_string))
@count
@paginate
def pget_harvest_record_errors(self, facets="", **kwargs):
facet_string = query_filter_builder(None, facets)
return self.db.query(HarvestRecordError).filter(text(facet_string))
#### FILTERED BUILDER QUERIES ####
def get_harvest_records_by_job(self, job_id, facets="", **kwargs):
facet_string = query_filter_builder(f"harvest_job_id = '{job_id}'", facets)
return self.pget_harvest_records(facets=facet_string, **kwargs)
def get_harvest_records_by_source(self, source_id, facets="", **kwargs):
facet_string = query_filter_builder(
f"harvest_source_id = '{source_id}'", facets
)
return self.pget_harvest_records(facets=facet_string, **kwargs)