| 1 |
# Copyright DataStax, Inc. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
from copy import deepcopy, copy |
| 16 |
from datetime import date, datetime, timedelta, timezone |
| 17 |
import logging |
| 18 |
from uuid import UUID as _UUID |
| 19 |
|
| 20 |
from cassandra import util |
| 21 |
from cassandra.cqltypes import SimpleDateType, _cqltypes, UserType |
| 22 |
from cassandra.cqlengine import ValidationError |
| 23 |
from cassandra.cqlengine.functions import get_total_seconds |
| 24 |
from cassandra.util import Duration as _Duration |
| 25 |
|
| 26 |
log = logging.getLogger(__name__) |
| 27 |
|
| 28 |
|
| 29 |
class BaseValueManager(object): |
| 30 |
|
| 31 |
def __init__(self, instance, column, value): |
| 32 |
self.instance = instance |
| 33 |
self.column = column |
| 34 |
self.value = value |
| 35 |
self.previous_value = None |
| 36 |
self.explicit = False |
| 37 |
|
| 38 |
@property |
| 39 |
def deleted(self): |
| 40 |
return self.column._val_is_null(self.value) and (self.explicit or not self.column._val_is_null(self.previous_value)) |
| 41 |
|
| 42 |
@property |
| 43 |
def changed(self): |
| 44 |
""" |
| 45 |
Indicates whether or not this value has changed. |
| 46 |
|
| 47 |
:rtype: boolean |
| 48 |
|
| 49 |
""" |
| 50 |
if self.explicit: |
| 51 |
return self.value != self.previous_value |
| 52 |
|
| 53 |
if isinstance(self.column, BaseContainerColumn): |
| 54 |
default_value = self.column.get_default() |
| 55 |
if self.column._val_is_null(default_value): |
| 56 |
return not self.column._val_is_null(self.value) and self.value != self.previous_value |
| 57 |
elif self.previous_value is None: |
| 58 |
return self.value != default_value |
| 59 |
|
| 60 |
return self.value != self.previous_value |
| 61 |
|
| 62 |
return False |
| 63 |
|
| 64 |
def reset_previous_value(self): |
| 65 |
self.previous_value = deepcopy(self.value) |
| 66 |
|
| 67 |
def getval(self): |
| 68 |
return self.value |
| 69 |
|
| 70 |
def setval(self, val): |
| 71 |
self.value = val |
| 72 |
self.explicit = True |
| 73 |
|
| 74 |
def delval(self): |
| 75 |
self.value = None |
| 76 |
|
| 77 |
def get_property(self): |
| 78 |
_get = lambda slf: self.getval() |
| 79 |
_set = lambda slf, val: self.setval(val) |
| 80 |
_del = lambda slf: self.delval() |
| 81 |
|
| 82 |
if self.column.can_delete: |
| 83 |
return property(_get, _set, _del) |
| 84 |
else: |
| 85 |
return property(_get, _set) |
| 86 |
|
| 87 |
|
| 88 |
class Column(object): |
| 89 |
|
| 90 |
# the cassandra type this column maps to |
| 91 |
db_type = None |
| 92 |
value_manager = BaseValueManager |
| 93 |
|
| 94 |
instance_counter = 0 |
| 95 |
|
| 96 |
_python_type_hashable = True |
| 97 |
|
| 98 |
primary_key = False |
| 99 |
""" |
| 100 |
bool flag, indicates this column is a primary key. The first primary key defined |
| 101 |
on a model is the partition key (unless partition keys are set), all others are cluster keys |
| 102 |
""" |
| 103 |
|
| 104 |
partition_key = False |
| 105 |
|
| 106 |
""" |
| 107 |
indicates that this column should be the partition key, defining |
| 108 |
more than one partition key column creates a compound partition key |
| 109 |
""" |
| 110 |
|
| 111 |
index = False |
| 112 |
""" |
| 113 |
bool flag, indicates an index should be created for this column |
| 114 |
""" |
| 115 |
|
| 116 |
custom_index = False |
| 117 |
""" |
| 118 |
bool flag, indicates an index is managed outside of cqlengine. This is |
| 119 |
useful if you want to do filter queries on fields that have custom |
| 120 |
indexes. |
| 121 |
""" |
| 122 |
|
| 123 |
db_field = None |
| 124 |
""" |
| 125 |
the fieldname this field will map to in the database |
| 126 |
""" |
| 127 |
|
| 128 |
default = None |
| 129 |
""" |
| 130 |
the default value, can be a value or a callable (no args) |
| 131 |
""" |
| 132 |
|
| 133 |
required = False |
| 134 |
""" |
| 135 |
boolean, is the field required? Model validation will raise and |
| 136 |
exception if required is set to True and there is a None value assigned |
| 137 |
""" |
| 138 |
|
| 139 |
clustering_order = None |
| 140 |
""" |
| 141 |
only applicable on clustering keys (primary keys that are not partition keys) |
| 142 |
determines the order that the clustering keys are sorted on disk |
| 143 |
""" |
| 144 |
|
| 145 |
discriminator_column = False |
| 146 |
""" |
| 147 |
boolean, if set to True, this column will be used for discriminating records |
| 148 |
of inherited models. |
| 149 |
|
| 150 |
Should only be set on a column of an abstract model being used for inheritance. |
| 151 |
|
| 152 |
There may only be one discriminator column per model. See :attr:`~.__discriminator_value__` |
| 153 |
for how to specify the value of this column on specialized models. |
| 154 |
""" |
| 155 |
|
| 156 |
static = False |
| 157 |
""" |
| 158 |
boolean, if set to True, this is a static column, with a single value per partition |
| 159 |
""" |
| 160 |
|
| 161 |
def __init__(self, |
| 162 |
primary_key=False, |
| 163 |
partition_key=False, |
| 164 |
index=False, |
| 165 |
db_field=None, |
| 166 |
default=None, |
| 167 |
required=False, |
| 168 |
clustering_order=None, |
| 169 |
discriminator_column=False, |
| 170 |
static=False, |
| 171 |
custom_index=False): |
| 172 |
self.partition_key = partition_key |
| 173 |
self.primary_key = partition_key or primary_key |
| 174 |
self.index = index |
| 175 |
self.custom_index = custom_index |
| 176 |
self.db_field = db_field |
| 177 |
self.default = default |
| 178 |
self.required = required |
| 179 |
self.clustering_order = clustering_order |
| 180 |
self.discriminator_column = discriminator_column |
| 181 |
|
| 182 |
# the column name in the model definition |
| 183 |
self.column_name = None |
| 184 |
self._partition_key_index = None |
| 185 |
self.static = static |
| 186 |
|
| 187 |
self.value = None |
| 188 |
|
| 189 |
# keep track of instantiation order |
| 190 |
self.position = Column.instance_counter |
| 191 |
Column.instance_counter += 1 |
| 192 |
|
| 193 |
def __ne__(self, other): |
| 194 |
if isinstance(other, Column): |
| 195 |
return self.position != other.position |
| 196 |
return NotImplemented |
| 197 |
|
| 198 |
def __eq__(self, other): |
| 199 |
if isinstance(other, Column): |
| 200 |
return self.position == other.position |
| 201 |
return NotImplemented |
| 202 |
|
| 203 |
def __lt__(self, other): |
| 204 |
if isinstance(other, Column): |
| 205 |
return self.position < other.position |
| 206 |
return NotImplemented |
| 207 |
|
| 208 |
def __le__(self, other): |
| 209 |
if isinstance(other, Column): |
| 210 |
return self.position <= other.position |
| 211 |
return NotImplemented |
| 212 |
|
| 213 |
def __gt__(self, other): |
| 214 |
if isinstance(other, Column): |
| 215 |
return self.position > other.position |
| 216 |
return NotImplemented |
| 217 |
|
| 218 |
def __ge__(self, other): |
| 219 |
if isinstance(other, Column): |
| 220 |
return self.position >= other.position |
| 221 |
return NotImplemented |
| 222 |
|
| 223 |
def __hash__(self): |
| 224 |
return id(self) |
| 225 |
|
| 226 |
def validate(self, value): |
| 227 |
""" |
| 228 |
Returns a cleaned and validated value. Raises a ValidationError |
| 229 |
if there's a problem |
| 230 |
""" |
| 231 |
if value is None: |
| 232 |
if self.required: |
| 233 |
raise ValidationError('{0} - None values are not allowed'.format(self.column_name or self.db_field)) |
| 234 |
return value |
| 235 |
|
| 236 |
def to_python(self, value): |
| 237 |
""" |
| 238 |
Converts data from the database into python values |
| 239 |
raises a ValidationError if the value can't be converted |
| 240 |
""" |
| 241 |
return value |
| 242 |
|
| 243 |
def to_database(self, value): |
| 244 |
""" |
| 245 |
Converts python value into database value |
| 246 |
""" |
| 247 |
return value |
| 248 |
|
| 249 |
@property |
| 250 |
def has_default(self): |
| 251 |
return self.default is not None |
| 252 |
|
| 253 |
@property |
| 254 |
def is_primary_key(self): |
| 255 |
return self.primary_key |
| 256 |
|
| 257 |
@property |
| 258 |
def can_delete(self): |
| 259 |
return not self.primary_key |
| 260 |
|
| 261 |
def get_default(self): |
| 262 |
if self.has_default: |
| 263 |
if callable(self.default): |
| 264 |
return self.default() |
| 265 |
else: |
| 266 |
return self.default |
| 267 |
|
| 268 |
def get_column_def(self): |
| 269 |
""" |
| 270 |
Returns a column definition for CQL table definition |
| 271 |
""" |
| 272 |
static = "static" if self.static else "" |
| 273 |
return '{0} {1} {2}'.format(self.cql, self.db_type, static) |
| 274 |
|
| 275 |
# TODO: make columns use cqltypes under the hood |
| 276 |
# until then, this bridges the gap in using types along with cassandra.metadata for CQL generation |
| 277 |
def cql_parameterized_type(self): |
| 278 |
return self.db_type |
| 279 |
|
| 280 |
def set_column_name(self, name): |
| 281 |
""" |
| 282 |
Sets the column name during document class construction |
| 283 |
This value will be ignored if db_field is set in __init__ |
| 284 |
""" |
| 285 |
self.column_name = name |
| 286 |
|
| 287 |
@property |
| 288 |
def db_field_name(self): |
| 289 |
""" Returns the name of the cql name of this column """ |
| 290 |
return self.db_field if self.db_field is not None else self.column_name |
| 291 |
|
| 292 |
@property |
| 293 |
def db_index_name(self): |
| 294 |
""" Returns the name of the cql index """ |
| 295 |
return 'index_{0}'.format(self.db_field_name) |
| 296 |
|
| 297 |
@property |
| 298 |
def has_index(self): |
| 299 |
return self.index or self.custom_index |
| 300 |
|
| 301 |
@property |
| 302 |
def cql(self): |
| 303 |
return self.get_cql() |
| 304 |
|
| 305 |
def get_cql(self): |
| 306 |
return '"{0}"'.format(self.db_field_name) |
| 307 |
|
| 308 |
def _val_is_null(self, val): |
| 309 |
""" determines if the given value equates to a null value for the given column type """ |
| 310 |
return val is None |
| 311 |
|
| 312 |
@property |
| 313 |
def sub_types(self): |
| 314 |
return [] |
| 315 |
|
| 316 |
@property |
| 317 |
def cql_type(self): |
| 318 |
return _cqltypes[self.db_type] |
| 319 |
|
| 320 |
|
| 321 |
class Blob(Column): |
| 322 |
""" |
| 323 |
Stores a raw binary value |
| 324 |
""" |
| 325 |
db_type = 'blob' |
| 326 |
|
| 327 |
def to_database(self, value): |
| 328 |
|
| 329 |
if not isinstance(value, (bytes, bytearray)): |
| 330 |
raise Exception("expecting a binary, got a %s" % type(value)) |
| 331 |
|
| 332 |
val = super(Bytes, self).to_database(value) |
| 333 |
return bytearray(val) |
| 334 |
|
| 335 |
|
| 336 |
Bytes = Blob |
| 337 |
|
| 338 |
|
| 339 |
class Inet(Column): |
| 340 |
""" |
| 341 |
Stores an IP address in IPv4 or IPv6 format |
| 342 |
""" |
| 343 |
db_type = 'inet' |
| 344 |
|
| 345 |
|
| 346 |
class Text(Column): |
| 347 |
""" |
| 348 |
Stores a UTF-8 encoded string |
| 349 |
""" |
| 350 |
db_type = 'text' |
| 351 |
|
| 352 |
def __init__(self, min_length=None, max_length=None, **kwargs): |
| 353 |
""" |
| 354 |
:param int min_length: Sets the minimum length of this string, for validation purposes. |
| 355 |
Defaults to 1 if this is a ``required`` column. Otherwise, None. |
| 356 |
:param int max_length: Sets the maximum length of this string, for validation purposes. |
| 357 |
""" |
| 358 |
self.min_length = ( |
| 359 |
1 if min_length is None and kwargs.get('required', False) |
| 360 |
else min_length) |
| 361 |
self.max_length = max_length |
| 362 |
|
| 363 |
if self.min_length is not None: |
| 364 |
if self.min_length < 0: |
| 365 |
raise ValueError( |
| 366 |
'Minimum length is not allowed to be negative.') |
| 367 |
|
| 368 |
if self.max_length is not None: |
| 369 |
if self.max_length < 0: |
| 370 |
raise ValueError( |
| 371 |
'Maximum length is not allowed to be negative.') |
| 372 |
|
| 373 |
if self.min_length is not None and self.max_length is not None: |
| 374 |
if self.max_length < self.min_length: |
| 375 |
raise ValueError( |
| 376 |
'Maximum length must be greater or equal ' |
| 377 |
'to minimum length.') |
| 378 |
|
| 379 |
super(Text, self).__init__(**kwargs) |
| 380 |
|
| 381 |
def validate(self, value): |
| 382 |
value = super(Text, self).validate(value) |
| 383 |
if not isinstance(value, (str, bytearray)) and value is not None: |
| 384 |
raise ValidationError('{0} {1} is not a string'.format(self.column_name, type(value))) |
| 385 |
if self.max_length is not None: |
| 386 |
if value and len(value) > self.max_length: |
| 387 |
raise ValidationError('{0} is longer than {1} characters'.format(self.column_name, self.max_length)) |
| 388 |
if self.min_length: |
| 389 |
if (self.min_length and not value) or len(value) < self.min_length: |
| 390 |
raise ValidationError('{0} is shorter than {1} characters'.format(self.column_name, self.min_length)) |
| 391 |
return value |
| 392 |
|
| 393 |
|
| 394 |
class Ascii(Text): |
| 395 |
""" |
| 396 |
Stores a US-ASCII character string |
| 397 |
""" |
| 398 |
db_type = 'ascii' |
| 399 |
|
| 400 |
def validate(self, value): |
| 401 |
""" Only allow ASCII and None values. |
| 402 |
|
| 403 |
Check against US-ASCII, a.k.a. 7-bit ASCII, a.k.a. ISO646-US, a.k.a. |
| 404 |
the Basic Latin block of the Unicode character set. |
| 405 |
|
| 406 |
Source: https://github.com/apache/cassandra/blob |
| 407 |
/3dcbe90e02440e6ee534f643c7603d50ca08482b/src/java/org/apache/cassandra |
| 408 |
/serializers/AsciiSerializer.java#L29 |
| 409 |
""" |
| 410 |
value = super(Ascii, self).validate(value) |
| 411 |
if value: |
| 412 |
charset = value if isinstance( |
| 413 |
value, (bytearray, )) else map(ord, value) |
| 414 |
if not set(range(128)).issuperset(charset): |
| 415 |
raise ValidationError( |
| 416 |
'{!r} is not an ASCII string.'.format(value)) |
| 417 |
return value |
| 418 |
|
| 419 |
|
| 420 |
class Integer(Column): |
| 421 |
""" |
| 422 |
Stores a 32-bit signed integer value |
| 423 |
""" |
| 424 |
|
| 425 |
db_type = 'int' |
| 426 |
|
| 427 |
def validate(self, value): |
| 428 |
val = super(Integer, self).validate(value) |
| 429 |
if val is None: |
| 430 |
return |
| 431 |
try: |
| 432 |
return int(val) |
| 433 |
except (TypeError, ValueError): |
| 434 |
raise ValidationError("{0} {1} can't be converted to integral value".format(self.column_name, value)) |
| 435 |
|
| 436 |
def to_python(self, value): |
| 437 |
return self.validate(value) |
| 438 |
|
| 439 |
def to_database(self, value): |
| 440 |
return self.validate(value) |
| 441 |
|
| 442 |
|
| 443 |
class TinyInt(Integer): |
| 444 |
""" |
| 445 |
Stores an 8-bit signed integer value |
| 446 |
|
| 447 |
.. versionadded:: 2.6.0 |
| 448 |
|
| 449 |
requires C* 2.2+ and protocol v4+ |
| 450 |
""" |
| 451 |
db_type = 'tinyint' |
| 452 |
|
| 453 |
|
| 454 |
class SmallInt(Integer): |
| 455 |
""" |
| 456 |
Stores a 16-bit signed integer value |
| 457 |
|
| 458 |
.. versionadded:: 2.6.0 |
| 459 |
|
| 460 |
requires C* 2.2+ and protocol v4+ |
| 461 |
""" |
| 462 |
db_type = 'smallint' |
| 463 |
|
| 464 |
|
| 465 |
class BigInt(Integer): |
| 466 |
""" |
| 467 |
Stores a 64-bit signed integer value |
| 468 |
""" |
| 469 |
db_type = 'bigint' |
| 470 |
|
| 471 |
|
| 472 |
class VarInt(Column): |
| 473 |
""" |
| 474 |
Stores an arbitrary-precision integer |
| 475 |
""" |
| 476 |
db_type = 'varint' |
| 477 |
|
| 478 |
def validate(self, value): |
| 479 |
val = super(VarInt, self).validate(value) |
| 480 |
if val is None: |
| 481 |
return |
| 482 |
try: |
| 483 |
return int(val) |
| 484 |
except (TypeError, ValueError): |
| 485 |
raise ValidationError( |
| 486 |
"{0} {1} can't be converted to integral value".format(self.column_name, value)) |
| 487 |
|
| 488 |
def to_python(self, value): |
| 489 |
return self.validate(value) |
| 490 |
|
| 491 |
def to_database(self, value): |
| 492 |
return self.validate(value) |
| 493 |
|
| 494 |
|
| 495 |
class CounterValueManager(BaseValueManager): |
| 496 |
def __init__(self, instance, column, value): |
| 497 |
super(CounterValueManager, self).__init__(instance, column, value) |
| 498 |
self.value = self.value or 0 |
| 499 |
self.previous_value = self.previous_value or 0 |
| 500 |
|
| 501 |
|
| 502 |
class Counter(Integer): |
| 503 |
""" |
| 504 |
Stores a counter that can be incremented and decremented |
| 505 |
""" |
| 506 |
db_type = 'counter' |
| 507 |
|
| 508 |
value_manager = CounterValueManager |
| 509 |
|
| 510 |
def __init__(self, |
| 511 |
index=False, |
| 512 |
db_field=None, |
| 513 |
required=False): |
| 514 |
super(Counter, self).__init__( |
| 515 |
primary_key=False, |
| 516 |
partition_key=False, |
| 517 |
index=index, |
| 518 |
db_field=db_field, |
| 519 |
default=0, |
| 520 |
required=required, |
| 521 |
) |
| 522 |
|
| 523 |
|
| 524 |
class DateTime(Column): |
| 525 |
""" |
| 526 |
Stores a datetime value |
| 527 |
""" |
| 528 |
db_type = 'timestamp' |
| 529 |
|
| 530 |
truncate_microseconds = False |
| 531 |
""" |
| 532 |
Set this ``True`` to have model instances truncate the date, quantizing it in the same way it will be in the database. |
| 533 |
This allows equality comparison between assigned values and values read back from the database:: |
| 534 |
|
| 535 |
DateTime.truncate_microseconds = True |
| 536 |
assert Model.create(id=0, d=datetime.utcnow()) == Model.objects(id=0).first() |
| 537 |
|
| 538 |
Defaults to ``False`` to preserve legacy behavior. May change in the future. |
| 539 |
""" |
| 540 |
|
| 541 |
def to_python(self, value): |
| 542 |
if value is None: |
| 543 |
return |
| 544 |
if isinstance(value, datetime): |
| 545 |
if DateTime.truncate_microseconds: |
| 546 |
us = value.microsecond |
| 547 |
truncated_us = us // 1000 * 1000 |
| 548 |
return value - timedelta(microseconds=us - truncated_us) |
| 549 |
else: |
| 550 |
return value |
| 551 |
elif isinstance(value, date): |
| 552 |
return datetime(*(value.timetuple()[:6])) |
| 553 |
|
| 554 |
return datetime.fromtimestamp(value, tz=timezone.utc).replace(tzinfo=None) |
| 555 |
|
| 556 |
def to_database(self, value): |
| 557 |
value = super(DateTime, self).to_database(value) |
| 558 |
if value is None: |
| 559 |
return |
| 560 |
if not isinstance(value, datetime): |
| 561 |
if isinstance(value, date): |
| 562 |
value = datetime(value.year, value.month, value.day) |
| 563 |
else: |
| 564 |
raise ValidationError("{0} '{1}' is not a datetime object".format(self.column_name, value)) |
| 565 |
epoch = datetime(1970, 1, 1, tzinfo=value.tzinfo) |
| 566 |
offset = get_total_seconds(epoch.tzinfo.utcoffset(epoch)) if epoch.tzinfo else 0 |
| 567 |
|
| 568 |
return int((get_total_seconds(value - epoch) - offset) * 1000) |
| 569 |
|
| 570 |
|
| 571 |
class Date(Column): |
| 572 |
""" |
| 573 |
Stores a simple date, with no time-of-day |
| 574 |
|
| 575 |
.. versionchanged:: 2.6.0 |
| 576 |
|
| 577 |
removed overload of Date and DateTime. DateTime is a drop-in replacement for legacy models |
| 578 |
|
| 579 |
requires C* 2.2+ and protocol v4+ |
| 580 |
""" |
| 581 |
db_type = 'date' |
| 582 |
|
| 583 |
def to_database(self, value): |
| 584 |
if value is None: |
| 585 |
return |
| 586 |
|
| 587 |
# need to translate to int version because some dates are not representable in |
| 588 |
# string form (datetime limitation) |
| 589 |
d = value if isinstance(value, util.Date) else util.Date(value) |
| 590 |
return d.days_from_epoch + SimpleDateType.EPOCH_OFFSET_DAYS |
| 591 |
|
| 592 |
def to_python(self, value): |
| 593 |
if value is None: |
| 594 |
return |
| 595 |
if isinstance(value, util.Date): |
| 596 |
return value |
| 597 |
if isinstance(value, datetime): |
| 598 |
value = value.date() |
| 599 |
return util.Date(value) |
| 600 |
|
| 601 |
class Time(Column): |
| 602 |
""" |
| 603 |
Stores a timezone-naive time-of-day, with nanosecond precision |
| 604 |
|
| 605 |
.. versionadded:: 2.6.0 |
| 606 |
|
| 607 |
requires C* 2.2+ and protocol v4+ |
| 608 |
""" |
| 609 |
db_type = 'time' |
| 610 |
|
| 611 |
def to_database(self, value): |
| 612 |
value = super(Time, self).to_database(value) |
| 613 |
if value is None: |
| 614 |
return |
| 615 |
# str(util.Time) yields desired CQL encoding |
| 616 |
return value if isinstance(value, util.Time) else util.Time(value) |
| 617 |
|
| 618 |
def to_python(self, value): |
| 619 |
value = super(Time, self).to_database(value) |
| 620 |
if value is None: |
| 621 |
return |
| 622 |
if isinstance(value, util.Time): |
| 623 |
return value |
| 624 |
return util.Time(value) |
| 625 |
|
| 626 |
class Duration(Column): |
| 627 |
""" |
| 628 |
Stores a duration (months, days, nanoseconds) |
| 629 |
|
| 630 |
.. versionadded:: 3.10.0 |
| 631 |
|
| 632 |
requires C* 3.10+ and protocol v4+ |
| 633 |
""" |
| 634 |
db_type = 'duration' |
| 635 |
|
| 636 |
def validate(self, value): |
| 637 |
val = super(Duration, self).validate(value) |
| 638 |
if val is None: |
| 639 |
return |
| 640 |
if not isinstance(val, _Duration): |
| 641 |
raise TypeError('{0} {1} is not a valid Duration.'.format(self.column_name, value)) |
| 642 |
return val |
| 643 |
|
| 644 |
|
| 645 |
class UUID(Column): |
| 646 |
""" |
| 647 |
Stores a type 1 or 4 UUID |
| 648 |
""" |
| 649 |
db_type = 'uuid' |
| 650 |
|
| 651 |
def validate(self, value): |
| 652 |
val = super(UUID, self).validate(value) |
| 653 |
if val is None: |
| 654 |
return |
| 655 |
if isinstance(val, _UUID): |
| 656 |
return val |
| 657 |
if isinstance(val, str): |
| 658 |
try: |
| 659 |
return _UUID(val) |
| 660 |
except ValueError: |
| 661 |
# fall-through to error |
| 662 |
pass |
| 663 |
raise ValidationError("{0} {1} is not a valid uuid".format( |
| 664 |
self.column_name, value)) |
| 665 |
|
| 666 |
def to_python(self, value): |
| 667 |
return self.validate(value) |
| 668 |
|
| 669 |
def to_database(self, value): |
| 670 |
return self.validate(value) |
| 671 |
|
| 672 |
|
| 673 |
class TimeUUID(UUID): |
| 674 |
""" |
| 675 |
UUID containing timestamp |
| 676 |
""" |
| 677 |
|
| 678 |
db_type = 'timeuuid' |
| 679 |
|
| 680 |
|
| 681 |
class Boolean(Column): |
| 682 |
""" |
| 683 |
Stores a boolean True or False value |
| 684 |
""" |
| 685 |
db_type = 'boolean' |
| 686 |
|
| 687 |
def validate(self, value): |
| 688 |
""" Always returns a Python boolean. """ |
| 689 |
value = super(Boolean, self).validate(value) |
| 690 |
|
| 691 |
if value is not None: |
| 692 |
value = bool(value) |
| 693 |
|
| 694 |
return value |
| 695 |
|
| 696 |
def to_python(self, value): |
| 697 |
return self.validate(value) |
| 698 |
|
| 699 |
|
| 700 |
class BaseFloat(Column): |
| 701 |
def validate(self, value): |
| 702 |
value = super(BaseFloat, self).validate(value) |
| 703 |
if value is None: |
| 704 |
return |
| 705 |
try: |
| 706 |
return float(value) |
| 707 |
except (TypeError, ValueError): |
| 708 |
raise ValidationError("{0} {1} is not a valid float".format(self.column_name, value)) |
| 709 |
|
| 710 |
def to_python(self, value): |
| 711 |
return self.validate(value) |
| 712 |
|
| 713 |
def to_database(self, value): |
| 714 |
return self.validate(value) |
| 715 |
|
| 716 |
|
| 717 |
class Float(BaseFloat): |
| 718 |
""" |
| 719 |
Stores a single-precision floating-point value |
| 720 |
""" |
| 721 |
db_type = 'float' |
| 722 |
|
| 723 |
|
| 724 |
class Double(BaseFloat): |
| 725 |
""" |
| 726 |
Stores a double-precision floating-point value |
| 727 |
""" |
| 728 |
db_type = 'double' |
| 729 |
|
| 730 |
|
| 731 |
class Decimal(Column): |
| 732 |
""" |
| 733 |
Stores a variable precision decimal value |
| 734 |
""" |
| 735 |
db_type = 'decimal' |
| 736 |
|
| 737 |
def validate(self, value): |
| 738 |
from decimal import Decimal as _Decimal |
| 739 |
from decimal import InvalidOperation |
| 740 |
val = super(Decimal, self).validate(value) |
| 741 |
if val is None: |
| 742 |
return |
| 743 |
try: |
| 744 |
return _Decimal(repr(val)) if isinstance(val, float) else _Decimal(val) |
| 745 |
except InvalidOperation: |
| 746 |
raise ValidationError("{0} '{1}' can't be coerced to decimal".format(self.column_name, val)) |
| 747 |
|
| 748 |
def to_python(self, value): |
| 749 |
return self.validate(value) |
| 750 |
|
| 751 |
def to_database(self, value): |
| 752 |
return self.validate(value) |
| 753 |
|
| 754 |
|
| 755 |
class BaseCollectionColumn(Column): |
| 756 |
""" |
| 757 |
Base Container type for collection-like columns. |
| 758 |
|
| 759 |
http://cassandra.apache.org/doc/cql3/CQL-3.0.html#collections |
| 760 |
""" |
| 761 |
def __init__(self, types, **kwargs): |
| 762 |
""" |
| 763 |
:param types: a sequence of sub types in this collection |
| 764 |
""" |
| 765 |
instances = [] |
| 766 |
for t in types: |
| 767 |
inheritance_comparator = issubclass if isinstance(t, type) else isinstance |
| 768 |
if not inheritance_comparator(t, Column): |
| 769 |
raise ValidationError("%s is not a column class" % (t,)) |
| 770 |
if t.db_type is None: |
| 771 |
raise ValidationError("%s is an abstract type" % (t,)) |
| 772 |
inst = t() if isinstance(t, type) else t |
| 773 |
if isinstance(t, BaseCollectionColumn): |
| 774 |
inst._freeze_db_type() |
| 775 |
instances.append(inst) |
| 776 |
|
| 777 |
self.types = instances |
| 778 |
super(BaseCollectionColumn, self).__init__(**kwargs) |
| 779 |
|
| 780 |
def validate(self, value): |
| 781 |
value = super(BaseCollectionColumn, self).validate(value) |
| 782 |
# It is dangerous to let collections have more than 65535. |
| 783 |
# See: https://issues.apache.org/jira/browse/CASSANDRA-5428 |
| 784 |
if value is not None and len(value) > 65535: |
| 785 |
raise ValidationError("{0} Collection can't have more than 65535 elements.".format(self.column_name)) |
| 786 |
return value |
| 787 |
|
| 788 |
def _val_is_null(self, val): |
| 789 |
return not val |
| 790 |
|
| 791 |
def _freeze_db_type(self): |
| 792 |
if not self.db_type.startswith('frozen'): |
| 793 |
self.db_type = "frozen<%s>" % (self.db_type,) |
| 794 |
|
| 795 |
@property |
| 796 |
def sub_types(self): |
| 797 |
return self.types |
| 798 |
|
| 799 |
@property |
| 800 |
def cql_type(self): |
| 801 |
return _cqltypes[self.__class__.__name__.lower()].apply_parameters([c.cql_type for c in self.types]) |
| 802 |
|
| 803 |
|
| 804 |
class Tuple(BaseCollectionColumn): |
| 805 |
""" |
| 806 |
Stores a fixed-length set of positional values |
| 807 |
|
| 808 |
http://docs.datastax.com/en/cql/3.1/cql/cql_reference/tupleType.html |
| 809 |
""" |
| 810 |
def __init__(self, *args, **kwargs): |
| 811 |
""" |
| 812 |
:param args: column types representing tuple composition |
| 813 |
""" |
| 814 |
if not args: |
| 815 |
raise ValueError("Tuple must specify at least one inner type") |
| 816 |
super(Tuple, self).__init__(args, **kwargs) |
| 817 |
self.db_type = 'tuple<{0}>'.format(', '.join(typ.db_type for typ in self.types)) |
| 818 |
|
| 819 |
def validate(self, value): |
| 820 |
val = super(Tuple, self).validate(value) |
| 821 |
if val is None: |
| 822 |
return |
| 823 |
if len(val) > len(self.types): |
| 824 |
raise ValidationError("Value %r has more fields than tuple definition (%s)" % |
| 825 |
(val, ', '.join(t for t in self.types))) |
| 826 |
return tuple(t.validate(v) for t, v in zip(self.types, val)) |
| 827 |
|
| 828 |
def to_python(self, value): |
| 829 |
if value is None: |
| 830 |
return tuple() |
| 831 |
return tuple(t.to_python(v) for t, v in zip(self.types, value)) |
| 832 |
|
| 833 |
def to_database(self, value): |
| 834 |
if value is None: |
| 835 |
return |
| 836 |
return tuple(t.to_database(v) for t, v in zip(self.types, value)) |
| 837 |
|
| 838 |
|
| 839 |
class BaseContainerColumn(BaseCollectionColumn): |
| 840 |
pass |
| 841 |
|
| 842 |
|
| 843 |
class Set(BaseContainerColumn): |
| 844 |
""" |
| 845 |
Stores a set of unordered, unique values |
| 846 |
|
| 847 |
http://www.datastax.com/documentation/cql/3.1/cql/cql_using/use_set_t.html |
| 848 |
""" |
| 849 |
|
| 850 |
_python_type_hashable = False |
| 851 |
|
| 852 |
def __init__(self, value_type, strict=True, default=set, **kwargs): |
| 853 |
""" |
| 854 |
:param value_type: a column class indicating the types of the value |
| 855 |
:param strict: sets whether non set values will be coerced to set |
| 856 |
type on validation, or raise a validation error, defaults to True |
| 857 |
""" |
| 858 |
self.strict = strict |
| 859 |
super(Set, self).__init__((value_type,), default=default, **kwargs) |
| 860 |
self.value_col = self.types[0] |
| 861 |
if not self.value_col._python_type_hashable: |
| 862 |
raise ValidationError("Cannot create a Set with unhashable value type (see PYTHON-494)") |
| 863 |
self.db_type = 'set<{0}>'.format(self.value_col.db_type) |
| 864 |
|
| 865 |
def validate(self, value): |
| 866 |
val = super(Set, self).validate(value) |
| 867 |
if val is None: |
| 868 |
return |
| 869 |
types = (set, util.SortedSet) if self.strict else (set, util.SortedSet, list, tuple) |
| 870 |
if not isinstance(val, types): |
| 871 |
if self.strict: |
| 872 |
raise ValidationError('{0} {1} is not a set object'.format(self.column_name, val)) |
| 873 |
else: |
| 874 |
raise ValidationError('{0} {1} cannot be coerced to a set object'.format(self.column_name, val)) |
| 875 |
|
| 876 |
if None in val: |
| 877 |
raise ValidationError("{0} None not allowed in a set".format(self.column_name)) |
| 878 |
# TODO: stop doing this conversion because it doesn't support non-hashable collections as keys (cassandra does) |
| 879 |
# will need to start using the cassandra.util types in the next major rev (PYTHON-494) |
| 880 |
return set(self.value_col.validate(v) for v in val) |
| 881 |
|
| 882 |
def to_python(self, value): |
| 883 |
if value is None: |
| 884 |
return set() |
| 885 |
return set(self.value_col.to_python(v) for v in value) |
| 886 |
|
| 887 |
def to_database(self, value): |
| 888 |
if value is None: |
| 889 |
return None |
| 890 |
return set(self.value_col.to_database(v) for v in value) |
| 891 |
|
| 892 |
|
| 893 |
class List(BaseContainerColumn): |
| 894 |
""" |
| 895 |
Stores a list of ordered values |
| 896 |
|
| 897 |
http://www.datastax.com/documentation/cql/3.1/cql/cql_using/use_list_t.html |
| 898 |
""" |
| 899 |
|
| 900 |
_python_type_hashable = False |
| 901 |
|
| 902 |
def __init__(self, value_type, default=list, **kwargs): |
| 903 |
""" |
| 904 |
:param value_type: a column class indicating the types of the value |
| 905 |
""" |
| 906 |
super(List, self).__init__((value_type,), default=default, **kwargs) |
| 907 |
self.value_col = self.types[0] |
| 908 |
self.db_type = 'list<{0}>'.format(self.value_col.db_type) |
| 909 |
|
| 910 |
def validate(self, value): |
| 911 |
val = super(List, self).validate(value) |
| 912 |
if val is None: |
| 913 |
return |
| 914 |
if not isinstance(val, (set, list, tuple)): |
| 915 |
raise ValidationError('{0} {1} is not a list object'.format(self.column_name, val)) |
| 916 |
if None in val: |
| 917 |
raise ValidationError("{0} None is not allowed in a list".format(self.column_name)) |
| 918 |
return [self.value_col.validate(v) for v in val] |
| 919 |
|
| 920 |
def to_python(self, value): |
| 921 |
if value is None: |
| 922 |
return [] |
| 923 |
return [self.value_col.to_python(v) for v in value] |
| 924 |
|
| 925 |
def to_database(self, value): |
| 926 |
if value is None: |
| 927 |
return None |
| 928 |
return [self.value_col.to_database(v) for v in value] |
| 929 |
|
| 930 |
|
| 931 |
class Map(BaseContainerColumn): |
| 932 |
""" |
| 933 |
Stores a key -> value map (dictionary) |
| 934 |
|
| 935 |
https://docs.datastax.com/en/dse/6.7/cql/cql/cql_using/useMap.html |
| 936 |
""" |
| 937 |
|
| 938 |
_python_type_hashable = False |
| 939 |
|
| 940 |
def __init__(self, key_type, value_type, default=dict, **kwargs): |
| 941 |
""" |
| 942 |
:param key_type: a column class indicating the types of the key |
| 943 |
:param value_type: a column class indicating the types of the value |
| 944 |
""" |
| 945 |
super(Map, self).__init__((key_type, value_type), default=default, **kwargs) |
| 946 |
self.key_col = self.types[0] |
| 947 |
self.value_col = self.types[1] |
| 948 |
|
| 949 |
if not self.key_col._python_type_hashable: |
| 950 |
raise ValidationError("Cannot create a Map with unhashable key type (see PYTHON-494)") |
| 951 |
|
| 952 |
self.db_type = 'map<{0}, {1}>'.format(self.key_col.db_type, self.value_col.db_type) |
| 953 |
|
| 954 |
def validate(self, value): |
| 955 |
val = super(Map, self).validate(value) |
| 956 |
if val is None: |
| 957 |
return |
| 958 |
if not isinstance(val, (dict, util.OrderedMap)): |
| 959 |
raise ValidationError('{0} {1} is not a dict object'.format(self.column_name, val)) |
| 960 |
if None in val: |
| 961 |
raise ValidationError("{0} None is not allowed in a map".format(self.column_name)) |
| 962 |
# TODO: stop doing this conversion because it doesn't support non-hashable collections as keys (cassandra does) |
| 963 |
# will need to start using the cassandra.util types in the next major rev (PYTHON-494) |
| 964 |
return dict((self.key_col.validate(k), self.value_col.validate(v)) for k, v in val.items()) |
| 965 |
|
| 966 |
def to_python(self, value): |
| 967 |
if value is None: |
| 968 |
return {} |
| 969 |
if value is not None: |
| 970 |
return dict((self.key_col.to_python(k), self.value_col.to_python(v)) for k, v in value.items()) |
| 971 |
|
| 972 |
def to_database(self, value): |
| 973 |
if value is None: |
| 974 |
return None |
| 975 |
return dict((self.key_col.to_database(k), self.value_col.to_database(v)) for k, v in value.items()) |
| 976 |
|
| 977 |
|
| 978 |
class UDTValueManager(BaseValueManager): |
| 979 |
@property |
| 980 |
def changed(self): |
| 981 |
if self.explicit: |
| 982 |
return self.value != self.previous_value |
| 983 |
|
| 984 |
default_value = self.column.get_default() |
| 985 |
if not self.column._val_is_null(default_value): |
| 986 |
return self.value != default_value |
| 987 |
elif self.previous_value is None: |
| 988 |
return not self.column._val_is_null(self.value) and self.value.has_changed_fields() |
| 989 |
|
| 990 |
return False |
| 991 |
|
| 992 |
def reset_previous_value(self): |
| 993 |
if self.value is not None: |
| 994 |
self.value.reset_changed_fields() |
| 995 |
self.previous_value = copy(self.value) |
| 996 |
|
| 997 |
|
| 998 |
class UserDefinedType(Column): |
| 999 |
""" |
| 1000 |
User Defined Type column |
| 1001 |
|
| 1002 |
http://www.datastax.com/documentation/cql/3.1/cql/cql_using/cqlUseUDT.html |
| 1003 |
|
| 1004 |
These columns are represented by a specialization of :class:`cassandra.cqlengine.usertype.UserType`. |
| 1005 |
|
| 1006 |
Please see :ref:`user_types` for examples and discussion. |
| 1007 |
""" |
| 1008 |
|
| 1009 |
value_manager = UDTValueManager |
| 1010 |
|
| 1011 |
def __init__(self, user_type, **kwargs): |
| 1012 |
""" |
| 1013 |
:param type user_type: specifies the :class:`~.cqlengine.usertype.UserType` model of the column |
| 1014 |
""" |
| 1015 |
self.user_type = user_type |
| 1016 |
self.db_type = "frozen<%s>" % user_type.type_name() |
| 1017 |
super(UserDefinedType, self).__init__(**kwargs) |
| 1018 |
|
| 1019 |
@property |
| 1020 |
def sub_types(self): |
| 1021 |
return list(self.user_type._fields.values()) |
| 1022 |
|
| 1023 |
@property |
| 1024 |
def cql_type(self): |
| 1025 |
return UserType.make_udt_class(keyspace='', udt_name=self.user_type.type_name(), |
| 1026 |
field_names=[c.db_field_name for c in self.user_type._fields.values()], |
| 1027 |
field_types=[c.cql_type for c in self.user_type._fields.values()]) |
| 1028 |
|
| 1029 |
def validate(self, value): |
| 1030 |
val = super(UserDefinedType, self).validate(value) |
| 1031 |
if val is None: |
| 1032 |
return |
| 1033 |
val.validate() |
| 1034 |
return val |
| 1035 |
|
| 1036 |
def to_python(self, value): |
| 1037 |
if value is None: |
| 1038 |
return |
| 1039 |
|
| 1040 |
copied_value = deepcopy(value) |
| 1041 |
for name, field in self.user_type._fields.items(): |
| 1042 |
if copied_value[name] is not None or isinstance(field, BaseContainerColumn): |
| 1043 |
copied_value[name] = field.to_python(copied_value[name]) |
| 1044 |
|
| 1045 |
return copied_value |
| 1046 |
|
| 1047 |
def to_database(self, value): |
| 1048 |
if value is None: |
| 1049 |
return |
| 1050 |
|
| 1051 |
copied_value = deepcopy(value) |
| 1052 |
for name, field in self.user_type._fields.items(): |
| 1053 |
if copied_value[name] is not None or isinstance(field, BaseContainerColumn): |
| 1054 |
copied_value[name] = field.to_database(copied_value[name]) |
| 1055 |
|
| 1056 |
return copied_value |
| 1057 |
|
| 1058 |
|
| 1059 |
def resolve_udts(col_def, out_list): |
| 1060 |
for col in col_def.sub_types: |
| 1061 |
resolve_udts(col, out_list) |
| 1062 |
if isinstance(col_def, UserDefinedType): |
| 1063 |
out_list.append(col_def.user_type) |
| 1064 |
|
| 1065 |
|
| 1066 |
class _PartitionKeysToken(Column): |
| 1067 |
""" |
| 1068 |
virtual column representing token of partition columns. |
| 1069 |
Used by filter(pk__token=Token(...)) filters |
| 1070 |
""" |
| 1071 |
|
| 1072 |
def __init__(self, model): |
| 1073 |
self.partition_columns = list(model._partition_keys.values()) |
| 1074 |
super(_PartitionKeysToken, self).__init__(partition_key=True) |
| 1075 |
|
| 1076 |
@property |
| 1077 |
def db_field_name(self): |
| 1078 |
return 'token({0})'.format(', '.join(['"{0}"'.format(c.db_field_name) for c in self.partition_columns])) |