/
__init__.py
6313 lines (5499 loc) · 249 KB
/
__init__.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
"""
Copyright 2017 Inmanta
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contact: code@inmanta.com
"""
import asyncio
import copy
import datetime
import enum
import hashlib
import json
import logging
import re
import typing
import uuid
import warnings
from abc import ABC, abstractmethod
from collections import abc, defaultdict
from configparser import RawConfigParser
from contextlib import AbstractAsyncContextManager
from itertools import chain
from typing import (
Any,
Awaitable,
Callable,
Dict,
Generic,
Iterable,
List,
NewType,
Optional,
Pattern,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
from uuid import UUID
import asyncpg
import dateutil
import pydantic
import pydantic.tools
import typing_inspect
from asyncpg import Connection
from asyncpg.exceptions import SerializationError
from asyncpg.protocol import Record
import inmanta.const as const
import inmanta.db.versions
import inmanta.resources as resources
import inmanta.util as util
from crontab import CronTab
from inmanta.const import DATETIME_MIN_UTC, DONE_STATES, UNDEPLOYABLE_NAMES, AgentStatus, LogLevel, ResourceState
from inmanta.data import model as m
from inmanta.data import schema
from inmanta.data.model import AuthMethod, PagingBoundaries, ResourceIdStr, api_boundary_datetime_normalizer
from inmanta.protocol.common import custom_json_encoder
from inmanta.protocol.exceptions import BadRequest, NotFound
from inmanta.server import config
from inmanta.stable_api import stable_api
from inmanta.types import JsonType, PrimitiveTypes
LOGGER = logging.getLogger(__name__)
DBLIMIT = 100000
APILIMIT = 1000
# TODO: disconnect
# TODO: difference between None and not set
# Used as the 'default' parameter value for the Field class, when no default value has been set
default_unset = object()
PRIMITIVE_SQL_TYPES = Union[str, int, bool, datetime.datetime, UUID]
"""
Locking order rules:
In general, locks should be acquired consistently with delete cascade lock order, which is top down. Additional lock orderings
are as follows. This list should be extended when new locks (explicit or implicit) are introduced. The rules below are written
as `A -> B`, meaning A should be locked before B in any transaction that acquires a lock on both.
- Code -> ConfigurationModel
"""
@enum.unique
class QueryType(str, enum.Enum):
def _generate_next_value_(name, start: int, count: int, last_values: abc.Sequence[object]) -> str: # noqa: N805
"""
Make enum.auto() return the name of the enum member in lower case.
"""
return name.lower()
EQUALS = enum.auto() # The filter value equals the value in the database
CONTAINS = enum.auto() # Any of the filter values are equal to the value in the database (exact match)
IS_NOT_NULL = enum.auto() # The value is NULL in the database
CONTAINS_PARTIAL = enum.auto() # Any of the filter values are equal to the value in the database (partial match)
RANGE = enum.auto() # The values in the database are in the range described by the filter values and operators
NOT_CONTAINS = enum.auto() # None of the filter values are equal to the value in the database (exact match)
COMBINED = enum.auto() # The value describes a combination of other query types
class InvalidQueryType(Exception):
def __init__(self, message: str) -> None:
super(InvalidQueryType, self).__init__(message)
self.message = message
class TableLockMode(enum.Enum):
"""
Table level locks as defined in the PostgreSQL docs:
https://www.postgresql.org/docs/13/explicit-locking.html#LOCKING-TABLES. When acquiring a lock, make sure to use the same
locking order accross transactions (as described at the top of this module) to prevent deadlocks and to otherwise respect
the consistency docs: https://www.postgresql.org/docs/13/applevel-consistency.html#NON-SERIALIZABLE-CONSISTENCY.
Not all lock modes are currently supported to keep the interface minimal (only include what we actually use). This class
may be extended when a new lock mode is required.
"""
ROW_EXCLUSIVE: str = "ROW EXCLUSIVE"
SHARE_UPDATE_EXCLUSIVE: str = "SHARE UPDATE EXCLUSIVE"
SHARE: str = "SHARE"
SHARE_ROW_EXCLUSIVE: str = "SHARE ROW EXCLUSIVE"
class RowLockMode(enum.Enum):
"""
Row level locks as defined in the PostgreSQL docs: https://www.postgresql.org/docs/13/explicit-locking.html#LOCKING-ROWS.
When acquiring a lock, make sure to use the same locking order accross transactions (as described at the top of this
module) to prevent deadlocks and to otherwise respect the consistency docs:
https://www.postgresql.org/docs/13/applevel-consistency.html#NON-SERIALIZABLE-CONSISTENCY.
"""
FOR_UPDATE: str = "FOR UPDATE"
FOR_NO_KEY_UPDATE: str = "FOR NO KEY UPDATE"
FOR_SHARE: str = "FOR SHARE"
FOR_KEY_SHARE: str = "FOR KEY SHARE"
class RangeOperator(enum.Enum):
LT = "<"
LE = "<="
GT = ">"
GE = ">="
@property
def pg_value(self) -> str:
return self.value
@classmethod
def parse(cls, text: str) -> "RangeOperator":
try:
return cls[text.upper()]
except KeyError:
raise ValueError(f"Failed to parse {text} as a RangeOperator")
RangeConstraint = list[tuple[RangeOperator, int]]
DateRangeConstraint = list[tuple[RangeOperator, datetime.datetime]]
QueryFilter = Tuple[QueryType, object]
class PagingCounts:
def __init__(self, total: int, before: int, after: int) -> None:
self.total = total
self.before = before
self.after = after
class InvalidQueryParameter(Exception):
def __init__(self, message: str) -> None:
super(InvalidQueryParameter, self).__init__(message)
self.message = message
class InvalidFieldNameException(Exception):
def __init__(self, message: str, *args: object) -> None:
super().__init__(message, *args)
self.message = message
ColumnNameStr = NewType("ColumnNameStr", str)
"""
A valid database column name
"""
OrderStr = NewType("OrderStr", str)
"""
A valid database ordering
"""
class ArgumentCollector:
"""
Small helper to make placeholders for query arguments
args = ArgumentCollector()
query = f"SELECT * FROM table WHERE a = {args(a_value)} AND b = {args(b_value)}"
con.fetch(query, *args.get_values())
"""
def __init__(self, offset: int = 0, de_duplicate: bool = False) -> None:
"""
:param offset: the smallest number already in use, the next one given out will be offset+1
:param de_duplicate: if the value is the same, return the same number
"""
self.args: list[object] = []
self.offset = offset
self.de_duplicate = de_duplicate
def __call__(self, entry: object) -> str:
if self.de_duplicate and entry in self.args:
return "$" + str(self.args.index(entry) + 1 + self.offset)
self.args.append(entry)
return "$" + str(len(self.args) + self.offset)
def get_values(self) -> list[object]:
return self.args
class PagingOrder(str, enum.Enum):
ASC = "ASC"
DESC = "DESC"
def invert(self) -> "PagingOrder":
if self == PagingOrder.ASC:
return PagingOrder.DESC
return PagingOrder.ASC
@property
def db_form(self) -> OrderStr:
if self == PagingOrder.ASC:
return OrderStr("ASC NULLS FIRST")
return OrderStr("DESC NULLS LAST")
class InvalidSort(Exception):
def __init__(self, message: str, *args: object) -> None:
super(InvalidSort, self).__init__(message, *args)
self.message = message
class ColumnType:
"""
Class encapsulating all handling of specific column types
This implementation supports the PRIMITIVE_SQL_TYPES types, for more specific behavior, make a subclass.
"""
def __init__(self, base_type: Type[PRIMITIVE_SQL_TYPES], nullable: bool):
self.base_type = base_type
self.nullable = nullable
def as_basic_filter_elements(self, name: str, value: object) -> Sequence[Tuple[str, "ColumnType", object]]:
"""
Break down this filter into more elementary filters
:param name: column name, intended to be passed through get_accessor
:param value: the value of this column
:return: a list of (name, type, value) items
"""
return [(name, self, self.get_value(value))]
def as_basic_order_elements(self, name: str, order: PagingOrder) -> Sequence[Tuple[str, "ColumnType", PagingOrder]]:
"""
Break down this filter into more elementary filters
:param name: column name, intended to be passed through get_accessor
:return: a list of (name, type, order) items
"""
return [(name, self, order)]
def get_value(self, value: object) -> Optional[PRIMITIVE_SQL_TYPES]:
"""
Prepare the actual value for use as an argument in a prepared statement for this type
"""
if value is None:
if not self.nullable:
raise ValueError("None is not a valid value")
else:
return None
if isinstance(value, self.base_type):
# It is as expected
return value
if self.base_type == bool:
return pydantic.validators.bool_validator(value)
if self.base_type == datetime.datetime and isinstance(value, str):
return api_boundary_datetime_normalizer(dateutil.parser.isoparse(value))
if issubclass(self.base_type, (str, int)) and isinstance(value, (str, int, bool)):
# We can cast between those types
return self.base_type(value)
raise ValueError(f"{value} is not a valid value")
def get_accessor(self, column_name: str, table_prefix: Optional[str] = None) -> str:
"""
return the sql statement to get this column, as used in filter and other statements
"""
table_prefix_value = "" if table_prefix is None else table_prefix + "."
return table_prefix_value + column_name
def coalesce_to_min(self, value_reference: str) -> str:
"""If the order by column is nullable, coalesce the parameter value to the minimum value of the specific type
This is required for the comparisons used for paging, because comparing a value to
NULL always yields NULL.
"""
if self.nullable:
if self.base_type == datetime.datetime:
return f"COALESCE({value_reference}, to_timestamp(0))"
elif self.base_type == bool:
return f"COALESCE({value_reference}, FALSE)"
elif self.base_type == int:
# we only support positive ints up till now
return f"COALESCE({value_reference}, -1)"
elif self.base_type == str:
return f"COALESCE({value_reference}, '')"
elif self.base_type == UUID:
return f"COALESCE({value_reference}, '00000000-0000-0000-0000-000000000000'::uuid)"
else:
assert False, "Unexpected argument type received, this should not happen"
return value_reference
class TablePrefixWrapper(ColumnType):
def __init__(self, table_name: str, child: ColumnType) -> None:
self.table_name = table_name
self.child = child
@property
def nullable(self) -> bool:
return self.child.nullable
def get_value(self, value: object) -> Optional[PRIMITIVE_SQL_TYPES]:
return self.child.get_value(value)
def get_accessor(self, column_name: str, table_prefix: Optional[str] = None) -> str:
if not table_prefix:
table_prefix = self.table_name
return self.child.get_accessor(column_name, table_prefix)
def coalesce_to_min(self, value_reference: str) -> str:
return self.child.coalesce_to_min(value_reference)
class ForcedStringColumn(ColumnType):
"""A string that is explicitly cast to a specific string type"""
def __init__(self, forced_type: str) -> None:
super().__init__(base_type=str, nullable=False)
self.forced_type = forced_type
def get_accessor(self, column_name: str, table_prefix: Optional[str] = None) -> str:
"""
return the sql statement to get this column, as used in filter and other statements
"""
return super().get_accessor(column_name, table_prefix) + "::" + self.forced_type
class ResourceVersionIdColumnType(ColumnType):
def __init__(self) -> None:
self.nullable = False
def as_basic_filter_elements(self, name: str, value: object) -> Sequence[Tuple[str, "ColumnType", object]]:
"""
Break down this filter into more elementary filters
:param name: column name, intended to be passed through get_accessor
:param value: the value of this column
:return: a list of (name, type, value) items
"""
assert isinstance(value, str)
id = resources.Id.parse_resource_version_id(value)
return [
("resource_id", StringColumn, StringColumn.get_value(id.resource_str())),
("model", PositiveIntColumn, PositiveIntColumn.get_value(id.version)),
]
def as_basic_order_elements(self, name: str, order: PagingOrder) -> Sequence[Tuple[str, "ColumnType", PagingOrder]]:
"""
Break down this filter into more elementary filters
:param name: column name, intended to be passed through get_accessor
:return: a list of (name, type, order) items
"""
return [("resource_id", StringColumn, order), ("model", PositiveIntColumn, order)]
def get_value(self, value: object) -> Optional[PRIMITIVE_SQL_TYPES]:
"""
Prepare the actual value for use as an argument in a prepared statement for this type
"""
raise NotImplementedError()
def get_accessor(self, column_name: str, table_prefix: Optional[str] = None) -> str:
"""
return the sql statement to get this column, as used in filter and other statements
"""
raise NotImplementedError()
def coalesce_to_min(self, value_reference: str) -> str:
"""If the order by column is nullable, coalesce the parameter value to the minimum value of the specific type
This is required for the comparisons used for paging, because comparing a value to
NULL always yields NULL.
"""
raise NotImplementedError()
StringColumn = ColumnType(base_type=str, nullable=False)
OptionalStringColumn = ColumnType(base_type=str, nullable=True)
DateTimeColumn = ColumnType(base_type=datetime.datetime, nullable=False)
OptionalDateTimeColumn = ColumnType(base_type=datetime.datetime, nullable=True)
PositiveIntColumn = ColumnType(base_type=int, nullable=False)
# Negatives ints require updating coalesce_to_min
TextColumn = ForcedStringColumn("text")
UUIDColumn = ColumnType(base_type=uuid.UUID, nullable=False)
BoolColumn = ColumnType(base_type=bool, nullable=False)
ResourceVersionIdColumn = ResourceVersionIdColumnType()
class DatabaseOrderV2(ABC):
"""
Helper API for handling database order and filtering
This class defines the consumer interface,
It is made into a separate type, to make it very explicit what is exposed externally, to limit feature creep
"""
@abstractmethod
def as_filter(
self,
offset: int,
column_value: Optional[PRIMITIVE_SQL_TYPES] = None,
id_value: Optional[PRIMITIVE_SQL_TYPES] = None,
start: bool = True,
) -> Tuple[List[str], List[object]]:
"""
Produce a filter for this order, to select all record before or after the given id
:param offset: the next free number to use for query parameters
:param column_value: the boundary value for the user specified order
:param id_value: the boundary value for the built in order order
:param start: is this the start filter? if so, retain all values` > (column_value, id_value)`
:return: The filter (as a string) and all associated query parameter values
None values can have a double meaning here:
- no value provided
- the value is provided and None
The distinction can be made as follows:
1. at least one of the columns must be not nullable (otherwise the sorting is not unique)
2. when both value are None, we are not paging and return '[],[]'
3. when one of the values is effective, we produce a filter
More specifically:
1. when we have a single order, and `column_value` is not None, this singe value is used for filtering
2. when we have a double order and the 'id_value' is not None and `self.get_order_by_column_type().nullable`,
we consider the null an effective value and filter on both `column_value` and `id_value`
3. when we have a double order and the 'id_value' is not None and `not self.get_order_by_column_type().nullable`,
we consider the null not a value and filter only on `id_value`
"""
pass
@abstractmethod
def get_order_by_statement(self, invert: bool = False, table: Optional[str] = None) -> str:
"""Get this order as an order_by statement"""
pass
@abstractmethod
def get_order(self) -> PagingOrder:
"""Return the order of this paging request"""
pass
@abstractmethod
def get_paging_boundaries(self, first: abc.Mapping[str, object], last: abc.Mapping[str, object]) -> PagingBoundaries:
"""Return the page boundaries, given the first and last record of the page"""
pass
T_SELF = TypeVar("T_SELF", bound="SingleDatabaseOrder")
class SingleDatabaseOrder(DatabaseOrderV2, ABC):
"""
Abstract Base class for ordering when using
- a user specified order, that is always unique
"""
def __init__(
self,
order_by_column: ColumnNameStr,
order: PagingOrder,
) -> None:
"""The order_by_column and order parameters should be validated"""
self.order_by_column = order_by_column
self.order = order
# Configuration methods
@classmethod
def get_valid_sort_columns(cls) -> Dict[ColumnNameStr, ColumnType]:
"""Return all valid columns for lookup and their type"""
raise NotImplementedError()
# Factory
@classmethod
def parse_from_string(
cls: Type[T_SELF],
sort: str,
) -> T_SELF:
valid_sort_pattern: Pattern[str] = re.compile(
f"^({'|'.join(cls.get_valid_sort_columns().keys())})\\.(asc|desc)$", re.IGNORECASE
)
match = valid_sort_pattern.match(sort)
if match and len(match.groups()) == 2:
order_by_column = match.groups()[0].lower()
# Verify there is no escaping from the regex by exact match
assert order_by_column in cls.get_valid_sort_columns()
order = match.groups()[1].upper()
return cls(order_by_column=ColumnNameStr(order_by_column), order=PagingOrder[order])
raise InvalidSort(f"Sort parameter invalid: {sort}")
# Internal helpers
def get_order(self, invert: bool = False) -> PagingOrder:
"""The order string representing the direction the results should be sorted by"""
return self.order.invert() if invert else self.order
def get_order_by_column_type(self) -> ColumnType:
"""The type of the order by column"""
return self.get_valid_sort_columns()[self.order_by_column]
def get_order_by_column_api_name(self) -> str:
"""The name of the column that the results should be ordered by"""
return self.order_by_column
# External API
def as_filter(
self,
offset: int,
column_value: Optional[PRIMITIVE_SQL_TYPES] = None,
id_value: Optional[PRIMITIVE_SQL_TYPES] = None,
start: bool = True,
) -> Tuple[List[str], List[object]]:
"""
Produce a filter for this order, to select all record before or after the given id
:param offset: the next free number to use for query parameters
:param column_value: the value for the user specified order
:param id_value: the value for the built in order order, if this class has one. Otherwise this value is ignored.
:param start: is this the start filter? if so, retain all values` > (column_value, id_value)`
:return: The filter (as a string) and all associated query parameter values
"""
relation = ">" if start else "<"
if column_value is None:
return [], []
coll_type = self.get_order_by_column_type()
col_name = self.order_by_column
value = coll_type.get_value(column_value)
ac = ArgumentCollector(offset=offset - 1)
filter = f"{coll_type.get_accessor(col_name)} {relation} {ac(value)}"
return [filter], ac.args
def get_order_elements(self, invert: bool) -> Sequence[tuple[ColumnNameStr, ColumnType, PagingOrder]]:
"""
return a list of column/column type/order triples, to format an ORDER BY or FILTER statement
"""
order = self.get_order(invert)
return [
(self.order_by_column, self.get_order_by_column_type(), order),
]
def get_order_by_statement(self, invert: bool = False, table: Optional[str] = None) -> str:
"""Return the actual order by statement, as derived from get_order_elements"""
order_by_part = ", ".join(
(f"{type.get_accessor(col, table)} {order.db_form}" for col, type, order in self.get_order_elements(invert))
)
return f" ORDER BY {order_by_part}"
def get_paging_boundaries(self, first: abc.Mapping[str, object], last: abc.Mapping[str, object]) -> PagingBoundaries:
"""Return the page boundaries, given the first and last record returned"""
if self.get_order() == PagingOrder.ASC:
first, last = last, first
order_column_name = self.order_by_column
order_type: ColumnType = self.get_order_by_column_type()
def assert_not_null(in_value: Optional[PRIMITIVE_SQL_TYPES]) -> PRIMITIVE_SQL_TYPES:
# Make mypy happy
assert in_value is not None
return in_value
return PagingBoundaries(
start=assert_not_null(order_type.get_value(first[order_column_name])),
first_id=None,
end=assert_not_null(order_type.get_value(last[order_column_name])),
last_id=None,
)
def __str__(self) -> str:
# used to serialize the order back to a paging url
return f"{self.order_by_column}.{self.order.value.lower()}"
class AbstractDatabaseOrderV2(SingleDatabaseOrder, ABC):
"""
Abstract Base class for ordering when using
- a user specified order
- an additional built in order to make the ordering unique (the id_collumn)
"""
@property
@abstractmethod
def id_column(self) -> Tuple[ColumnNameStr, ColumnType]:
"""Name and type of the id column of this database order"""
pass
# External API
def as_filter(
self,
offset: int,
column_value: Optional[PRIMITIVE_SQL_TYPES] = None,
id_value: Optional[PRIMITIVE_SQL_TYPES] = None,
start: bool = True,
) -> Tuple[List[str], List[object]]:
"""
Produce a filter for this order, to select all record before or after the given id
:param offset: the next free number to use for query parameters
:param column_value: the value for the user specified order
:param id_value: the value for the built in order order
:param start: is this the start filter? if so, retain all values`> (column_value, id_value)`,
otherwise `< (column_value, id_value)`.
:return: The filter (as a string) and all associated query parameter values
"""
# All the filter elements:
# 1. name of the actual collumn in the DB
# 2. type of the collumn
# 3. sanitized value of the collumn
filter_elements: list[tuple[str, ColumnType, object]] = []
order_by_collumns_type = self.get_order_by_column_type()
paging_on_nullable = order_by_collumns_type.nullable and id_value is not None
if column_value is not None or paging_on_nullable:
# Have column value or paging on nullable
filter_elements.extend(order_by_collumns_type.as_basic_filter_elements(self.order_by_column, column_value))
if id_value is not None:
# Have ID
id_name, id_type = self.id_column
if id_name != self.order_by_column:
filter_elements.extend(id_type.as_basic_filter_elements(id_name, id_value))
relation = ">" if start else "<"
if len(filter_elements) == 0:
return [], []
ac = ArgumentCollector(offset=offset - 1)
if len(filter_elements) == 1:
col_name, coll_type, value = filter_elements[0]
filter = f"{coll_type.get_accessor(col_name)} {relation} {ac(value)}"
return [filter], ac.args
else:
# composed filter:
# 1. comparison of two tuples (c_a, c_b) < (c_a, c_b)
# 2. nulls must be removed to get proper comparison
names_tuple = ", ".join(
[coll_type.coalesce_to_min(coll_type.get_accessor(col_name)) for col_name, coll_type, value in filter_elements]
)
values_references_tuple = ", ".join(
[coll_type.coalesce_to_min(ac(value)) for col_name, coll_type, value in filter_elements]
)
filter = f"({names_tuple}) {relation} ({values_references_tuple})"
return [filter], ac.args
def get_order_elements(self, invert: bool) -> list[tuple[ColumnNameStr, ColumnType, PagingOrder]]:
"""
return a list of column/column type/order triples, to format an ORDER BY or FILTER statement
"""
order = self.get_order(invert)
id_name, id_type = self.id_column
return list(
self.get_order_by_column_type().as_basic_order_elements(self.order_by_column, order)
) + id_type.as_basic_order_elements(id_name, order)
def get_paging_boundaries(self, first: abc.Mapping[str, object], last: abc.Mapping[str, object]) -> PagingBoundaries:
"""Return the page boundaries, given the first and last record returned"""
if self.get_order() == PagingOrder.ASC:
first, last = last, first
order_column_name = self.order_by_column
order_type: ColumnType = self.get_order_by_column_type()
id_column, id_type = self.id_column
return PagingBoundaries(
start=order_type.get_value(first[order_column_name]),
first_id=id_type.get_value(first[id_column]),
end=order_type.get_value(last[order_column_name]),
last_id=id_type.get_value(last[id_column]),
)
class VersionedResourceOrder(AbstractDatabaseOrderV2):
"""Represents the ordering by which resources should be sorted"""
@classmethod
def get_valid_sort_columns(cls) -> Dict[ColumnNameStr, ColumnType]:
return {
ColumnNameStr("resource_type"): StringColumn,
ColumnNameStr("agent"): StringColumn,
ColumnNameStr("resource_id_value"): StringColumn,
}
@property
def id_column(self) -> Tuple[ColumnNameStr, ColumnType]:
"""Name of the id column of this database order"""
return ColumnNameStr("resource_id"), StringColumn
class ResourceOrder(VersionedResourceOrder):
"""Represents the ordering by which resources should be sorted"""
@classmethod
def get_valid_sort_columns(cls) -> Dict[ColumnNameStr, ColumnType]:
return {
ColumnNameStr("resource_type"): StringColumn,
ColumnNameStr("agent"): StringColumn,
ColumnNameStr("resource_id"): StringColumn,
ColumnNameStr("resource_id_value"): StringColumn,
ColumnNameStr("status"): TextColumn,
}
@property
def id_column(self) -> Tuple[ColumnNameStr, ColumnType]:
"""Name of the id column of this database order"""
return ColumnNameStr("resource_version_id"), ResourceVersionIdColumn
def get_paging_boundaries(self, first: abc.Mapping[str, object], last: abc.Mapping[str, object]) -> PagingBoundaries:
if self.get_order() == PagingOrder.ASC:
first, last = last, first
order_column_name = self.order_by_column
order_type: ColumnType = self.get_order_by_column_type()
def make_id(record: abc.Mapping[str, object]) -> str:
resource_id = record["resource_id"]
assert isinstance(resource_id, str)
model = record["model"]
return resource_id + ",v=" + str(model)
return PagingBoundaries(
start=order_type.get_value(first[order_column_name]),
first_id=make_id(first),
end=order_type.get_value(last[order_column_name]),
last_id=make_id(last),
)
class ResourceHistoryOrder(AbstractDatabaseOrderV2):
"""Represents the ordering by which resource history should be sorted"""
@classmethod
def get_valid_sort_columns(cls) -> Dict[ColumnNameStr, ColumnType]:
"""Describes the names and types of the columns that are valid for this DatabaseOrder"""
return {ColumnNameStr("date"): DateTimeColumn}
@property
def id_column(self) -> Tuple[ColumnNameStr, ColumnType]:
"""Name and type of the id column of this database order"""
return (ColumnNameStr("attribute_hash"), StringColumn)
class ResourceLogOrder(SingleDatabaseOrder):
"""Represents the ordering by which resource logs should be sorted"""
@classmethod
def get_valid_sort_columns(cls) -> Dict[ColumnNameStr, ColumnType]:
return {
ColumnNameStr("timestamp"): DateTimeColumn,
}
class CompileReportOrder(AbstractDatabaseOrderV2):
"""Represents the ordering by which compile reports should be sorted"""
@classmethod
def get_valid_sort_columns(cls) -> Dict[ColumnNameStr, ColumnType]:
"""Describes the names and types of the columns that are valid for this DatabaseOrder"""
return {ColumnNameStr("requested"): DateTimeColumn}
@property
def id_column(self) -> Tuple[ColumnNameStr, ColumnType]:
"""Name and type of the id column of this database order"""
return (ColumnNameStr("id"), UUIDColumn)
class AgentOrder(AbstractDatabaseOrderV2):
"""Represents the ordering by which agents should be sorted"""
@classmethod
def get_valid_sort_columns(cls) -> Dict[ColumnNameStr, ColumnType]:
"""Describes the names and types of the columns that are valid for this DatabaseOrder"""
return {
ColumnNameStr("name"): TablePrefixWrapper("a", StringColumn),
ColumnNameStr("process_name"): OptionalStringColumn,
ColumnNameStr("paused"): BoolColumn,
ColumnNameStr("last_failover"): OptionalDateTimeColumn,
ColumnNameStr("status"): StringColumn,
}
@property
def id_column(self) -> Tuple[ColumnNameStr, ColumnType]:
"""Name and type of the id column of this database order"""
return (ColumnNameStr("name"), TablePrefixWrapper("a", StringColumn))
class DesiredStateVersionOrder(SingleDatabaseOrder):
"""Represents the ordering by which desired state versions should be sorted"""
@classmethod
def get_valid_sort_columns(cls) -> Dict[ColumnNameStr, ColumnType]:
return {
ColumnNameStr("version"): PositiveIntColumn,
}
class ParameterOrder(AbstractDatabaseOrderV2):
"""Represents the ordering by which parameters should be sorted"""
@classmethod
def get_valid_sort_columns(cls) -> Dict[ColumnNameStr, ColumnType]:
return {
ColumnNameStr("name"): StringColumn,
ColumnNameStr("source"): StringColumn,
ColumnNameStr("updated"): OptionalDateTimeColumn,
}
@property
def id_column(self) -> Tuple[ColumnNameStr, ColumnType]:
"""Name and type of the id column of this database order"""
return (ColumnNameStr("id"), UUIDColumn)
class FactOrder(AbstractDatabaseOrderV2):
"""Represents the ordering by which facts should be sorted"""
@classmethod
def get_valid_sort_columns(cls) -> Dict[ColumnNameStr, ColumnType]:
return {
ColumnNameStr("name"): StringColumn,
ColumnNameStr("resource_id"): StringColumn,
}
@property
def id_column(self) -> Tuple[ColumnNameStr, ColumnType]:
"""Name and type of the id column of this database order"""
return (ColumnNameStr("id"), UUIDColumn)
class NotificationOrder(AbstractDatabaseOrderV2):
"""Represents the ordering by which notifications should be sorted"""
@classmethod
def get_valid_sort_columns(cls) -> Dict[ColumnNameStr, ColumnType]:
"""Describes the names and types of the columns that are valid for this DatabaseOrder"""
return {
ColumnNameStr("created"): DateTimeColumn,
}
@property
def id_column(self) -> Tuple[ColumnNameStr, ColumnType]:
"""Name and type of the id column of this database order"""
return (ColumnNameStr("id"), UUIDColumn)
class DiscoveredResourceOrder(SingleDatabaseOrder):
"""Represents the ordering by which discovered resources should be sorted"""
@classmethod
def get_valid_sort_columns(cls) -> Dict[ColumnNameStr, ColumnType]:
"""Describes the names and types of the columns that are valid for this DatabaseOrder"""
return {
ColumnNameStr("discovered_resource_id"): StringColumn,
}
class BaseQueryBuilder(ABC):
"""Provides a way to build up a sql query from its parts.
Each method returns a new query builder instance, with the additional parameters processed"""
def __init__(
self,
select_clause: Optional[str] = None,
from_clause: Optional[str] = None,
filter_statements: Optional[List[str]] = None,
values: Optional[List[object]] = None,
) -> None:
"""
The parameters are the parts of an sql query,
which can also be added to the builder with the appropriate methods
:param select_clause: The select clause of the query
:param from_clause: From clause of the query
:param filter_statements: A list of filters for the query
:param values: The values to be used for the filter statements
"""
self.select_clause = select_clause
self._from_clause = from_clause
self.filter_statements = filter_statements or []
self.values = values or []
def _join_filter_statements(self, filter_statements: List[str]) -> str:
"""Join multiple filter statements"""
if filter_statements:
return "WHERE " + " AND ".join(filter_statements)
return ""
@abstractmethod
def from_clause(self, from_clause: str) -> "BaseQueryBuilder":
"""Set the from clause of the query"""
raise NotImplementedError()
@property
def offset(self) -> int:
"""The current offset of the values to be used for filter statements"""
return len(self.values) + 1
@abstractmethod
def filter(self, filter_statements: List[str], values: List[object]) -> "BaseQueryBuilder":
"""Add filters to the query"""
raise NotImplementedError()
@abstractmethod
def build(self) -> Tuple[str, List[object]]:
"""Builds up the full query string, and the parametrized value list, ready to be executed"""
raise NotImplementedError()
class SimpleQueryBuilder(BaseQueryBuilder):
"""A query builder suitable for most queries"""
def __init__(
self,
select_clause: Optional[str] = None,
from_clause: Optional[str] = None,
filter_statements: Optional[List[str]] = None,
values: Optional[List[object]] = None,
db_order: Optional[DatabaseOrderV2] = None,
limit: Optional[int] = None,
backward_paging: bool = False,
prelude: Optional[str] = None,
) -> None:
"""
:param select_clause: The select clause of the query
:param from_clause: The from clause of the query
:param filter_statements: A list of filters for the query
:param values: The values to be used for the filter statements
:param db_order: The DatabaseOrder describing how the results should be ordered
:param limit: Limit the results to this amount
:param backward_paging: Whether the ordering of the results should be inverted,
used when going backward through the pages
:param prelude: part of the query preceding all else, for use with 'with' binding
"""
super().__init__(select_clause, from_clause, filter_statements, values)
self.db_order = db_order
self.limit = limit
self.backward_paging = backward_paging
self.prelude = prelude