-
Notifications
You must be signed in to change notification settings - Fork 4
/
config.py
1681 lines (1311 loc) · 53 KB
/
config.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
# -*- coding: utf-8 -*-
import decimal
import datetime
import inspect
import re
import json
import logging
import uuid
import enum
import dsnparse
from datatypes import (
Datetime,
property as cachedproperty,
)
from datatypes.enum import (
find_value,
)
from .compat import *
from . import utils
logger = logging.getLogger(__name__)
class Connection(object):
"""set the paramaters you want to use to connect to an interface
https://github.com/Jaymon/Mingo/blob/master/Mingo/MingoConfig.php
"""
name = ""
"""string -- the name of this connection (eg, Postgres, or SQLite)"""
interface_name = ""
"""string -- full Interface class name -- the interface the connection
should use to talk with the db"""
interface_class = None
"""Holds the interface class this connection should use"""
host = ""
"""the hostname"""
database = ""
"""the db name to use, in postgres, this is the database name"""
port = 0
"""the host port"""
username = ""
"""the username to use to to connect to the db"""
password = ""
"""the password for the username"""
readonly = False
"""Set to true to make the connection readonly"""
options = None
"""any other db options, these can be interface implementation specific"""
@property
def interface(self):
"""Return a new Interface instance using this configuration"""
interface_class = self.interface_class
return interface_class(self)
def __init__(self, fields=None, **fields_kwargs):
"""
set all the values by passing them into this constructor, any
unrecognized kwargs get put into .options
:example:
c = Connection(
host="127.0.0.1",
database="dbname",
port=5000,
some_random_thing="foo"
)
print(c.port) # 5000
print(c.options) # {"some_random_thing": "foo"}
"""
kwargs = utils.make_dict(fields, fields_kwargs)
if "interface_name" not in kwargs:
raise ValueError("no interface_name passed into Connection")
self.options = {}
for key, val in kwargs.items():
if hasattr(self, key):
setattr(self, key, val)
else:
self.options[key] = val
interface_module, interface_class = utils.get_objects(
self.interface_name
)
self.interface_class = interface_class
def get(self, key, default=None):
"""Works similar dict.get"""
return getattr(self, key, default)
class DsnConnection(Connection):
"""
sets up a connection configuration using a "prom dsn" or connection string
the prom dsn is in the form:
<SCHEME>://<HOST>/<PATH>?<QUERY>#<FRAGMENT>
Where <SCHEME> is:
<full.python.path.InterfaceClass>
And <HOST> is:
://<username>:<password>@<host>:<port>
And <PATH> is:
/<database>
And <QUERY> is:
?<options=val&query=string>
And <FRAGMENT> is:
#<connection-name>
This is useful to allow connections coming in through environment variables
as described in :
http://www.12factor.net/backing-services
It tooks its inspiration from this project:
https://github.com/kennethreitz/dj-database-url
http://en.wikipedia.org/wiki/Connection_string
http://en.wikipedia.org/wiki/Data_source_name
"""
dsn = ""
"""holds the raw dsn string that was parsed"""
def __init__(self, dsn):
# get the scheme, which is actually our interface_name
kwargs = self.parse(dsn)
super().__init__(**kwargs)
def parse(self, dsn):
parser = dsnparse.parse(dsn)
d = parser.fields
d["dsn"] = parser.parser.dsn
# remap certain values
d["name"] = d.pop("fragment")
d["interface_name"] = self.normalize_scheme(d.pop("scheme"))
d["database"] = parser.database
d["options"] = d.pop("query_params", {})
d["host"] = d.pop("hostname")
d["readonly"] = bool(d["options"].pop("readonly", self.readonly))
# get rid of certain values
d.pop("params", None)
return d
def normalize_scheme(self, v):
ret = v
d = {
"prom.interface.sqlite.SQLite": set(["sqlite"]),
"prom.interface.postgres.PostgreSQL": set(
["postgres", "postgresql", "psql"]
)
}
kv = v.lower()
for interface_name, vals in d.items():
if kv in vals:
ret = interface_name
break
return ret
class Schema(object):
"""
handles all table schema definition
the table schema definition includes the table name, the fields the table
has, and the indexes that are on the table
"""
instances = {}
"""class variable, holds different schema instances for various orms"""
table_name = ""
"""string -- set the table name for this schema instance"""
fields = None
"""dict -- all the fields this schema instance will use"""
indexes = None
"""dict -- all the indexes this schema will have"""
lookup = None
"""dict -- field information lookup table, basically an internal cache"""
@property
def normal_fields(self):
"""fields that aren't magic (eg, don't start with an underscore)"""
return {f:v for f, v in self.fields.items() if not f.startswith('_')}
@property
def required_fields(self):
"""The normal required fields (eg, no magic fields like _id are
included)
"""
return {f:v for f, v in self.normal_fields.items() if v.required}
@property
def ref_fields(self):
"""Return FK reference fields"""
return {f:v for f, v in self.normal_fields.items() if v.is_ref()}
@property
def magic_fields(self):
"""the magic fields for the schema, magic fields start with an
underscore
"""
return {f:v for f, v in self.fields.items() if f.startswith('_')}
@property
def pk_fields(self):
pk_fields = {}
for pk_name in self.pk_names:
pk_fields[pk_name] = self.fields[pk_name]
return pk_fields
@property
def pk_name(self):
"""returns the primary key name for this schema"""
try:
pk_field = self.__getattr__("pk")
pk_name = pk_field.name
except AttributeError:
pk_name = None
return pk_name
@property
def pk_names(self):
"""Returns all the field names comprising the primary key as a list"""
pk_name = self.pk_name
return [pk_name] if pk_name else []
@property
def schemas(self):
"""Find and return all the schemas that are needed for this schema to
install successfully
Another way to put this is all the schemas this Schema touches
:returns: list, a list of Schema instances, self will be at the end
"""
schemas = []
for f in self.fields.values():
if s := f.schema:
schemas.extend(s.schemas)
schemas.append(self)
return schemas
@classmethod
def get_instance(cls, orm_class, **kwargs):
"""return a Schema singleton instance for the given orm_class
if there isn't already an instance in cache then a new instance will be
created. If a Schema instance is already in cache then it will be
returned
:param orm_class: Orm, the class to create the schema for
:returns: Schema
"""
table_name = orm_class.table_name
if table_name in cls.instances:
s = cls.instances[table_name]
else:
s = cls(table_name)
s.orm_class = orm_class
seen_properties = {}
for klass in inspect.getmro(orm_class)[:-1]:
for k, v in vars(klass).items():
k = String(k)
field = None
if isinstance(v, Field):
field = v
elif isinstance(v, Index):
s.set_index(k, v)
seen_properties[k] = v
elif isinstance(v, type) and issubclass(v, Field):
# We've defined a Field class inline of the Orm, so we
# want to instantiate it and set it in all the places
field = v.get_instance()
else:
if v is None:
seen_properties[k] = v
if field:
if k in seen_properties:
if seen_properties[k] is None:
for fn in field.names:
s.lookup["field_names_deleted"][fn] = k
else:
s.set_field(k, field)
seen_properties[k] = field
cls.instances[table_name] = s
return s
def __init__(self, table_name, **fields_or_indexes):
"""Create an instance
every Orm should have a .schema attribute that is an instance of this
class
:example:
schema = Schema(
"table_name"
field1=Field(int, True),
field2=Field(str),
index_fields=Index("field1", "field2")
)
:param table_name: string, the table name
:param **fields_or_indexes: a dict of field name or index keys with
tuple values, see __getattr__ for more details
"""
self.fields = {}
self.indexes = {}
self.table_name = String(table_name)
self.orm_class = None
self.lookup = {
"field_names": {},
# holds parent's Field.names that have been set to None in children
# classes. Basically, if a parent class sets foo and then a child
# class later on sets foo = None then foo.names will be here
"field_names_deleted": {},
}
for name, val in fields_or_indexes.items():
self.set(name, val)
def __str__(self):
return self.table_name
def __iter__(self):
"""iterate through all the fields defined in this schema
:returns: tuple, (name, Field)
"""
return (f for f in self.fields.items())
def set(self, name, val):
if isinstance(val, Field):
self.set_field(name, val)
elif isinstance(val, Index):
self.set_index(name, val)
else:
raise TypeError("Not a Field or Index instance")
def __getattr__(self, name):
"""return the Field instance for the given name
:returns: str, the string value of the attribute name, eg, self.foo
returns "foo"
"""
try:
return self.lookup["field_names"][name]
except KeyError:
raise AttributeError(
"No {} field in schema {}".format(name, self.table_name)
)
def has_field(self, field_name):
"""Return True if schema contains field_name"""
return field_name in self.lookup["field_names"]
def __contains__(self, field_name):
return self.has_field(field_name)
def set_field(self, field_name, field):
if not field_name:
raise ValueError("field_name is empty")
if field_name in self.fields:
raise ValueError(
f"{field_name} already exists and cannot be changed"
)
if not isinstance(field, Field):
raise ValueError(f"{type(field)} is not a Field instance")
field.__set_name__(self.orm_class, field_name)
if field.unique:
self.set_index(field_name, Index(field_name, unique=True))
if field.index:
self.set_index(field_name, Index(field_name))
self.fields[field_name] = field
for fn in field.names:
if fn in self.lookup["field_names"] and fn in field.aliases:
self.lookup["field_names"].pop(fn)
logger.warning(
" ".join([
"{} ignored alias {} for {} because it is".format(
self,
fn,
field.name,
),
"used by another field",
])
)
else:
self.lookup["field_names"][fn] = field
return self
def set_index(self, index_name, index):
"""Add an index to the schema
for the most part, you will use the __getattr__ method of adding
indexes for a more fluid interface, but you can use this if you want to
get closer to the bare metal
:param index_name: str, the name of the index
:param index: Index, an Index instance
"""
if not index_name:
raise ValueError("index_name must have a value")
if index_name in self.indexes:
raise ValueError(
"index_name {} has already been defined on {}".format(
index_name, str(self.indexes[index_name].field_names)
)
)
if not isinstance(index, Index):
raise ValueError(f"{type(index)} is not an Index instance")
index.name = index_name
index.orm_class = self.orm_class
self.indexes[index_name] = index
return self
def field_name(self, field_name, *default):
"""Get the canonical field name of field_name
most of the time, the field name of field_name will just be field_name,
but this checks the configured aliases to return the canonical name
:param field_name: str, the field_name you want the canonical field
name for
:param *default: mixed, if present this will be returned instead of
AttributeError raised if field_name doesn't exist
"""
try:
return self.__getattr__(field_name).name
except AttributeError:
if default:
return default[0]
else:
if field_name in self.lookup["field_names_deleted"]:
try:
return self.lookup["field_names_deleted"][field_name]
except KeyError as e:
raise AttributeError(field_name) from e
else:
raise
def field_model_name(self, field_name):
"""Check field_name against all the field's ref model names to see if
there is a match, this is separate from .field_name because there are
times when this behavior might not be desirable
:param field_name: str, the field/model name you want the canonical
field name for
:returns: str, the canonical field name
"""
for fn, field in self.fields.items():
if field_name in field.ref_names:
return fn
raise AttributeError(field_name)
def create_orm(self, orm_class=None):
"""If you have a schema but don't have an Orm for it, you can call this
method and have an orm_class created that will have the fields and
table_name of this schema
:param orm_class: Orm, if you want your generated class to have a
certain parent class you can pass in the parent class you want
:returns: Orm, your child orm populated with information from this
schema
"""
if not orm_class:
from .model import Orm # avoid circular dependency
orm_class = Orm
child_class = type(
String(self.table_name),
(orm_class,),
{"table_name": self.table_name, "schema": self}
)
# clear all the Field and Index properties in anticipation of adding
# the fields from the Schema
seen_properties = set()
for klass in inspect.getmro(child_class):
for k, v in vars(klass).items():
if k not in seen_properties:
if isinstance(v, (Field, Index)):
setattr(child_class, k, None)
elif isinstance(v, type) and issubclass(v, Field):
setattr(child_class, k, None)
seen_properties.add(k)
for field_name, field in self:
setattr(child_class, field_name, field)
return child_class
class Index(object):
"""Each index on the table is configured using this class
"""
def __init__(self, *field_names, **options):
"""initialize an index
:param *field_names: the string field names this index will index on,
fields have to be already added to this schema index
:param **options:
- unique: bool, True if the index should be unique, false otherwise
"""
if not field_names:
raise ValueError("field_names list is empty")
self.name = ""
self.field_names = list(map(String, field_names))
self.options = options
self.unique = options.get("unique", False)
class FieldMeta(type):
"""Allows a class definition to be a descriptor also
I don't love this solution, but I like the syntax of just being able to
define a subclass inside an Orm and have it work. The problem is an
embedded class isn't, by default, a descriptor instance, so it wasn't
calling fset, fget, and fdel.
This makes it so an embedded field class will be treated as a descriptor.
It uses an embedded .instance property to actually perform the operations
"""
def __set_name__(cls, orm_class, name):
"""I'm not quite sure why this works, but it does. Basically, when you
define the field as an embedded class in the orm, this method will get
called when the class is being parsed/loaded the first time.
So this method gets called and we use cls to create a Field instance
and we then set our newly created instance onto orm_class.name. So
after this method is called, orm_class.name will be a Field instance
instead of a Field subclass
"""
logger.debug(
"Creating field descriptor {}.{} with class {}".format(
orm_class.__name__,
name,
cls.__name__
)
)
instance = cls(cls.type, cls.required, cls.options)
instance.__set_name__(orm_class, name)
setattr(orm_class, name, instance)
class Field(object, metaclass=FieldMeta):
"""Each column in the database is configured using this class
You can set some getters and setters on this object in order to fine tune
control over how a field in the db is set and fetched from the instance and
also how it is set and fetched from the interface
to customize the field on set and get from the db, you can use the
decorators, which are classmethods:
:Example:
foo = Field(str, True)
@foo.igetter
def foo(self, val):
# do custom things when pulling foo from the database
return val
@foo.isetter
def foo(self, val):
# do custom things when putting foo into the database
return val
There are also fget/fset/fdel methods that can be set to customize behavior
on when a value is set on a particular orm instance, so if you wanted to
make sure that bar was always an int when it is set, you could:
:Example:
bar = Field(int, True)
@bar.fsetter
def bar(self, val):
# do custom things
return int(val)
@bar.fgetter
def bar(self, val):
return int(val)
@bar.jsonabler
def bar(self, name, val):
# convert val to something json safe, you can also change the name
return name, val
NOTE -- all these get/set/delete methods are different than traditional
python getters and setters because they always need to return a value and
they always take in the object instance manipulating them and the value.
NOTE -- Foreign key's can be passed orm instances from other classes
because those classes will call the FK's field methods when getting/setting
the field
You can also configure the Field using a class:
:Example:
class bar(Field):
type = int
required = True
options = {
"default": 0,
"unique": True,
"max_size": 512,
}
def fget(self, orm, v):
print("fget")
return v
def iget(self, orm, v):
print("iget")
return v
def fset(self, orm, v):
print("fset")
return v
def fdel(self, orm, v):
print("fdel")
return v
def iquery(self, query, v):
print("iquery")
return v
def jsonable(self, orm, field_name, v):
print("jsonable")
return field_name, v
https://docs.python.org/2/howto/descriptor.html
"""
required = False
"""True if this field is required"""
options = None
"""In the instance, this will be a dict of key/val pairs containing extra
information about the field"""
default = None
"""Default value for this field"""
help = ""
"""The description/help message for this field"""
name = ""
"""The field name"""
choices = None
"""A set of values that this field can be, if set then no other values can
be set"""
unique = False
"""True if this field is unique indexed"""
index = False
"""True if this field is indexed"""
orm_class = None
"""Holds the model class this field is defined on"""
@cachedproperty(cached="_schema")
def schema(self):
"""return the schema instance if this field is a reference to another
table
see .set_type() for an explanation on why we defer figuring this out
until now
"""
field_type = self.original_type
module, klass = utils.get_objects(field_type)
schema = klass.schema
if not schema:
raise ValueError(
"Field type {} is not an Orm class".format(field_type)
)
return schema
@property
def type(self):
"""alias of the interface type, this is really here so you can set it
to a value if you are inline defining a field, this will get passed to
the __init__ method and then be used to set ._interface_type"""
return self.interface_type
@property
def interface_type(self):
"""Returns the type that will be used in the interface to create the
table
see .set_type() for an explanation on why we defer this until here
"""
if self._interface_type is None:
if self.is_serialized():
self._interface_type = str
else:
s = self.schema
if s:
self._interface_type = s.pk.type
else:
self._interface_type = self.original_type
return self._interface_type
@property
def ref(self):
"""Returns the FK reference orm class"""
schema = self.schema
return schema.orm_class if schema else None
@property
def ref_class(self):
return self.ref
@property
def names(self):
names = set()
if self.name:
names.add(self.name)
names.update(self.aliases)
return names
@property
def aliases(self):
names = set()
names.update(self.options.get("names", []))
names.update(self.options.get("aliases", []))
if alias := self.options.get("alias", ""):
names.add(alias)
if self.is_pk():
names.add("pk")
if self.orm_class:
model_name = self.orm_class.model_name
names.add(f"{model_name}_id")
names.add(f"{model_name}_pk")
return names
@property
def ref_names(self):
"""Return the reference names for this field
:returns: set[str], basically a set of .ref.model_name and
.ref.models_name
"""
names = set()
if ref_class := self.ref:
names.add(ref_class.model_name)
names.add(ref_class.models_name)
return names
@property
def interface_options(self):
"""When the interface is doing stuff with the field it might call this
method to make sure it has all the options it needs to use the field
"""
if self.is_ref():
options = self.schema.pk.options
options.update(self.options)
else:
options = self.options
return options
def __init__(
self,
field_type,
field_required=False,
field_options=None,
**field_options_kwargs
):
"""
create a field
:param field_type: type, the python type of the field, so for a string
you would pass str, integer: int, boolean: bool, float: float
:param field_required: boolean, true if this field has to be there to
insert
:param field_options: Current options:
* size: int -- the size you want the string to be, or the int to be
* min_size: int -- the minimum size
* max_size: int -- if you want a varchar, set this
* unique: bool -- True to set a unique index on this field, this is
just for convenience and is equal to self.set_index(field_name,
[field_name], unique=True). this is a convenience option to set
a unique index on the field without having to add a separate
index statement
* ignore_case: bool -- True to ignore case if this field is used in
indexes
* default: mixed -- defaults to None, can be anything the db can
support
* jsonable_name: str, the name of the field when Orm.jsonable() is
called
* jsonable_field: bool, if False then this field won't be part of
Orm.jsonable() output
* jsonable: str|callable|bool,
- str, will be set to jsonable_name
- callable, will be used as self.jsonable
- bool, will set jsonable_field to False
* empty: bool, (default is True), set to False if the value cannot
be empty when being sent to the db (empty is None, "", 0,
or False)
* pk: bool, True to make this field the primary key
* auto: bool, True to tag this field as an auto-generated field.
Used with an int to set it to an auto-increment, use it with
UUID to have uuids auto generated
* autopk: bool, shortcut for setting pk=True, auto=True
* fvalue: callable[Any], called in the default .fset method to
normalize the value before setting the value as an attribute on
the orm
* ivalue: callable[Any], called in the default .iset method to
normalize the value before sending the value to the db
:param **field_options_kwargs: dict, will be combined with
field_options
"""
field_options = utils.make_dict(field_options, field_options_kwargs)
d = self.get_size(field_options)
field_options.update(d)
name = field_options.pop("name", "")
orm_class = field_options.pop("orm_class", None)
choices = field_options.pop("choices", set())
if choices or not self.choices:
self.choices = choices
if "jsonable" in field_options:
jsonable = field_options.pop("jsonable")
if isinstance(jsonable, str):
field_options.setdefault("jsonable_name", jsonable)
elif isinstance(jsonable, bool):
field_options.setdefault("jsonable_field", jsonable)
else:
field_options["jsonable"] = jsonable
if autopk := field_options.pop("autopk", False):
field_options["pk"] = autopk
field_options["auto"] = autopk
for k in list(field_options.keys()):
if hasattr(self, k):
setattr(self, k, field_options.pop(k))
self.options = field_options
self.required = field_required or self.is_pk()
self.set_type(field_type)
# this class is being created manually so mimic what the python parser
# would do
if name and orm_class:
self.__set_name__(orm_class, name)
elif orm_class:
self.orm_class = orm_class
elif name:
self.__set_name__(orm_class, name)
def __set_name__(self, orm_class, name):
"""This is called right after __init__
https://docs.python.org/3/howto/descriptor.html#customized-names
This is only called when an instance is created while a class is being
parsed/created, so if you just created an instance of Field you would
need to call this method manually
:param orm_class: type, the orm class this Field will belong to
:param name: str, the field's public name on the orm class
"""
self.orm_class = orm_class
self.name = name
# the field name this descriptor will use to set the value onto the orm
# instance
self.orm_field_name = f"_{name}"
# we keep a hash of the field's value when it was pulled from the
# interface (see .iget) so we know if the field has been modified
self.orm_interface_hash = f"_interface_{name}_hash"
if orm_class:
logger.debug(
"Field descriptor {}.{} created with internal name {}".format(
orm_class.__name__,
name,
self.orm_field_name
)
)
def get_size(self, field_options):
"""Figure out if this field has any size information"""
d = {}
min_size = field_options.pop("min_size", -1)
max_size = field_options.pop("max_size", -1)
size = field_options.pop("size", None)
if size is not None:
d['size'] = size
else:
if min_size > 0 and max_size < 0:
d['min_size'] = min_size
elif min_size < 0 and max_size > 0:
d['max_size'] = max_size
elif min_size > 0 and max_size > 0:
d['min_size'] = min_size
d['max_size'] = max_size
return d
def size_info(self):
"""Figure out actual sizing information with all the ways we can
calculate size now