/
littletable.py
4410 lines (3805 loc) · 171 KB
/
littletable.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
#
#
# littletable.py
#
# littletable is a simple in-memory database for ad-hoc or user-defined objects,
# supporting simple query and join operations - useful for ORM-like access
# to a collection of data objects, without dealing with SQL
#
#
# Copyright (c) 2010-2023 Paul T. McGuire
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
from __future__ import annotations
__doc__ = r"""
C{littletable} - a Python module to give ORM-like access to a collection of objects
The C{littletable} module provides a low-overhead, schema-less, in-memory database access to a
collection of user objects. C{Table}s can
contain user-defined objects, using those objects' C{__dict__}, C{__slots__}, or C{_fields}
mappings to access object attributes. Table contents can thus also include namedtuples,
SimpleNamespaces, or dataclasses.
C{Tables} can also be constructed using Python dicts. In this case, they are stored as
SimpleNamespaces.
In addition to basic insert/remove/query/delete access to the contents of a
Table, C{littletable} offers:
- indexing for improved retrieval performance, and optional enforcing key uniqueness
- access to objects using indexed attributes
- full text search on attributes containing extended text content
- simplified joins using '+' operator syntax between annotated Tables
- the result of any query or join is a new first-class C{littletable} Table
- pivot on one or two attributes to gather tabulated data summaries
- easy import/export to CSV and JSON files
C{littletable} Tables do not require an upfront schema definition, but simply work off of the
attributes in the stored values, and those referenced in any query parameters.
Here is a simple C{littletable} data storage/retrieval example::
from littletable import Table
# create table of customers
customers = Table('customers')
customers.create_index("id", unique=True)
customers.insert({id="0010", name="George Jetson"})
customers.insert({id="0020", name="Wile E. Coyote"})
customers.insert({id="0030", name="Jonny Quest"})
# create table of product catalog (load from CSV data)
catalog_data = '''\
sku,descr,unitofmeas,unitprice
BRDSD-001,Bird seed,LB,3
BBS-001,Steel BB's,LB,5
MAGNT-001,Magnet,EA,8
MAGLS-001,Magnifying glass,EA,12
ANVIL-001,1000lb anvil,EA,100
ROPE-001,1 in. heavy rope,100FT,10
ROBOT-001,Domestic robot,EA,5000'''
catalog = lt.Table("catalog")
catalog.create_index("sku", unique=True)
catalog.csv_import(catalog_data, transforms={'unitprice':int})
print(catalog.by.sku["ANVIL-001"].descr)
# create many-to-many link table of wishlist items
wishitems = Table('wishitems')
wishitems.create_index("custid")
wishitems.create_index("sku")
wishitems.insert({custid="0020", sku="ANVIL-001"})
wishitems.insert({custid="0020", sku="BRDSD-001"})
wishitems.insert({custid="0020", sku="MAGNT-001"})
wishitems.insert({custid="0030", sku="MAGNT-001"})
wishitems.insert({custid="0030", sku="MAGLS-001"})
# print a particular customer name
# (unique indexes will return a single item; non-unique
# indexes will return a list of all matching items)
print(customers.by.id["0030"].name)
# print all items sold by the pound
for item in catalog.where(unitofmeas="LB"):
print(item.sku, item.descr)
# print all items that cost more than 10
for item in catalog.where(lambda o : o.unitprice>10):
print(item.sku, item.descr, item.unitprice)
# join tables to create queryable wishlists collection
wishlists = customers.join_on("id") + wishitems.join_on("custid") + catalog.join_on("sku")
# print all wishlist items with price > 10
bigticketitems = wishlists().where(lambda ob : ob.unitprice > 10)
for item in bigticketitems:
print(item)
# list all wishlist items in descending order by price
for item in wishlists().orderby("unitprice desc"):
print(item)
"""
import base64
import copy
import csv
import datetime
import functools
import io
import itertools
import textwrap
import warnings
from enum import Enum
from io import StringIO
import json
import operator
import os
import random
import re
import shlex
import statistics
import sys
from collections import defaultdict, namedtuple, Counter
from collections.abc import Mapping, Sequence
from contextlib import closing
from functools import partial
from itertools import repeat, takewhile, chain, product, tee, groupby
from pathlib import Path
from types import SimpleNamespace
import urllib.request
from typing import (
Callable, Any, TextIO, Union, Optional, Iterable, Iterator, Generic, TypeVar, Type, cast,
)
try:
import rich
from rich import box
except ImportError:
rich = None
box = None
version_info = namedtuple("version_info", "major minor micro release_level serial")
__version_info__ = version_info(2, 2, 6, "final", 0)
__version__ = (
"{}.{}.{}".format(*__version_info__[:3])
+ (f"{__version_info__.release_level[0]}{__version_info__.serial}", "")[
__version_info__.release_level == "final"
]
)
__version_time__ = "9 Apr 2024 21:27 UTC"
__author__ = "Paul McGuire <ptmcg@austin.rr.com>"
# custom Exception classes
class SearchIndexInconsistentError(Exception):
"""
Exception raised when using search method on table that has been
modified since the search index was built.
"""
class NoSuchIndexError(KeyError):
"""
Exception raised when trying to access an index that does not exist.
"""
def __init__(self, attrname: str):
super().__init__(attrname)
def __str__(self) -> str:
index_name = super().__str__()
return f"no such index {index_name!r}"
class UnableToExtractAttributeNamesError(ValueError):
"""
Exception raised when attributes cannot be determined from an object.
"""
class ReadonlyIndexAccessError(Exception):
"""
Exception raised when trying to write to a readonly index.
"""
class AuthenticationWarning(Warning):
"""
Warning emitted when using authentication credentials with http:// URL.
"""
def __str__(self) -> str:
return (
"Using Basic Authentication over HTTP can expose login credentials; HTTPS is recommended"
)
def _emit_warning_with_user_frame(warning: Warning) -> None:
import warnings, sys
try:
cur = sys._getframe()
except AttributeError:
user_stack_level = 2
else:
# walk stack trace until outside of this module
user_stack_level = 0
while cur:
user_stack_level += 1
if cur.f_code.co_filename != __file__:
break
cur = cur.f_back
else:
user_stack_level = 2
warnings.warn(message=str(warning), category=type(warning), stacklevel=user_stack_level)
NL = os.linesep
default_row_class = SimpleNamespace
_numeric_type: tuple[type, ...] = (int, float)
right_justify_types: tuple[type, ...] = (int, float, datetime.timedelta)
try:
import numpy
except ImportError:
numpy = None
else:
_numeric_type += (numpy.number,)
try:
import openpyxl
except ImportError:
openpyxl = None
PredicateFunction = Callable[[Any], bool]
__all__ = [
"AuthenticationWarning",
"DataObject",
"FixedWidthReader",
"Table",
"csv_import",
"tsv_import",
"json_import",
"excel_import",
]
# define default stopwords for full_text_search
_stopwords = frozenset(
(*"""\
a about above after again against all am an and any are aren't as at be because been
before being below between both but by can't cannot could couldn't did didn't do does
doesn't doing don't down during each few for from further had hadn't has hasn't have haven't
having he he'd he'll he's her here here's hers herself him himself his how how's i i'd i'll
i'm i've if in into is isn't it it's its itself let's me more most mustn't my myself no nor
not of off on once only or other ought our ours ourselves out over own same shan't she she'd
she'll she's should shouldn't so some such than that that's the their theirs them themselves
then there there's these they they'd they'll they're they've this those through to too under
until up very was wasn't we we'd we'll we're we've were weren't what what's when when's
where where's which while who who's whom why why's with won't would wouldn't you
you'd you'll you're you've your yours yourself yourselves""".split(),
*"d ll m re s t ve".split(), "",
)
)
# irregular plurals and singulars for text search handling
_common_english_irregular_plurals = {
'addenda': 'addendum', 'addendums': 'addendum', 'alumnae': 'alumna', 'alumni': 'alumnus', 'analyses': 'analysis',
'antennae': 'antenna', 'antennas': 'antenna', 'antitheses': 'antithesis',
'appendices': 'appendix', 'appendixes': 'appendix', 'bacilli': 'bacillus', 'bacteria': 'bacterium',
'cacti': 'cactus', 'calves': 'calf', 'children': 'child', 'corpora': 'corpus', 'crises': 'crisis',
'criteria': 'criterion', 'curricula': 'curriculum', 'diagnoses': 'diagnosis', 'dice': 'die',
'dwarves': 'dwarf', 'dwarfs': 'dwarf', 'elves': 'elf', 'ellipses': 'ellipsis', 'errata': 'erratum',
'firemen': 'fireman', 'foci': 'focus', 'feet': 'foot', 'formulae': 'formula', 'fungi': 'fungus', 'genera': 'genus',
'geese': 'goose', 'halves': 'half', 'hooves': 'hoof', 'hypotheses': 'hypothesis',
'indices': 'index', 'indexes': 'index', 'knives': 'knife', 'larvae': 'larva', 'leaves': 'leaf', 'lives': 'life',
'loaves': 'loaf', 'loci': 'locus', 'lice': 'louse', 'men': 'man', 'matrices': 'matrix', 'media': 'medium',
'memoranda': 'memorandum', 'minutiae': 'minutia', 'mice': 'mouse', 'nebulae': 'nebula', 'nuclei': 'nucleus',
'oases': 'oasis', 'opera': 'opus', 'ova': 'ovum', 'oxen': 'ox', 'parentheses': 'parenthesis',
'phenomena': 'phenomenon', 'phyla': 'phylum', 'quizzes': 'quiz', 'radii': 'radius', 'referenda': 'referendum',
'scarves': 'scarf', 'selves': 'self', 'shelves': 'shelf', 'staves': 'staff', 'stimuli': 'stimulus',
'strata': 'stratum', 'syllabi': 'syllabus', 'symposia': 'symposium', 'synopses': 'synopsis', 'tableaux': 'tableau',
'theses': 'thesis', 'thieves': 'thief', 'teeth': 'tooth', 'vertebrae': 'vertebra', 'vertices': 'vertex',
'vitae': 'vita', 'vortices': 'vortex', 'wharves': 'wharf', 'wives': 'wife', 'wolves': 'wolf', 'women': 'woman',
}
_singulars_that_look_like_plurals = [
'rabies', 'scabies', 'caries', 'aries', 'series', 'billiards', 'grits', 'pliers', 'whereabouts', 'jeans',
'binoculars', 'scissors', 'tidings', 'trousers', 'clothes', 'news', 'measles', 'mumps', 'calculus', 'molasses',
'tweezers', 'dominoes', 'pants', 'odds', 'riches', 'alms', 'barracks', 'chassis', 'corps', 'headquarters', 'ides',
'kudos', 'species'
]
_plurals_map = {
**_common_english_irregular_plurals,
**{s: s for s in _singulars_that_look_like_plurals}
}
_significant_word_endings = (
'error',
'warning',
'exception',
)
def _object_attrnames(obj: Any) -> list[str]:
if hasattr(obj, "trait_names"):
return obj.trait_names()
if hasattr(obj, "__dict__"):
# normal object
return list(obj.__dict__)
if isinstance(obj, tuple) and hasattr(obj, "_fields"):
# namedtuple
return obj._fields
if hasattr(obj, "__slots__"):
return list(obj.__slots__)
raise UnableToExtractAttributeNamesError("object with unknown attributes")
def _to_dict(obj) -> dict[str, Any]:
if hasattr(obj, "trait_names"):
return {
k: v
for k, v in zip(obj.trait_names(), (getattr(obj, a) for a in obj.trait_names()))
}
if hasattr(obj, "__dict__"):
# normal object
return obj.__dict__
if isinstance(obj, tuple) and hasattr(obj, "_fields"):
# namedtuple
return dict(zip(obj._fields, obj))
if hasattr(obj, "__slots__"):
return {
k: v
for k, v in zip(obj.__slots__, (getattr(obj, a) for a in obj.__slots__))
}
raise UnableToExtractAttributeNamesError("object with unknown attributes")
def _to_json(obj, enc_cls: Type[json.JSONEncoder], **kwargs: Any) -> str:
return json.dumps(_to_dict(obj), cls=enc_cls, **kwargs)
class DataObject:
"""
A generic semi-mutable object for storing data values in a table. Attributes
can be set by passing in named arguments in the constructor, or by setting them
as C{object.attribute = value}. New attributes can be added any time, but updates
are ignored. Table joins are returned as a Table of DataObjects.
"""
def __init__(self, **kwargs: Any):
warnings.warn(
"littletable.DataObject class is deprecated, use types.Simplenamespace or Python dict",
DeprecationWarning,
stacklevel=2,
)
if kwargs:
self.__dict__.update(kwargs)
def __repr__(self):
return (
"{"
f"""{', '.join(f"{k!r}: {v!r}" for k, v in sorted(self.__dict__.items()))}"""
"}"
)
def __setattr__(self, attr, val):
# make all attributes write-once
if attr not in self.__dict__:
super().__setattr__(attr, val)
else:
raise AttributeError("can't set existing attribute")
def __hasattr__(self, key):
return key in self.__dict__
def __getitem__(self, k):
if hasattr(self, k):
return getattr(self, k)
else:
raise KeyError("object has no such attribute " + k)
__iter__ = None
def __setitem__(self, k, v):
if k not in self.__dict__:
self.__dict__[k] = v
else:
raise KeyError("attribute already exists")
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class _ObjIndex:
def __init__(self, attr):
self.attr = attr
self.obs = defaultdict(list)
self.is_unique = False
def sort(self, key, reverse: bool = False):
for seq in self.obs.values():
seq.sort(key=key, reverse=reverse)
def __setitem__(self, k, v):
self.obs[k].append(v)
def __getitem__(self, k):
return self.obs.get(k, [])
def __len__(self):
return len(self.obs)
def __iter__(self):
return iter(self.obs.keys())
def keys(self):
return sorted(filter(partial(operator.ne, None), self.obs.keys()))
def items(self):
return self.obs.items()
def remove(self, obj):
try:
k = getattr(obj, self.attr)
self.obs[k].remove(obj)
except (ValueError, AttributeError, KeyError):
pass
def __contains__(self, key):
return key in self.obs
def copy_template(self):
return self.__class__(self.attr)
def get(self, key, default=None):
if key in self:
return self[key]
else:
return default
def _clear(self):
self.obs.clear()
Mapping.register(_ObjIndex)
class _UniqueObjIndex(_ObjIndex):
def __init__(self, attr, accept_none=False):
super().__init__(attr)
self.obs = {}
self.is_unique = True
self.accept_none = accept_none
self.none_values = []
def sort(self, key, reverse: bool = False):
pass
def __setitem__(self, k, v):
if k is not None:
if k not in self.obs:
self.obs[k] = v
else:
raise KeyError(f"duplicate key value {k!r}")
else:
if self.accept_none:
self.none_values.append(v)
else:
raise ValueError("None is not a valid index key")
def __getitem__(self, k):
if k is not None:
return [self.obs.get(k)] if k in self.obs else []
else:
return list(self.none_values)
def __contains__(self, k):
if k is not None:
return k in self.obs
else:
return self.accept_none and self.none_values
def keys(self):
return sorted(self.obs.keys()) + ([None, ] if self.none_values else [])
def items(self):
return ((k, [v]) for k, v in self.obs.items())
def remove(self, obj):
if (k := getattr(obj, self.attr)) is not None:
self.obs.pop(k, None)
else:
try:
self.none_values.remove(obj)
except ValueError:
pass
def _clear(self):
super()._clear()
del self.none_values[:]
class _ObjIndexWrapper:
def __init__(self, ind, table):
self._index = ind
self._table: Table = table
def __getattr__(self, attr):
return getattr(self._index, attr)
def __call__(self, attr):
return getattr(self, attr)
def _getitem_using_slice(self, k):
where_selector = {
(False, False, False): lambda: ValueError("must specify start and/or stop values for slice"),
(False, True, False): lambda: Table.lt(k.stop),
(True, False, False): lambda: Table.ge(k.start),
(True, True, False): lambda: (Table.in_range(k.start, k.stop)
if k.start < k.stop
else ValueError("slice end must be greater than slice start")),
(False, False, True): lambda: ValueError("step slicing not supported"),
(True, False, True): lambda: ValueError("step slicing not supported"),
(False, True, True): lambda: ValueError("step slicing not supported"),
(True, True, True): lambda: ValueError("step slicing not supported"),
}[k.start is not None,
k.stop is not None,
k.step is not None]()
if isinstance(where_selector, Exception):
raise where_selector
return self._table.where(**{self._index.attr: where_selector})
def __getitem__(self, k):
if isinstance(k, slice):
return self._getitem_using_slice(k)
ret = self._table.copy_template()
if k in self._index:
ret.insert_many(self._index[k])
return ret
__iter__ = None
def __contains__(self, k):
return k in self._index
Mapping.register(_ObjIndexWrapper)
class _UniqueObjIndexWrapper(_ObjIndexWrapper):
def __getitem__(self, k):
if k is not None:
if isinstance(k, slice):
return super().__getitem__(k)
try:
return self._index[k][0]
except IndexError:
raise KeyError(f"no such value {k!r} in index {self._index.attr!r}")
else:
ret = self._table_template.copy_template()
if k in self._index:
ret.insert_many(self._index[k])
return ret
class _ReadonlyObjIndexWrapper(_ObjIndexWrapper):
def __setitem__(self, k, value):
raise ReadonlyIndexAccessError(f"no update access to index {self.attr!r}")
class _TableAttributeValueLister:
class UniquableIterator:
def __init__(self, seq):
self.__seq = seq
self.__iter = iter(seq)
def __iter__(self):
return self
def __next__(self):
return next(self.__iter)
def __getattr__(self, attr):
if attr == "unique":
self.__iter = filter(
lambda x, seen=set(): x not in seen and not seen.add(x), self.__iter
)
return self
raise AttributeError(f"no such attribute {attr!r} defined")
def __init__(self, table, default=None):
self.__table = table
self.__default = default
def __getattr__(self, attr):
if attr not in self.__table._indexes:
vals = (getattr(row, attr, self.__default) for row in self.__table)
else:
table_index = self.__table._indexes[attr]
if table_index.is_unique:
vals = table_index.keys()
else:
vals = chain.from_iterable(
repeat(k, len(table_index[k])) for k in table_index.keys()
)
return _TableAttributeValueLister.UniquableIterator(vals)
def __call__(self, attr):
return getattr(self, attr)
class _TableSearcher:
def __init__(self, table):
self.__table = table
def __getattr__(self, attr):
ret = partial(self.__table._search, attr)
ret.__name__ = f"Table.search.{attr}"
ret.__doc__ = """
{0}
Search function for attribute {1!r} in a Table.
Parameters:
- query: str - query expression containing one or more search terms
- limit: int - limit number of returned values, default=no limit
- min_score: int - minimum matching score for returned values
- include_words - include each records raw words in the search results
- as_table: bool - flag to select whether to return the results as a
of tuples or as a table (default=False, returns as a list of tuples)
Query search terms can be single words, optionally marked with
leading +, ++, -, or -- prefixes to indicate preference in records
with those words.
Returns:
- list or Table of search result tuples, each tuple containing:
- matched table record
- search score
- (if include_words=True) deduplicated list of words in the matched
record's {1!r}
""".format(ret.__name__, attr)
ret.__annotations__ = {
"query": str,
"limit": int,
"min_score": int,
"include_words": bool,
"as_table": bool,
"return": 'Table | list[tuple]'
}
return ret
def __call__(self, attr):
return getattr(self, attr)
def __dir__(self):
return list(self.__table._search_indexes)
class _IndexAccessor:
def __init__(self, table):
self._table = table
def __dir__(self):
ret = list(self._table._indexes)
return ret
def __getattr__(self, attr):
"""
A quick way to query for matching records using their indexed attributes. The attribute
name is used to locate the index, and returns a wrapper on the index. This wrapper provides
dict-like access to the underlying records in the table, as in::
employees.by.socsecnum["000-00-0000"]
customers.by.zipcode["12345"]
(C{'by'} is added as a pseudo-attribute on tables, to help indicate that the indexed attributes
are not attributes of the table, but of items in the table.)
The behavior differs slightly for unique and non-unique indexes:
- if the index is unique, then retrieving a matching object, will return just the object;
if there is no matching object, C{KeyError} is raised (making a table with a unique
index behave very much like a Python dict)
- if the index is non-unique, then all matching objects will be returned in a new Table,
just as if a regular query had been performed; if no objects match the key value, an empty
Table is returned and no exception is raised.
If there is no index defined for the given attribute, then C{AttributeError} is raised.
"""
attr_index = self._table._indexes.get(attr)
if attr_index is not None:
if isinstance(attr_index, _UniqueObjIndex):
attr_index_wrapper = _UniqueObjIndexWrapper(attr_index, self._table)
attr_index_wrapper.__doc__ = textwrap.dedent(
f"""\
Index accessor by {attr!r}
tbl.by.{attr}[attr_value] returns the object having {attr}=attr_value.
If no such object exists, raises KeyError.
"""
)
else:
attr_index_wrapper = _ObjIndexWrapper(attr_index, self._table)
attr_index_wrapper.__doc__ = textwrap.dedent(
f"""\
Index accessor by {attr!r}
tbl.by.{attr}[attr_value] returns a new Table of all objects having {attr}=attr_value.
If no matching objects exist, returns an empty Table.
"""
)
return attr_index_wrapper
raise AttributeError(f"Table {self._table.table_name!r} has no index {attr!r}")
def __call__(self, attr):
return getattr(self, attr)
_ImportExportDataContainer = Union[str, Path, Iterable[str], TextIO]
class ImportSourceType(Enum):
file = 0
string = 1
url = 2
path = 3
zip = 4
gzip = 5
lzma = 6
iterable = 7
class _MultiIterator(Iterator):
"""
Internal wrapper class to put a consistent iterable and
closeable interface on any of the types that might be used
as import sources:
- a str containing raw xSV data (denoted by a containing \n)
- a str URL (denoted by a leading "http")
- a str file name (containing the data, or a compressed
file containing data)
- a path to a file
- any iterable
"""
def __init__(
self,
seqobj: _ImportExportDataContainer,
encoding: str = "utf-8",
url_args: Optional[dict] = None,
):
def _decoder(seq: Iterable[bytes]) -> Iterable[str]:
for line in seq:
yield line.decode(encoding)
self.type = None
if isinstance(seqobj, Path):
seqobj = str(seqobj)
self.type = ImportSourceType.path
self._iterobj: Iterable[str]
self._closeobj = None
if isinstance(seqobj, str):
if "\n" in seqobj:
self._iterobj = iter(StringIO(seqobj))
self.type = ImportSourceType.string
elif seqobj.startswith(("http://", "https://")):
url_args = url_args or {}
urlopen_args = {}
if not isinstance(url_args.get("data", b""), bytes):
raise TypeError("'data' must be of type bytes")
if "username" in url_args:
if seqobj.startswith("http://"):
_emit_warning_with_user_frame(AuthenticationWarning())
creds = f"{url_args.pop('username')}:{url_args.pop('password', '')}"
auth = base64.b64encode(creds.encode('utf-8')).decode('utf-8')
# Create the auth request header, and add to url_args["headers"]
auth_header = {'Authorization': f'Basic {auth}'}
url_args["headers"] = {
**url_args.get("headers", {}),
**auth_header,
}
# extract any SSL-related args
urlopen_args = {
k: url_args.pop(k, None)
for k in "cafile capath context".split()
}
data_request = urllib.request.Request(url=seqobj, **url_args)
self._closeobj = urllib.request.urlopen(data_request, **urlopen_args)
self._iterobj = _decoder(self._closeobj)
self.type = ImportSourceType.url
else:
if seqobj.endswith(".gz"):
import gzip
self._closeobj = gzip.GzipFile(filename=seqobj)
self._iterobj = _decoder(self._closeobj)
self.type = ImportSourceType.gzip
elif seqobj.endswith((".xz", ".lzma")):
import lzma
self._iterobj = lzma.open(seqobj, "rt", encoding=encoding)
self.type = ImportSourceType.lzma
elif seqobj.endswith(".zip"):
import zipfile
# assume file name inside zip is the same as the zip file without the trailing ".zip"
inner_name = Path(seqobj).stem
self._closeobj = zipfile.ZipFile(seqobj).open(inner_name)
self._iterobj = _decoder(self._closeobj)
self.type = ImportSourceType.zip
elif seqobj.endswith(".xlsx") or seqobj.endswith("xlsm"):
self._iterobj = open(seqobj, 'rb')
if self.type is None:
self.type = ImportSourceType.file
else:
self._iterobj = open(seqobj, encoding=encoding)
if self.type is None:
self.type = ImportSourceType.file
else:
self._iterobj = iter(seqobj)
self.type = ImportSourceType.iterable
def __iter__(self) -> Iterator[Any]:
return self
def __next__(self) -> Any:
return next(self._iterobj)
def close(self) -> None:
if hasattr(self._iterobj, "close"):
self._iterobj.close()
if self._closeobj is not None:
self._closeobj.close()
FixedWidthParseSpec = Union[
tuple[str, int],
tuple[str, int, Optional[int]],
tuple[str, int, Optional[int], Optional[Callable[[str], Any]]],
]
class FixedWidthReader:
"""
Helper class to read fixed-width data and yield a sequence of dicts
representing each row of data.
Parameters:
- slice_spec: a list of tuples defining each column in the input file
Each tuple consists of:
- data column label
- starting column number (0-based)
- (optional) ending column number; if omitted or None, uses the
starting column of the next spec tuple as the ending column
for this column
- (optional) transform function: function called with the column
string value to convert to other type, such as int, float,
datetime, etc.; if omitted or None, str.strip() will be used
- src_file: a string filename or a file-like object containing the
fixed-width data to be loaded
"""
def __init__(
self,
slice_spec: list[FixedWidthParseSpec],
src_file: Union[str, Iterable, TextIO],
encoding: str = "utf-8",
):
def parse_spec(
spec: list[FixedWidthParseSpec],
) -> list[tuple[str, slice, Callable[[str], Any]]]:
ret = []
for cur, next_ in zip(spec, spec[1:] + [("", sys.maxsize, None, None)]):
label, col, endcol, fn = (cur + (None, None,))[:4]
if label is None:
continue
if endcol is None:
endcol = next_[1]
if fn is None:
fn = str.strip
ret.append((label.lower(), slice(col, endcol), fn))
return ret
self._slices = parse_spec(slice_spec)
self._src_file = src_file
self._encoding = encoding
def __iter__(self) -> Iterable[dict[str, Any]]:
with closing(_MultiIterator(self._src_file, self._encoding)) as _srciter:
for line in _srciter:
if not line.strip():
continue
yield {label: fn(line[slc]) for label, slc, fn in self._slices}
def _make_comparator(cmp_fn: Callable[[Any, Any], bool]) -> Callable[[Any], Callable[[Any], Callable[[Any], bool]]]:
"""
Internal function to help define Table.le, Table.lt, etc.
"""
def comparator_with_value(value: Any) -> Callable[[Any], Callable[[Any], bool]]:
def _Table_comparator_fn(attr: str) -> Callable[[Any], bool]:
def _inner(table_rec: Any) -> bool:
try:
return cmp_fn(getattr(table_rec, attr), value)
except TypeError:
return False
return _inner
_Table_comparator_fn.fn = cmp_fn
_Table_comparator_fn.value = value
return _Table_comparator_fn
return comparator_with_value
def _make_comparator_none(cmp_fn: Callable[[Any, Any], bool]) -> Callable[[], Callable[[str], Callable[[Any], bool]]]:
"""
Internal function to help define Table.is_none and Table.is_not_none.
"""
def comparator_with_value() -> Callable[[str], Callable[[Any], bool]]:
def _Table_comparator_fn(attr: str) -> Callable[[Any], bool]:
return lambda table_rec: cmp_fn(getattr(table_rec, attr), None)
_Table_comparator_fn.fn = cmp_fn
_Table_comparator_fn.value = None
return _Table_comparator_fn
return comparator_with_value
def _make_comparator_null(is_null: bool) -> Callable[[], Callable[[str], Callable[[Any], bool]]]:
"""
Internal function to help define Table.is_null and Table.is_not_null.
"""
def is_null_fn(a, value):
return (a in (None, "")) == value
def comparator_with_value() -> Callable[[str], Callable[[Any], bool]]:
def _Table_comparator_fn(attr: str) -> Callable[[Any], bool]:
return lambda table_rec: is_null_fn(getattr(table_rec, attr, None), is_null)
_Table_comparator_fn.fn = is_null_fn
_Table_comparator_fn.value = is_null
return _Table_comparator_fn
return comparator_with_value
def _make_comparator2(
cmp_fn: Callable[[Any, Any, Any], bool]
) -> Callable[[Any, Any], Callable[[str], Callable[[Any], bool]]]:
"""
Internal function to help define Table.within and between
"""
def comparator_with_value(lower: Any, upper: Any) -> Callable[[str], Callable[[Any], bool]]:
def _Table_comparator_fn(attr: str) -> Callable[[Any], bool]:
def _inner(table_rec: Any) -> bool:
try:
return cmp_fn(lower, getattr(table_rec, attr), upper)
except TypeError:
return False