Debian Codegraph @

cassandra/cqlengine/management.py

raw
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 collections import namedtuple
16 import json
17 import logging
18 import os
19 import warnings
20 from itertools import product
21
22 from cassandra import metadata
23 from cassandra.cqlengine import CQLEngineException
24 from cassandra.cqlengine import columns, query
25 from cassandra.cqlengine.connection import execute, get_cluster, format_log_context
26 from cassandra.cqlengine.models import Model
27 from cassandra.cqlengine.named import NamedTable
28 from cassandra.cqlengine.usertype import UserType
29
30 CQLENG_ALLOW_SCHEMA_MANAGEMENT = 'CQLENG_ALLOW_SCHEMA_MANAGEMENT'
31
32 Field = namedtuple('Field', ['name', 'type'])
33
34 log = logging.getLogger(__name__)
35
36 # system keyspaces
37 schema_columnfamilies = NamedTable('system', 'schema_columnfamilies')
38
39
40 def _get_context(keyspaces, connections):
41 """Return all the execution contexts"""
42
43 if keyspaces:
44 if not isinstance(keyspaces, (list, tuple)):
45 raise ValueError('keyspaces must be a list or a tuple.')
46
47 if connections:
48 if not isinstance(connections, (list, tuple)):
49 raise ValueError('connections must be a list or a tuple.')
50
51 keyspaces = keyspaces if keyspaces else [None]
52 connections = connections if connections else [None]
53
54 return product(connections, keyspaces)
55
56
57 def create_keyspace_simple(name, replication_factor, durable_writes=True, connections=None):
58 """
59 Creates a keyspace with SimpleStrategy for replica placement
60
61 If the keyspace already exists, it will not be modified.
62
63 **This function should be used with caution, especially in production environments.
64 Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
65
66 *There are plans to guard schema-modifying functions with an environment-driven conditional.*
67
68 :param str name: name of keyspace to create
69 :param int replication_factor: keyspace replication factor, used with :attr:`~.SimpleStrategy`
70 :param bool durable_writes: Write log is bypassed if set to False
71 :param list connections: List of connection names
72 """
73 _create_keyspace(name, durable_writes, 'SimpleStrategy',
74 {'replication_factor': replication_factor}, connections=connections)
75
76
77 def create_keyspace_network_topology(name, dc_replication_map, durable_writes=True, connections=None):
78 """
79 Creates a keyspace with NetworkTopologyStrategy for replica placement
80
81 If the keyspace already exists, it will not be modified.
82
83 **This function should be used with caution, especially in production environments.
84 Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
85
86 *There are plans to guard schema-modifying functions with an environment-driven conditional.*
87
88 :param str name: name of keyspace to create
89 :param dict dc_replication_map: map of dc_names: replication_factor
90 :param bool durable_writes: Write log is bypassed if set to False
91 :param list connections: List of connection names
92 """
93 _create_keyspace(name, durable_writes, 'NetworkTopologyStrategy', dc_replication_map, connections=connections)
94
95
96 def _create_keyspace(name, durable_writes, strategy_class, strategy_options, connections=None):
97 if not _allow_schema_modification():
98 return
99
100 if connections:
101 if not isinstance(connections, (list, tuple)):
102 raise ValueError('Connections must be a list or a tuple.')
103
104 def __create_keyspace(name, durable_writes, strategy_class, strategy_options, connection=None):
105 cluster = get_cluster(connection)
106
107 if name not in cluster.metadata.keyspaces:
108 log.info(format_log_context("Creating keyspace %s", connection=connection), name)
109 ks_meta = metadata.KeyspaceMetadata(name, durable_writes, strategy_class, strategy_options)
110 execute(ks_meta.as_cql_query(), connection=connection)
111 else:
112 log.info(format_log_context("Not creating keyspace %s because it already exists", connection=connection), name)
113
114 if connections:
115 for connection in connections:
116 __create_keyspace(name, durable_writes, strategy_class, strategy_options, connection=connection)
117 else:
118 __create_keyspace(name, durable_writes, strategy_class, strategy_options)
119
120
121 def drop_keyspace(name, connections=None):
122 """
123 Drops a keyspace, if it exists.
124
125 *There are plans to guard schema-modifying functions with an environment-driven conditional.*
126
127 **This function should be used with caution, especially in production environments.
128 Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
129
130 :param str name: name of keyspace to drop
131 :param list connections: List of connection names
132 """
133 if not _allow_schema_modification():
134 return
135
136 if connections:
137 if not isinstance(connections, (list, tuple)):
138 raise ValueError('Connections must be a list or a tuple.')
139
140 def _drop_keyspace(name, connection=None):
141 cluster = get_cluster(connection)
142 if name in cluster.metadata.keyspaces:
143 execute("DROP KEYSPACE {0}".format(metadata.protect_name(name)), connection=connection)
144
145 if connections:
146 for connection in connections:
147 _drop_keyspace(name, connection)
148 else:
149 _drop_keyspace(name)
150
151 def _get_index_name_by_column(table, column_name):
152 """
153 Find the index name for a given table and column.
154 """
155 protected_name = metadata.protect_name(column_name)
156 possible_index_values = [protected_name, "values(%s)" % protected_name]
157 for index_metadata in table.indexes.values():
158 options = dict(index_metadata.index_options)
159 if options.get('target') in possible_index_values:
160 return index_metadata.name
161
162
163 def sync_table(model, keyspaces=None, connections=None):
164 """
165 Inspects the model and creates / updates the corresponding table and columns.
166
167 If `keyspaces` is specified, the table will be synched for all specified keyspaces.
168 Note that the `Model.__keyspace__` is ignored in that case.
169
170 If `connections` is specified, the table will be synched for all specified connections. Note that the `Model.__connection__` is ignored in that case.
171 If not specified, it will try to get the connection from the Model.
172
173 Any User Defined Types used in the table are implicitly synchronized.
174
175 This function can only add fields that are not part of the primary key.
176
177 Note that the attributes removed from the model are not deleted on the database.
178 They become effectively ignored by (will not show up on) the model.
179
180 **This function should be used with caution, especially in production environments.
181 Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
182
183 *There are plans to guard schema-modifying functions with an environment-driven conditional.*
184 """
185
186 context = _get_context(keyspaces, connections)
187 for connection, keyspace in context:
188 with query.ContextQuery(model, keyspace=keyspace) as m:
189 _sync_table(m, connection=connection)
190
191
192 def _sync_table(model, connection=None):
193 if not _allow_schema_modification():
194 return
195
196 if not issubclass(model, Model):
197 raise CQLEngineException("Models must be derived from base Model.")
198
199 if model.__abstract__:
200 raise CQLEngineException("cannot create table from abstract model")
201
202 cf_name = model.column_family_name()
203 raw_cf_name = model._raw_column_family_name()
204
205 ks_name = model._get_keyspace()
206 connection = connection or model._get_connection()
207
208 cluster = get_cluster(connection)
209
210 try:
211 keyspace = cluster.metadata.keyspaces[ks_name]
212 except KeyError:
213 msg = format_log_context("Keyspace '{0}' for model {1} does not exist.", connection=connection)
214 raise CQLEngineException(msg.format(ks_name, model))
215
216 tables = keyspace.tables
217
218 syncd_types = set()
219 for col in model._columns.values():
220 udts = []
221 columns.resolve_udts(col, udts)
222 for udt in [u for u in udts if u not in syncd_types]:
223 _sync_type(ks_name, udt, syncd_types, connection=connection)
224
225 if raw_cf_name not in tables:
226 log.debug(format_log_context("sync_table creating new table %s", keyspace=ks_name, connection=connection), cf_name)
227 qs = _get_create_table(model)
228
229 try:
230 execute(qs, connection=connection)
231 except CQLEngineException as ex:
232 # 1.2 doesn't return cf names, so we have to examine the exception
233 # and ignore if it says the column family already exists
234 if "Cannot add already existing column family" not in str(ex):
235 raise
236 else:
237 log.debug(format_log_context("sync_table checking existing table %s", keyspace=ks_name, connection=connection), cf_name)
238 table_meta = tables[raw_cf_name]
239
240 _validate_pk(model, table_meta)
241
242 table_columns = table_meta.columns
243 model_fields = set()
244
245 for model_name, col in model._columns.items():
246 db_name = col.db_field_name
247 model_fields.add(db_name)
248 if db_name in table_columns:
249 col_meta = table_columns[db_name]
250 if col_meta.cql_type != col.db_type:
251 msg = format_log_context('Existing table {0} has column "{1}" with a type ({2}) differing from the model type ({3}).'
252 ' Model should be updated.', keyspace=ks_name, connection=connection)
253 msg = msg.format(cf_name, db_name, col_meta.cql_type, col.db_type)
254 warnings.warn(msg)
255 log.warning(msg)
256
257 continue
258
259 if col.primary_key or col.primary_key:
260 msg = format_log_context("Cannot add primary key '{0}' (with db_field '{1}') to existing table {2}", keyspace=ks_name, connection=connection)
261 raise CQLEngineException(msg.format(model_name, db_name, cf_name))
262
263 query = "ALTER TABLE {0} add {1}".format(cf_name, col.get_column_def())
264 execute(query, connection=connection)
265
266 db_fields_not_in_model = model_fields.symmetric_difference(table_columns)
267 if db_fields_not_in_model:
268 msg = format_log_context("Table {0} has fields not referenced by model: {1}", keyspace=ks_name, connection=connection)
269 log.info(msg.format(cf_name, db_fields_not_in_model))
270
271 _update_options(model, connection=connection)
272
273 table = cluster.metadata.keyspaces[ks_name].tables[raw_cf_name]
274
275 indexes = [c for n, c in model._columns.items() if c.index]
276
277 # TODO: support multiple indexes in C* 3.0+
278 for column in indexes:
279 index_name = _get_index_name_by_column(table, column.db_field_name)
280 if index_name:
281 continue
282
283 qs = ['CREATE INDEX']
284 qs += ['ON {0}'.format(cf_name)]
285 qs += ['("{0}")'.format(column.db_field_name)]
286 qs = ' '.join(qs)
287 execute(qs, connection=connection)
288
289
290 def _validate_pk(model, table_meta):
291 model_partition = [c.db_field_name for c in model._partition_keys.values()]
292 meta_partition = [c.name for c in table_meta.partition_key]
293 model_clustering = [c.db_field_name for c in model._clustering_keys.values()]
294 meta_clustering = [c.name for c in table_meta.clustering_key]
295
296 if model_partition != meta_partition or model_clustering != meta_clustering:
297 def _pk_string(partition, clustering):
298 return "PRIMARY KEY (({0}){1})".format(', '.join(partition), ', ' + ', '.join(clustering) if clustering else '')
299 raise CQLEngineException("Model {0} PRIMARY KEY composition does not match existing table {1}. "
300 "Model: {2}; Table: {3}. "
301 "Update model or drop the table.".format(model, model.column_family_name(),
302 _pk_string(model_partition, model_clustering),
303 _pk_string(meta_partition, meta_clustering)))
304
305
306 def sync_type(ks_name, type_model, connection=None):
307 """
308 Inspects the type_model and creates / updates the corresponding type.
309
310 Note that the attributes removed from the type_model are not deleted on the database (this operation is not supported).
311 They become effectively ignored by (will not show up on) the type_model.
312
313 **This function should be used with caution, especially in production environments.
314 Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
315
316 *There are plans to guard schema-modifying functions with an environment-driven conditional.*
317 """
318 if not _allow_schema_modification():
319 return
320
321 if not issubclass(type_model, UserType):
322 raise CQLEngineException("Types must be derived from base UserType.")
323
324 _sync_type(ks_name, type_model, connection=connection)
325
326
327 def _sync_type(ks_name, type_model, omit_subtypes=None, connection=None):
328
329 syncd_sub_types = omit_subtypes or set()
330 for field in type_model._fields.values():
331 udts = []
332 columns.resolve_udts(field, udts)
333 for udt in [u for u in udts if u not in syncd_sub_types]:
334 _sync_type(ks_name, udt, syncd_sub_types, connection=connection)
335 syncd_sub_types.add(udt)
336
337 type_name = type_model.type_name()
338 type_name_qualified = "%s.%s" % (ks_name, type_name)
339
340 cluster = get_cluster(connection)
341
342 keyspace = cluster.metadata.keyspaces[ks_name]
343 defined_types = keyspace.user_types
344
345 if type_name not in defined_types:
346 log.debug(format_log_context("sync_type creating new type %s", keyspace=ks_name, connection=connection), type_name_qualified)
347 cql = get_create_type(type_model, ks_name)
348 execute(cql, connection=connection)
349 cluster.refresh_user_type_metadata(ks_name, type_name)
350 type_model.register_for_keyspace(ks_name, connection=connection)
351 else:
352 type_meta = defined_types[type_name]
353 defined_fields = type_meta.field_names
354 model_fields = set()
355 for field in type_model._fields.values():
356 model_fields.add(field.db_field_name)
357 if field.db_field_name not in defined_fields:
358 execute("ALTER TYPE {0} ADD {1}".format(type_name_qualified, field.get_column_def()), connection=connection)
359 else:
360 field_type = type_meta.field_types[defined_fields.index(field.db_field_name)]
361 if field_type != field.db_type:
362 msg = format_log_context('Existing user type {0} has field "{1}" with a type ({2}) differing from the model user type ({3}).'
363 ' UserType should be updated.', keyspace=ks_name, connection=connection)
364 msg = msg.format(type_name_qualified, field.db_field_name, field_type, field.db_type)
365 warnings.warn(msg)
366 log.warning(msg)
367
368 type_model.register_for_keyspace(ks_name, connection=connection)
369
370 if len(defined_fields) == len(model_fields):
371 log.info(format_log_context("Type %s did not require synchronization", keyspace=ks_name, connection=connection), type_name_qualified)
372 return
373
374 db_fields_not_in_model = model_fields.symmetric_difference(defined_fields)
375 if db_fields_not_in_model:
376 msg = format_log_context("Type %s has fields not referenced by model: %s", keyspace=ks_name, connection=connection)
377 log.info(msg, type_name_qualified, db_fields_not_in_model)
378
379
380 def get_create_type(type_model, keyspace):
381 type_meta = metadata.UserType(keyspace,
382 type_model.type_name(),
383 (f.db_field_name for f in type_model._fields.values()),
384 (v.db_type for v in type_model._fields.values()))
385 return type_meta.as_cql_query()
386
387
388 def _get_create_table(model):
389 ks_table_name = model.column_family_name()
390 query_strings = ['CREATE TABLE {0}'.format(ks_table_name)]
391
392 # add column types
393 pkeys = [] # primary keys
394 ckeys = [] # clustering keys
395 qtypes = [] # field types
396
397 def add_column(col):
398 s = col.get_column_def()
399 if col.primary_key:
400 keys = (pkeys if col.partition_key else ckeys)
401 keys.append('"{0}"'.format(col.db_field_name))
402 qtypes.append(s)
403
404 for name, col in model._columns.items():
405 add_column(col)
406
407 qtypes.append('PRIMARY KEY (({0}){1})'.format(', '.join(pkeys), ckeys and ', ' + ', '.join(ckeys) or ''))
408
409 query_strings += ['({0})'.format(', '.join(qtypes))]
410
411 property_strings = []
412
413 _order = ['"{0}" {1}'.format(c.db_field_name, c.clustering_order or 'ASC') for c in model._clustering_keys.values()]
414 if _order:
415 property_strings.append('CLUSTERING ORDER BY ({0})'.format(', '.join(_order)))
416
417 # options strings use the V3 format, which matches CQL more closely and does not require mapping
418 property_strings += metadata.TableMetadataV3._make_option_strings(model.__options__ or {})
419
420 if property_strings:
421 query_strings += ['WITH {0}'.format(' AND '.join(property_strings))]
422
423 return ' '.join(query_strings)
424
425
426 def _get_table_metadata(model, connection=None):
427 # returns the table as provided by the native driver for a given model
428 cluster = get_cluster(connection)
429 ks = model._get_keyspace()
430 table = model._raw_column_family_name()
431 table = cluster.metadata.keyspaces[ks].tables[table]
432 return table
433
434
435 def _options_map_from_strings(option_strings):
436 # converts options strings to a mapping to strings or dict
437 options = {}
438 for option in option_strings:
439 name, value = option.split('=')
440 i = value.find('{')
441 if i >= 0:
442 value = value[i:value.rfind('}') + 1].replace("'", '"') # from cql single quotes to json double; not aware of any values that would be escaped right now
443 value = json.loads(value)
444 else:
445 value = value.strip()
446 options[name.strip()] = value
447 return options
448
449
450 def _update_options(model, connection=None):
451 """Updates the table options for the given model if necessary.
452
453 :param model: The model to update.
454 :param connection: Name of the connection to use
455
456 :return: `True`, if the options were modified in Cassandra,
457 `False` otherwise.
458 :rtype: bool
459 """
460 ks_name = model._get_keyspace()
461 msg = format_log_context("Checking %s for option differences", keyspace=ks_name, connection=connection)
462 log.debug(msg, model)
463 model_options = model.__options__ or {}
464
465 table_meta = _get_table_metadata(model, connection=connection)
466 # go to CQL string first to normalize meta from different versions
467 existing_option_strings = set(table_meta._make_option_strings(table_meta.options))
468 existing_options = _options_map_from_strings(existing_option_strings)
469 model_option_strings = metadata.TableMetadataV3._make_option_strings(model_options)
470 model_options = _options_map_from_strings(model_option_strings)
471
472 update_options = {}
473 for name, value in model_options.items():
474 try:
475 existing_value = existing_options[name]
476 except KeyError:
477 msg = format_log_context("Invalid table option: '%s'; known options: %s", keyspace=ks_name, connection=connection)
478 raise KeyError(msg % (name, existing_options.keys()))
479 if isinstance(existing_value, str):
480 if value != existing_value:
481 update_options[name] = value
482 else:
483 try:
484 for k, v in value.items():
485 if existing_value[k] != v:
486 update_options[name] = value
487 break
488 except KeyError:
489 update_options[name] = value
490
491 if update_options:
492 options = ' AND '.join(metadata.TableMetadataV3._make_option_strings(update_options))
493 query = "ALTER TABLE {0} WITH {1}".format(model.column_family_name(), options)
494 execute(query, connection=connection)
495 return True
496
497 return False
498
499
500 def drop_table(model, keyspaces=None, connections=None):
501 """
502 Drops the table indicated by the model, if it exists.
503
504 If `keyspaces` is specified, the table will be dropped for all specified keyspaces. Note that the `Model.__keyspace__` is ignored in that case.
505
506 If `connections` is specified, the table will be synched for all specified connections. Note that the `Model.__connection__` is ignored in that case.
507 If not specified, it will try to get the connection from the Model.
508
509
510 **This function should be used with caution, especially in production environments.
511 Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
512
513 *There are plans to guard schema-modifying functions with an environment-driven conditional.*
514 """
515
516 context = _get_context(keyspaces, connections)
517 for connection, keyspace in context:
518 with query.ContextQuery(model, keyspace=keyspace) as m:
519 _drop_table(m, connection=connection)
520
521
522 def _drop_table(model, connection=None):
523 if not _allow_schema_modification():
524 return
525
526 connection = connection or model._get_connection()
527
528 # don't try to delete non existant tables
529 meta = get_cluster(connection).metadata
530
531 ks_name = model._get_keyspace()
532 raw_cf_name = model._raw_column_family_name()
533
534 try:
535 meta.keyspaces[ks_name].tables[raw_cf_name]
536 execute('DROP TABLE {0};'.format(model.column_family_name()), connection=connection)
537 except KeyError:
538 pass
539
540
541 def _allow_schema_modification():
542 if not os.getenv(CQLENG_ALLOW_SCHEMA_MANAGEMENT):
543 msg = CQLENG_ALLOW_SCHEMA_MANAGEMENT + " environment variable is not set. Future versions of this package will require this variable to enable management functions."
544 warnings.warn(msg)
545 log.warning(msg)
546
547 return True