| 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 |
import re |
| 16 |
|
| 17 |
from cassandra.util import OrderedDict |
| 18 |
from cassandra.cqlengine import CQLEngineException |
| 19 |
from cassandra.cqlengine import columns |
| 20 |
from cassandra.cqlengine import connection as conn |
| 21 |
from cassandra.cqlengine import models |
| 22 |
|
| 23 |
|
| 24 |
class UserTypeException(CQLEngineException): |
| 25 |
pass |
| 26 |
|
| 27 |
|
| 28 |
class UserTypeDefinitionException(UserTypeException): |
| 29 |
pass |
| 30 |
|
| 31 |
|
| 32 |
class BaseUserType(object): |
| 33 |
""" |
| 34 |
The base type class; don't inherit from this, inherit from UserType, defined below |
| 35 |
""" |
| 36 |
__type_name__ = None |
| 37 |
|
| 38 |
_fields = None |
| 39 |
_db_map = None |
| 40 |
|
| 41 |
def __init__(self, **values): |
| 42 |
self._values = {} |
| 43 |
if self._db_map: |
| 44 |
values = dict((self._db_map.get(k, k), v) for k, v in values.items()) |
| 45 |
|
| 46 |
for name, field in self._fields.items(): |
| 47 |
field_default = field.get_default() if field.has_default else None |
| 48 |
value = values.get(name, field_default) |
| 49 |
if value is not None or isinstance(field, columns.BaseContainerColumn): |
| 50 |
value = field.to_python(value) |
| 51 |
value_mngr = field.value_manager(self, field, value) |
| 52 |
value_mngr.explicit = name in values |
| 53 |
self._values[name] = value_mngr |
| 54 |
|
| 55 |
def __eq__(self, other): |
| 56 |
if self.__class__ != other.__class__: |
| 57 |
return False |
| 58 |
|
| 59 |
keys = set(self._fields.keys()) |
| 60 |
other_keys = set(other._fields.keys()) |
| 61 |
if keys != other_keys: |
| 62 |
return False |
| 63 |
|
| 64 |
for key in other_keys: |
| 65 |
if getattr(self, key, None) != getattr(other, key, None): |
| 66 |
return False |
| 67 |
|
| 68 |
return True |
| 69 |
|
| 70 |
def __ne__(self, other): |
| 71 |
return not self.__eq__(other) |
| 72 |
|
| 73 |
def __str__(self): |
| 74 |
return "{{{0}}}".format(', '.join("'{0}': {1}".format(k, getattr(self, k)) for k, v in self._values.items())) |
| 75 |
|
| 76 |
def has_changed_fields(self): |
| 77 |
return any(v.changed for v in self._values.values()) |
| 78 |
|
| 79 |
def reset_changed_fields(self): |
| 80 |
for v in self._values.values(): |
| 81 |
v.reset_previous_value() |
| 82 |
|
| 83 |
def __iter__(self): |
| 84 |
for field in self._fields.keys(): |
| 85 |
yield field |
| 86 |
|
| 87 |
def __getattr__(self, attr): |
| 88 |
# provides the mapping from db_field to fields |
| 89 |
try: |
| 90 |
return getattr(self, self._db_map[attr]) |
| 91 |
except KeyError: |
| 92 |
raise AttributeError(attr) |
| 93 |
|
| 94 |
def __getitem__(self, key): |
| 95 |
if not isinstance(key, str): |
| 96 |
raise TypeError |
| 97 |
if key not in self._fields.keys(): |
| 98 |
raise KeyError |
| 99 |
return getattr(self, key) |
| 100 |
|
| 101 |
def __setitem__(self, key, val): |
| 102 |
if not isinstance(key, str): |
| 103 |
raise TypeError |
| 104 |
if key not in self._fields.keys(): |
| 105 |
raise KeyError |
| 106 |
return setattr(self, key, val) |
| 107 |
|
| 108 |
def __len__(self): |
| 109 |
try: |
| 110 |
return self._len |
| 111 |
except: |
| 112 |
self._len = len(self._fields.keys()) |
| 113 |
return self._len |
| 114 |
|
| 115 |
def keys(self): |
| 116 |
""" Returns a list of column IDs. """ |
| 117 |
return [k for k in self] |
| 118 |
|
| 119 |
def values(self): |
| 120 |
""" Returns list of column values. """ |
| 121 |
return [self[k] for k in self] |
| 122 |
|
| 123 |
def items(self): |
| 124 |
""" Returns a list of column ID/value tuples. """ |
| 125 |
return [(k, self[k]) for k in self] |
| 126 |
|
| 127 |
@classmethod |
| 128 |
def register_for_keyspace(cls, keyspace, connection=None): |
| 129 |
conn.register_udt(keyspace, cls.type_name(), cls, connection=connection) |
| 130 |
|
| 131 |
@classmethod |
| 132 |
def type_name(cls): |
| 133 |
""" |
| 134 |
Returns the type name if it's been defined |
| 135 |
otherwise, it creates it from the class name |
| 136 |
""" |
| 137 |
if cls.__type_name__: |
| 138 |
type_name = cls.__type_name__.lower() |
| 139 |
else: |
| 140 |
camelcase = re.compile(r'([a-z])([A-Z])') |
| 141 |
ccase = lambda s: camelcase.sub(lambda v: '{0}_{1}'.format(v.group(1), v.group(2)), s) |
| 142 |
|
| 143 |
type_name = ccase(cls.__name__) |
| 144 |
# trim to less than 48 characters or cassandra will complain |
| 145 |
type_name = type_name[-48:] |
| 146 |
type_name = type_name.lower() |
| 147 |
type_name = re.sub(r'^_+', '', type_name) |
| 148 |
cls.__type_name__ = type_name |
| 149 |
|
| 150 |
return type_name |
| 151 |
|
| 152 |
def validate(self): |
| 153 |
""" |
| 154 |
Cleans and validates the field values |
| 155 |
""" |
| 156 |
for name, field in self._fields.items(): |
| 157 |
v = getattr(self, name) |
| 158 |
if v is None and not self._values[name].explicit and field.has_default: |
| 159 |
v = field.get_default() |
| 160 |
val = field.validate(v) |
| 161 |
setattr(self, name, val) |
| 162 |
|
| 163 |
|
| 164 |
class UserTypeMetaClass(type): |
| 165 |
|
| 166 |
def __new__(cls, name, bases, attrs): |
| 167 |
field_dict = OrderedDict() |
| 168 |
|
| 169 |
field_defs = [(k, v) for k, v in attrs.items() if isinstance(v, columns.Column)] |
| 170 |
field_defs = sorted(field_defs, key=lambda x: x[1].position) |
| 171 |
|
| 172 |
def _transform_column(field_name, field_obj): |
| 173 |
field_dict[field_name] = field_obj |
| 174 |
field_obj.set_column_name(field_name) |
| 175 |
attrs[field_name] = models.ColumnDescriptor(field_obj) |
| 176 |
|
| 177 |
# transform field definitions |
| 178 |
for k, v in field_defs: |
| 179 |
# don't allow a field with the same name as a built-in attribute or method |
| 180 |
if k in BaseUserType.__dict__: |
| 181 |
raise UserTypeDefinitionException("field '{0}' conflicts with built-in attribute/method".format(k)) |
| 182 |
_transform_column(k, v) |
| 183 |
|
| 184 |
attrs['_fields'] = field_dict |
| 185 |
|
| 186 |
db_map = {} |
| 187 |
for field_name, field in field_dict.items(): |
| 188 |
db_field = field.db_field_name |
| 189 |
if db_field != field_name: |
| 190 |
if db_field in field_dict: |
| 191 |
raise UserTypeDefinitionException("db_field '{0}' for field '{1}' conflicts with another attribute name".format(db_field, field_name)) |
| 192 |
db_map[db_field] = field_name |
| 193 |
attrs['_db_map'] = db_map |
| 194 |
|
| 195 |
klass = super(UserTypeMetaClass, cls).__new__(cls, name, bases, attrs) |
| 196 |
|
| 197 |
return klass |
| 198 |
|
| 199 |
|
| 200 |
class UserType(BaseUserType, metaclass=UserTypeMetaClass): |
| 201 |
""" |
| 202 |
This class is used to model User Defined Types. To define a type, declare a class inheriting from this, |
| 203 |
and assign field types as class attributes: |
| 204 |
|
| 205 |
.. code-block:: python |
| 206 |
|
| 207 |
# connect with default keyspace ... |
| 208 |
|
| 209 |
from cassandra.cqlengine.columns import Text, Integer |
| 210 |
from cassandra.cqlengine.usertype import UserType |
| 211 |
|
| 212 |
class address(UserType): |
| 213 |
street = Text() |
| 214 |
zipcode = Integer() |
| 215 |
|
| 216 |
from cassandra.cqlengine import management |
| 217 |
management.sync_type(address) |
| 218 |
|
| 219 |
Please see :ref:`user_types` for a complete example and discussion. |
| 220 |
""" |
| 221 |
|
| 222 |
__type_name__ = None |
| 223 |
""" |
| 224 |
*Optional.* Sets the name of the CQL type for this type. |
| 225 |
|
| 226 |
If not specified, the type name will be the name of the class, with it's module name as it's prefix. |
| 227 |
""" |