showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 1 | """ |
| 2 | Extensions to Django's model logic. |
| 3 | """ |
| 4 | |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 5 | import re |
Michael Liang | 8864e86 | 2014-07-22 08:36:05 -0700 | [diff] [blame] | 6 | import time |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 7 | import django.core.exceptions |
Jakob Juelich | 7bef841 | 2014-10-14 19:11:54 -0700 | [diff] [blame^] | 8 | from django.db import models as dbmodels, backend, connection, connections |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 9 | from django.db.models.sql import query |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 10 | import django.db.models.sql.where |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 11 | from django.utils import datastructures |
Prashanth B | 489b91d | 2014-03-15 12:17:16 -0700 | [diff] [blame] | 12 | from autotest_lib.frontend.afe import rdb_model_extensions |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 13 | |
Prashanth B | 489b91d | 2014-03-15 12:17:16 -0700 | [diff] [blame] | 14 | |
| 15 | class ValidationError(django.core.exceptions.ValidationError): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 16 | """\ |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 17 | Data validation error in adding or updating an object. The associated |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 18 | value is a dictionary mapping field names to error strings. |
| 19 | """ |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 20 | |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 21 | def _quote_name(name): |
| 22 | """Shorthand for connection.ops.quote_name().""" |
| 23 | return connection.ops.quote_name(name) |
| 24 | |
| 25 | |
beeps | cc9fc70 | 2013-12-02 12:45:38 -0800 | [diff] [blame] | 26 | class LeasedHostManager(dbmodels.Manager): |
| 27 | """Query manager for unleased, unlocked hosts. |
| 28 | """ |
| 29 | def get_query_set(self): |
| 30 | return (super(LeasedHostManager, self).get_query_set().filter( |
| 31 | leased=0, locked=0)) |
| 32 | |
| 33 | |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 34 | class ExtendedManager(dbmodels.Manager): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 35 | """\ |
| 36 | Extended manager supporting subquery filtering. |
| 37 | """ |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 38 | |
showard | f828c77 | 2010-01-25 21:49:42 +0000 | [diff] [blame] | 39 | class CustomQuery(query.Query): |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 40 | def __init__(self, *args, **kwargs): |
showard | f828c77 | 2010-01-25 21:49:42 +0000 | [diff] [blame] | 41 | super(ExtendedManager.CustomQuery, self).__init__(*args, **kwargs) |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 42 | self._custom_joins = [] |
| 43 | |
| 44 | |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 45 | def clone(self, klass=None, **kwargs): |
showard | f828c77 | 2010-01-25 21:49:42 +0000 | [diff] [blame] | 46 | obj = super(ExtendedManager.CustomQuery, self).clone(klass) |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 47 | obj._custom_joins = list(self._custom_joins) |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 48 | return obj |
showard | 08f981b | 2008-06-24 21:59:03 +0000 | [diff] [blame] | 49 | |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 50 | |
| 51 | def combine(self, rhs, connector): |
showard | f828c77 | 2010-01-25 21:49:42 +0000 | [diff] [blame] | 52 | super(ExtendedManager.CustomQuery, self).combine(rhs, connector) |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 53 | if hasattr(rhs, '_custom_joins'): |
| 54 | self._custom_joins.extend(rhs._custom_joins) |
| 55 | |
| 56 | |
| 57 | def add_custom_join(self, table, condition, join_type, |
| 58 | condition_values=(), alias=None): |
| 59 | if alias is None: |
| 60 | alias = table |
| 61 | join_dict = dict(table=table, |
| 62 | condition=condition, |
| 63 | condition_values=condition_values, |
| 64 | join_type=join_type, |
| 65 | alias=alias) |
| 66 | self._custom_joins.append(join_dict) |
| 67 | |
| 68 | |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 69 | @classmethod |
| 70 | def convert_query(self, query_set): |
| 71 | """ |
showard | f828c77 | 2010-01-25 21:49:42 +0000 | [diff] [blame] | 72 | Convert the query set's "query" attribute to a CustomQuery. |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 73 | """ |
| 74 | # Make a copy of the query set |
| 75 | query_set = query_set.all() |
| 76 | query_set.query = query_set.query.clone( |
showard | f828c77 | 2010-01-25 21:49:42 +0000 | [diff] [blame] | 77 | klass=ExtendedManager.CustomQuery, |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 78 | _custom_joins=[]) |
| 79 | return query_set |
showard | 43a3d26 | 2008-11-12 18:17:05 +0000 | [diff] [blame] | 80 | |
| 81 | |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 82 | class _WhereClause(object): |
| 83 | """Object allowing us to inject arbitrary SQL into Django queries. |
showard | 43a3d26 | 2008-11-12 18:17:05 +0000 | [diff] [blame] | 84 | |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 85 | By using this instead of extra(where=...), we can still freely combine |
| 86 | queries with & and |. |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 87 | """ |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 88 | def __init__(self, clause, values=()): |
| 89 | self._clause = clause |
| 90 | self._values = values |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 91 | |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 92 | |
Dale Curtis | 74a314b | 2011-06-23 14:55:46 -0700 | [diff] [blame] | 93 | def as_sql(self, qn=None, connection=None): |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 94 | return self._clause, self._values |
| 95 | |
| 96 | |
| 97 | def relabel_aliases(self, change_map): |
| 98 | return |
showard | 43a3d26 | 2008-11-12 18:17:05 +0000 | [diff] [blame] | 99 | |
| 100 | |
showard | 8b0ea22 | 2009-12-23 19:23:03 +0000 | [diff] [blame] | 101 | def add_join(self, query_set, join_table, join_key, join_condition='', |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 102 | join_condition_values=(), join_from_key=None, alias=None, |
| 103 | suffix='', exclude=False, force_left_join=False): |
| 104 | """Add a join to query_set. |
| 105 | |
| 106 | Join looks like this: |
| 107 | (INNER|LEFT) JOIN <join_table> AS <alias> |
| 108 | ON (<this table>.<join_from_key> = <join_table>.<join_key> |
| 109 | and <join_condition>) |
| 110 | |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 111 | @param join_table table to join to |
| 112 | @param join_key field referencing back to this model to use for the join |
| 113 | @param join_condition extra condition for the ON clause of the join |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 114 | @param join_condition_values values to substitute into join_condition |
| 115 | @param join_from_key column on this model to join from. |
showard | 8b0ea22 | 2009-12-23 19:23:03 +0000 | [diff] [blame] | 116 | @param alias alias to use for for join |
| 117 | @param suffix suffix to add to join_table for the join alias, if no |
| 118 | alias is provided |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 119 | @param exclude if true, exclude rows that match this join (will use a |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 120 | LEFT OUTER JOIN and an appropriate WHERE condition) |
showard | c478040 | 2009-08-31 18:31:34 +0000 | [diff] [blame] | 121 | @param force_left_join - if true, a LEFT OUTER JOIN will be used |
| 122 | instead of an INNER JOIN regardless of other options |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 123 | """ |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 124 | join_from_table = query_set.model._meta.db_table |
| 125 | if join_from_key is None: |
| 126 | join_from_key = self.model._meta.pk.name |
| 127 | if alias is None: |
| 128 | alias = join_table + suffix |
| 129 | full_join_key = _quote_name(alias) + '.' + _quote_name(join_key) |
| 130 | full_join_condition = '%s = %s.%s' % (full_join_key, |
| 131 | _quote_name(join_from_table), |
| 132 | _quote_name(join_from_key)) |
showard | 43a3d26 | 2008-11-12 18:17:05 +0000 | [diff] [blame] | 133 | if join_condition: |
| 134 | full_join_condition += ' AND (' + join_condition + ')' |
| 135 | if exclude or force_left_join: |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 136 | join_type = query_set.query.LOUTER |
showard | 43a3d26 | 2008-11-12 18:17:05 +0000 | [diff] [blame] | 137 | else: |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 138 | join_type = query_set.query.INNER |
showard | 43a3d26 | 2008-11-12 18:17:05 +0000 | [diff] [blame] | 139 | |
showard | f828c77 | 2010-01-25 21:49:42 +0000 | [diff] [blame] | 140 | query_set = self.CustomQuery.convert_query(query_set) |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 141 | query_set.query.add_custom_join(join_table, |
| 142 | full_join_condition, |
| 143 | join_type, |
| 144 | condition_values=join_condition_values, |
| 145 | alias=alias) |
showard | 43a3d26 | 2008-11-12 18:17:05 +0000 | [diff] [blame] | 146 | |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 147 | if exclude: |
| 148 | query_set = query_set.extra(where=[full_join_key + ' IS NULL']) |
| 149 | |
| 150 | return query_set |
| 151 | |
| 152 | |
| 153 | def _info_for_many_to_one_join(self, field, join_to_query, alias): |
| 154 | """ |
| 155 | @param field: the ForeignKey field on the related model |
| 156 | @param join_to_query: the query over the related model that we're |
| 157 | joining to |
| 158 | @param alias: alias of joined table |
| 159 | """ |
| 160 | info = {} |
| 161 | rhs_table = join_to_query.model._meta.db_table |
| 162 | info['rhs_table'] = rhs_table |
| 163 | info['rhs_column'] = field.column |
| 164 | info['lhs_column'] = field.rel.get_related_field().column |
| 165 | rhs_where = join_to_query.query.where |
| 166 | rhs_where.relabel_aliases({rhs_table: alias}) |
Dale Curtis | 74a314b | 2011-06-23 14:55:46 -0700 | [diff] [blame] | 167 | compiler = join_to_query.query.get_compiler(using=join_to_query.db) |
| 168 | initial_clause, values = compiler.as_sql() |
| 169 | all_clauses = (initial_clause,) |
| 170 | if hasattr(join_to_query.query, 'extra_where'): |
| 171 | all_clauses += join_to_query.query.extra_where |
| 172 | info['where_clause'] = ( |
| 173 | ' AND '.join('(%s)' % clause for clause in all_clauses)) |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 174 | info['values'] = values |
| 175 | return info |
| 176 | |
| 177 | |
| 178 | def _info_for_many_to_many_join(self, m2m_field, join_to_query, alias, |
| 179 | m2m_is_on_this_model): |
| 180 | """ |
| 181 | @param m2m_field: a Django field representing the M2M relationship. |
| 182 | It uses a pivot table with the following structure: |
| 183 | this model table <---> M2M pivot table <---> joined model table |
| 184 | @param join_to_query: the query over the related model that we're |
| 185 | joining to. |
| 186 | @param alias: alias of joined table |
| 187 | """ |
| 188 | if m2m_is_on_this_model: |
| 189 | # referenced field on this model |
| 190 | lhs_id_field = self.model._meta.pk |
| 191 | # foreign key on the pivot table referencing lhs_id_field |
| 192 | m2m_lhs_column = m2m_field.m2m_column_name() |
| 193 | # foreign key on the pivot table referencing rhd_id_field |
| 194 | m2m_rhs_column = m2m_field.m2m_reverse_name() |
| 195 | # referenced field on related model |
| 196 | rhs_id_field = m2m_field.rel.get_related_field() |
| 197 | else: |
| 198 | lhs_id_field = m2m_field.rel.get_related_field() |
| 199 | m2m_lhs_column = m2m_field.m2m_reverse_name() |
| 200 | m2m_rhs_column = m2m_field.m2m_column_name() |
| 201 | rhs_id_field = join_to_query.model._meta.pk |
| 202 | |
| 203 | info = {} |
| 204 | info['rhs_table'] = m2m_field.m2m_db_table() |
| 205 | info['rhs_column'] = m2m_lhs_column |
| 206 | info['lhs_column'] = lhs_id_field.column |
| 207 | |
| 208 | # select the ID of related models relevant to this join. we can only do |
| 209 | # a single join, so we need to gather this information up front and |
| 210 | # include it in the join condition. |
| 211 | rhs_ids = join_to_query.values_list(rhs_id_field.attname, flat=True) |
| 212 | assert len(rhs_ids) == 1, ('Many-to-many custom field joins can only ' |
| 213 | 'match a single related object.') |
| 214 | rhs_id = rhs_ids[0] |
| 215 | |
| 216 | info['where_clause'] = '%s.%s = %s' % (_quote_name(alias), |
| 217 | _quote_name(m2m_rhs_column), |
| 218 | rhs_id) |
| 219 | info['values'] = () |
| 220 | return info |
| 221 | |
| 222 | |
| 223 | def join_custom_field(self, query_set, join_to_query, alias, |
| 224 | left_join=True): |
| 225 | """Join to a related model to create a custom field in the given query. |
| 226 | |
| 227 | This method is used to construct a custom field on the given query based |
| 228 | on a many-valued relationsip. join_to_query should be a simple query |
| 229 | (no joins) on the related model which returns at most one related row |
| 230 | per instance of this model. |
| 231 | |
| 232 | For many-to-one relationships, the joined table contains the matching |
| 233 | row from the related model it one is related, NULL otherwise. |
| 234 | |
| 235 | For many-to-many relationships, the joined table contains the matching |
| 236 | row if it's related, NULL otherwise. |
| 237 | """ |
| 238 | relationship_type, field = self.determine_relationship( |
| 239 | join_to_query.model) |
| 240 | |
| 241 | if relationship_type == self.MANY_TO_ONE: |
| 242 | info = self._info_for_many_to_one_join(field, join_to_query, alias) |
| 243 | elif relationship_type == self.M2M_ON_RELATED_MODEL: |
| 244 | info = self._info_for_many_to_many_join( |
| 245 | m2m_field=field, join_to_query=join_to_query, alias=alias, |
| 246 | m2m_is_on_this_model=False) |
| 247 | elif relationship_type ==self.M2M_ON_THIS_MODEL: |
| 248 | info = self._info_for_many_to_many_join( |
| 249 | m2m_field=field, join_to_query=join_to_query, alias=alias, |
| 250 | m2m_is_on_this_model=True) |
| 251 | |
| 252 | return self.add_join(query_set, info['rhs_table'], info['rhs_column'], |
| 253 | join_from_key=info['lhs_column'], |
| 254 | join_condition=info['where_clause'], |
| 255 | join_condition_values=info['values'], |
| 256 | alias=alias, |
| 257 | force_left_join=left_join) |
| 258 | |
| 259 | |
showard | f828c77 | 2010-01-25 21:49:42 +0000 | [diff] [blame] | 260 | def key_on_joined_table(self, join_to_query): |
| 261 | """Get a non-null column on the table joined for the given query. |
| 262 | |
| 263 | This analyzes the join that would be produced if join_to_query were |
| 264 | passed to join_custom_field. |
| 265 | """ |
| 266 | relationship_type, field = self.determine_relationship( |
| 267 | join_to_query.model) |
| 268 | if relationship_type == self.MANY_TO_ONE: |
| 269 | return join_to_query.model._meta.pk.column |
| 270 | return field.m2m_column_name() # any column on the M2M table will do |
| 271 | |
| 272 | |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 273 | def add_where(self, query_set, where, values=()): |
| 274 | query_set = query_set.all() |
| 275 | query_set.query.where.add(self._WhereClause(where, values), |
| 276 | django.db.models.sql.where.AND) |
showard | c478040 | 2009-08-31 18:31:34 +0000 | [diff] [blame] | 277 | return query_set |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 278 | |
| 279 | |
showard | eaccf8f | 2009-04-16 03:11:33 +0000 | [diff] [blame] | 280 | def _get_quoted_field(self, table, field): |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 281 | return _quote_name(table) + '.' + _quote_name(field) |
showard | 5ef36e9 | 2008-07-02 16:37:09 +0000 | [diff] [blame] | 282 | |
| 283 | |
showard | 7c199df | 2008-10-03 10:17:15 +0000 | [diff] [blame] | 284 | def get_key_on_this_table(self, key_field=None): |
showard | 5ef36e9 | 2008-07-02 16:37:09 +0000 | [diff] [blame] | 285 | if key_field is None: |
| 286 | # default to primary key |
| 287 | key_field = self.model._meta.pk.column |
| 288 | return self._get_quoted_field(self.model._meta.db_table, key_field) |
| 289 | |
| 290 | |
showard | eaccf8f | 2009-04-16 03:11:33 +0000 | [diff] [blame] | 291 | def escape_user_sql(self, sql): |
| 292 | return sql.replace('%', '%%') |
| 293 | |
showard | 5ef36e9 | 2008-07-02 16:37:09 +0000 | [diff] [blame] | 294 | |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 295 | def _custom_select_query(self, query_set, selects): |
Jakob Juelich | 7bef841 | 2014-10-14 19:11:54 -0700 | [diff] [blame^] | 296 | """Execute a custom select query. |
| 297 | |
| 298 | @param query_set: query set as returned by query_objects. |
| 299 | @param selects: Tables/Columns to select, e.g. tko_test_labels_list.id. |
| 300 | |
| 301 | @returns: Result of the query as returned by cursor.fetchall(). |
| 302 | """ |
Dale Curtis | 74a314b | 2011-06-23 14:55:46 -0700 | [diff] [blame] | 303 | compiler = query_set.query.get_compiler(using=query_set.db) |
| 304 | sql, params = compiler.as_sql() |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 305 | from_ = sql[sql.find(' FROM'):] |
| 306 | |
| 307 | if query_set.query.distinct: |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 308 | distinct = 'DISTINCT ' |
| 309 | else: |
| 310 | distinct = '' |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 311 | |
| 312 | sql_query = ('SELECT ' + distinct + ','.join(selects) + from_) |
Jakob Juelich | 7bef841 | 2014-10-14 19:11:54 -0700 | [diff] [blame^] | 313 | # Chose the connection that's responsible for this type of object |
| 314 | cursor = connections[query_set.db].cursor() |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 315 | cursor.execute(sql_query, params) |
| 316 | return cursor.fetchall() |
| 317 | |
| 318 | |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 319 | def _is_relation_to(self, field, model_class): |
| 320 | return field.rel and field.rel.to is model_class |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 321 | |
| 322 | |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 323 | MANY_TO_ONE = object() |
| 324 | M2M_ON_RELATED_MODEL = object() |
| 325 | M2M_ON_THIS_MODEL = object() |
| 326 | |
| 327 | def determine_relationship(self, related_model): |
| 328 | """ |
| 329 | Determine the relationship between this model and related_model. |
| 330 | |
| 331 | related_model must have some sort of many-valued relationship to this |
| 332 | manager's model. |
| 333 | @returns (relationship_type, field), where relationship_type is one of |
| 334 | MANY_TO_ONE, M2M_ON_RELATED_MODEL, M2M_ON_THIS_MODEL, and field |
| 335 | is the Django field object for the relationship. |
| 336 | """ |
| 337 | # look for a foreign key field on related_model relating to this model |
| 338 | for field in related_model._meta.fields: |
| 339 | if self._is_relation_to(field, self.model): |
| 340 | return self.MANY_TO_ONE, field |
| 341 | |
| 342 | # look for an M2M field on related_model relating to this model |
| 343 | for field in related_model._meta.many_to_many: |
| 344 | if self._is_relation_to(field, self.model): |
| 345 | return self.M2M_ON_RELATED_MODEL, field |
| 346 | |
| 347 | # maybe this model has the many-to-many field |
| 348 | for field in self.model._meta.many_to_many: |
| 349 | if self._is_relation_to(field, related_model): |
| 350 | return self.M2M_ON_THIS_MODEL, field |
| 351 | |
| 352 | raise ValueError('%s has no relation to %s' % |
| 353 | (related_model, self.model)) |
| 354 | |
| 355 | |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 356 | def _get_pivot_iterator(self, base_objects_by_id, related_model): |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 357 | """ |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 358 | Determine the relationship between this model and related_model, and |
| 359 | return a pivot iterator. |
| 360 | @param base_objects_by_id: dict of instances of this model indexed by |
| 361 | their IDs |
| 362 | @returns a pivot iterator, which yields a tuple (base_object, |
| 363 | related_object) for each relationship between a base object and a |
| 364 | related object. all base_object instances come from base_objects_by_id. |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 365 | Note -- this depends on Django model internals. |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 366 | """ |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 367 | relationship_type, field = self.determine_relationship(related_model) |
| 368 | if relationship_type == self.MANY_TO_ONE: |
| 369 | return self._many_to_one_pivot(base_objects_by_id, |
| 370 | related_model, field) |
| 371 | elif relationship_type == self.M2M_ON_RELATED_MODEL: |
| 372 | return self._many_to_many_pivot( |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 373 | base_objects_by_id, related_model, field.m2m_db_table(), |
| 374 | field.m2m_reverse_name(), field.m2m_column_name()) |
showard | 7e67b43 | 2010-01-20 01:13:04 +0000 | [diff] [blame] | 375 | else: |
| 376 | assert relationship_type == self.M2M_ON_THIS_MODEL |
| 377 | return self._many_to_many_pivot( |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 378 | base_objects_by_id, related_model, field.m2m_db_table(), |
| 379 | field.m2m_column_name(), field.m2m_reverse_name()) |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 380 | |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 381 | |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 382 | def _many_to_one_pivot(self, base_objects_by_id, related_model, |
| 383 | foreign_key_field): |
| 384 | """ |
| 385 | @returns a pivot iterator - see _get_pivot_iterator() |
| 386 | """ |
| 387 | filter_data = {foreign_key_field.name + '__pk__in': |
| 388 | base_objects_by_id.keys()} |
| 389 | for related_object in related_model.objects.filter(**filter_data): |
showard | a5a72c9 | 2009-08-20 23:35:21 +0000 | [diff] [blame] | 390 | # lookup base object in the dict, rather than grabbing it from the |
| 391 | # related object. we need to return instances from the dict, not |
| 392 | # fresh instances of the same models (and grabbing model instances |
| 393 | # from the related models incurs a DB query each time). |
| 394 | base_object_id = getattr(related_object, foreign_key_field.attname) |
| 395 | base_object = base_objects_by_id[base_object_id] |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 396 | yield base_object, related_object |
| 397 | |
| 398 | |
| 399 | def _query_pivot_table(self, base_objects_by_id, pivot_table, |
Jakob Juelich | 7bef841 | 2014-10-14 19:11:54 -0700 | [diff] [blame^] | 400 | pivot_from_field, pivot_to_field, related_model): |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 401 | """ |
| 402 | @param id_list list of IDs of self.model objects to include |
| 403 | @param pivot_table the name of the pivot table |
| 404 | @param pivot_from_field a field name on pivot_table referencing |
| 405 | self.model |
| 406 | @param pivot_to_field a field name on pivot_table referencing the |
| 407 | related model. |
Jakob Juelich | 7bef841 | 2014-10-14 19:11:54 -0700 | [diff] [blame^] | 408 | @param related_model the related model |
| 409 | |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 410 | @returns pivot list of IDs (base_id, related_id) |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 411 | """ |
| 412 | query = """ |
| 413 | SELECT %(from_field)s, %(to_field)s |
| 414 | FROM %(table)s |
| 415 | WHERE %(from_field)s IN (%(id_list)s) |
| 416 | """ % dict(from_field=pivot_from_field, |
| 417 | to_field=pivot_to_field, |
| 418 | table=pivot_table, |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 419 | id_list=','.join(str(id_) for id_ |
| 420 | in base_objects_by_id.iterkeys())) |
Jakob Juelich | 7bef841 | 2014-10-14 19:11:54 -0700 | [diff] [blame^] | 421 | |
| 422 | # Chose the connection that's responsible for this type of object |
| 423 | # The databases for related_model and the current model will always |
| 424 | # be the same, related_model is just easier to obtain here because |
| 425 | # self is only a ExtendedManager, not the object. |
| 426 | cursor = connections[related_model.objects.db].cursor() |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 427 | cursor.execute(query) |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 428 | return cursor.fetchall() |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 429 | |
| 430 | |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 431 | def _many_to_many_pivot(self, base_objects_by_id, related_model, |
| 432 | pivot_table, pivot_from_field, pivot_to_field): |
| 433 | """ |
| 434 | @param pivot_table: see _query_pivot_table |
| 435 | @param pivot_from_field: see _query_pivot_table |
| 436 | @param pivot_to_field: see _query_pivot_table |
| 437 | @returns a pivot iterator - see _get_pivot_iterator() |
| 438 | """ |
| 439 | id_pivot = self._query_pivot_table(base_objects_by_id, pivot_table, |
Jakob Juelich | 7bef841 | 2014-10-14 19:11:54 -0700 | [diff] [blame^] | 440 | pivot_from_field, pivot_to_field, |
| 441 | related_model) |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 442 | |
| 443 | all_related_ids = list(set(related_id for base_id, related_id |
| 444 | in id_pivot)) |
| 445 | related_objects_by_id = related_model.objects.in_bulk(all_related_ids) |
| 446 | |
| 447 | for base_id, related_id in id_pivot: |
| 448 | yield base_objects_by_id[base_id], related_objects_by_id[related_id] |
| 449 | |
| 450 | |
| 451 | def populate_relationships(self, base_objects, related_model, |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 452 | related_list_name): |
| 453 | """ |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 454 | For each instance of this model in base_objects, add a field named |
| 455 | related_list_name listing all the related objects of type related_model. |
| 456 | related_model must be in a many-to-one or many-to-many relationship with |
| 457 | this model. |
| 458 | @param base_objects - list of instances of this model |
| 459 | @param related_model - model class related to this model |
| 460 | @param related_list_name - attribute name in which to store the related |
| 461 | object list. |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 462 | """ |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 463 | if not base_objects: |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 464 | # if we don't bail early, we'll get a SQL error later |
| 465 | return |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 466 | |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 467 | base_objects_by_id = dict((base_object._get_pk_val(), base_object) |
| 468 | for base_object in base_objects) |
| 469 | pivot_iterator = self._get_pivot_iterator(base_objects_by_id, |
| 470 | related_model) |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 471 | |
showard | 68693f7 | 2009-05-20 00:31:53 +0000 | [diff] [blame] | 472 | for base_object in base_objects: |
| 473 | setattr(base_object, related_list_name, []) |
| 474 | |
| 475 | for base_object, related_object in pivot_iterator: |
| 476 | getattr(base_object, related_list_name).append(related_object) |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 477 | |
| 478 | |
jamesren | e365623 | 2010-03-02 00:00:30 +0000 | [diff] [blame] | 479 | class ModelWithInvalidQuerySet(dbmodels.query.QuerySet): |
| 480 | """ |
| 481 | QuerySet that handles delete() properly for models with an "invalid" bit |
| 482 | """ |
| 483 | def delete(self): |
| 484 | for model in self: |
| 485 | model.delete() |
| 486 | |
| 487 | |
| 488 | class ModelWithInvalidManager(ExtendedManager): |
| 489 | """ |
| 490 | Manager for objects with an "invalid" bit |
| 491 | """ |
| 492 | def get_query_set(self): |
| 493 | return ModelWithInvalidQuerySet(self.model) |
| 494 | |
| 495 | |
| 496 | class ValidObjectsManager(ModelWithInvalidManager): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 497 | """ |
| 498 | Manager returning only objects with invalid=False. |
| 499 | """ |
| 500 | def get_query_set(self): |
| 501 | queryset = super(ValidObjectsManager, self).get_query_set() |
| 502 | return queryset.filter(invalid=False) |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 503 | |
| 504 | |
Prashanth B | 489b91d | 2014-03-15 12:17:16 -0700 | [diff] [blame] | 505 | class ModelExtensions(rdb_model_extensions.ModelValidators): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 506 | """\ |
Prashanth B | 489b91d | 2014-03-15 12:17:16 -0700 | [diff] [blame] | 507 | Mixin with convenience functions for models, built on top of |
| 508 | the model validators in rdb_model_extensions. |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 509 | """ |
| 510 | # TODO: at least some of these functions really belong in a custom |
| 511 | # Manager class |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 512 | |
Jakob Juelich | 3bb7c80 | 2014-09-02 16:31:11 -0700 | [diff] [blame] | 513 | |
| 514 | SERIALIZATION_LINKS_TO_FOLLOW = set() |
| 515 | """ |
| 516 | To be able to send jobs and hosts to shards, it's necessary to find their |
| 517 | dependencies. |
| 518 | The most generic approach for this would be to traverse all relationships |
| 519 | to other objects recursively. This would list all objects that are related |
| 520 | in any way. |
| 521 | But this approach finds too many objects: If a host should be transferred, |
| 522 | all it's relationships would be traversed. This would find an acl group. |
| 523 | If then the acl group's relationships are traversed, the relationship |
| 524 | would be followed backwards and many other hosts would be found. |
| 525 | |
| 526 | This mapping tells that algorithm which relations to follow explicitly. |
| 527 | """ |
| 528 | |
Jakob Juelich | f865d33 | 2014-09-29 10:47:49 -0700 | [diff] [blame] | 529 | |
| 530 | SERIALIZATION_LOCAL_LINKS_TO_UPDATE = set() |
| 531 | """ |
| 532 | On deserializion, if the object to persist already exists, local fields |
| 533 | will only be updated, if their name is in this set. |
| 534 | """ |
| 535 | |
| 536 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 537 | @classmethod |
| 538 | def convert_human_readable_values(cls, data, to_human_readable=False): |
| 539 | """\ |
| 540 | Performs conversions on user-supplied field data, to make it |
| 541 | easier for users to pass human-readable data. |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 542 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 543 | For all fields that have choice sets, convert their values |
| 544 | from human-readable strings to enum values, if necessary. This |
| 545 | allows users to pass strings instead of the corresponding |
| 546 | integer values. |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 547 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 548 | For all foreign key fields, call smart_get with the supplied |
| 549 | data. This allows the user to pass either an ID value or |
| 550 | the name of the object as a string. |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 551 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 552 | If to_human_readable=True, perform the inverse - i.e. convert |
| 553 | numeric values to human readable values. |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 554 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 555 | This method modifies data in-place. |
| 556 | """ |
| 557 | field_dict = cls.get_field_dict() |
| 558 | for field_name in data: |
showard | e732ee7 | 2008-09-23 19:15:43 +0000 | [diff] [blame] | 559 | if field_name not in field_dict or data[field_name] is None: |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 560 | continue |
| 561 | field_obj = field_dict[field_name] |
| 562 | # convert enum values |
| 563 | if field_obj.choices: |
| 564 | for choice_data in field_obj.choices: |
| 565 | # choice_data is (value, name) |
| 566 | if to_human_readable: |
| 567 | from_val, to_val = choice_data |
| 568 | else: |
| 569 | to_val, from_val = choice_data |
| 570 | if from_val == data[field_name]: |
| 571 | data[field_name] = to_val |
| 572 | break |
| 573 | # convert foreign key values |
| 574 | elif field_obj.rel: |
showard | a4ea574 | 2009-02-17 20:56:23 +0000 | [diff] [blame] | 575 | dest_obj = field_obj.rel.to.smart_get(data[field_name], |
| 576 | valid_only=False) |
showard | f8b1904 | 2009-05-12 17:22:49 +0000 | [diff] [blame] | 577 | if to_human_readable: |
Paul Pendlebury | 5a8c6ad | 2011-02-01 07:20:17 -0800 | [diff] [blame] | 578 | # parameterized_jobs do not have a name_field |
| 579 | if (field_name != 'parameterized_job' and |
| 580 | dest_obj.name_field is not None): |
showard | f8b1904 | 2009-05-12 17:22:49 +0000 | [diff] [blame] | 581 | data[field_name] = getattr(dest_obj, |
| 582 | dest_obj.name_field) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 583 | else: |
showard | b0a7303 | 2009-03-27 18:35:41 +0000 | [diff] [blame] | 584 | data[field_name] = dest_obj |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 585 | |
| 586 | |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 587 | |
| 588 | |
Dale Curtis | 74a314b | 2011-06-23 14:55:46 -0700 | [diff] [blame] | 589 | def _validate_unique(self): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 590 | """\ |
| 591 | Validate that unique fields are unique. Django manipulators do |
| 592 | this too, but they're a huge pain to use manually. Trust me. |
| 593 | """ |
| 594 | errors = {} |
| 595 | cls = type(self) |
| 596 | field_dict = self.get_field_dict() |
| 597 | manager = cls.get_valid_manager() |
| 598 | for field_name, field_obj in field_dict.iteritems(): |
| 599 | if not field_obj.unique: |
| 600 | continue |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 601 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 602 | value = getattr(self, field_name) |
showard | bd18ab7 | 2009-09-18 21:20:27 +0000 | [diff] [blame] | 603 | if value is None and field_obj.auto_created: |
| 604 | # don't bother checking autoincrement fields about to be |
| 605 | # generated |
| 606 | continue |
| 607 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 608 | existing_objs = manager.filter(**{field_name : value}) |
| 609 | num_existing = existing_objs.count() |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 610 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 611 | if num_existing == 0: |
| 612 | continue |
| 613 | if num_existing == 1 and existing_objs[0].id == self.id: |
| 614 | continue |
| 615 | errors[field_name] = ( |
| 616 | 'This value must be unique (%s)' % (value)) |
| 617 | return errors |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 618 | |
| 619 | |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 620 | def _validate(self): |
| 621 | """ |
| 622 | First coerces all fields on this instance to their proper Python types. |
| 623 | Then runs validation on every field. Returns a dictionary of |
| 624 | field_name -> error_list. |
| 625 | |
| 626 | Based on validate() from django.db.models.Model in Django 0.96, which |
| 627 | was removed in Django 1.0. It should reappear in a later version. See: |
| 628 | http://code.djangoproject.com/ticket/6845 |
| 629 | """ |
| 630 | error_dict = {} |
| 631 | for f in self._meta.fields: |
| 632 | try: |
| 633 | python_value = f.to_python( |
| 634 | getattr(self, f.attname, f.get_default())) |
| 635 | except django.core.exceptions.ValidationError, e: |
jamesren | 1e0a4ce | 2010-04-21 17:45:11 +0000 | [diff] [blame] | 636 | error_dict[f.name] = str(e) |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 637 | continue |
| 638 | |
| 639 | if not f.blank and not python_value: |
| 640 | error_dict[f.name] = 'This field is required.' |
| 641 | continue |
| 642 | |
| 643 | setattr(self, f.attname, python_value) |
| 644 | |
| 645 | return error_dict |
| 646 | |
| 647 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 648 | def do_validate(self): |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 649 | errors = self._validate() |
Dale Curtis | 74a314b | 2011-06-23 14:55:46 -0700 | [diff] [blame] | 650 | unique_errors = self._validate_unique() |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 651 | for field_name, error in unique_errors.iteritems(): |
| 652 | errors.setdefault(field_name, error) |
| 653 | if errors: |
| 654 | raise ValidationError(errors) |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 655 | |
| 656 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 657 | # actually (externally) useful methods follow |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 658 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 659 | @classmethod |
| 660 | def add_object(cls, data={}, **kwargs): |
| 661 | """\ |
| 662 | Returns a new object created with the given data (a dictionary |
| 663 | mapping field names to values). Merges any extra keyword args |
| 664 | into data. |
| 665 | """ |
Prashanth B | 489b91d | 2014-03-15 12:17:16 -0700 | [diff] [blame] | 666 | data = dict(data) |
| 667 | data.update(kwargs) |
| 668 | data = cls.prepare_data_args(data) |
| 669 | cls.convert_human_readable_values(data) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 670 | data = cls.provide_default_values(data) |
Prashanth B | 489b91d | 2014-03-15 12:17:16 -0700 | [diff] [blame] | 671 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 672 | obj = cls(**data) |
| 673 | obj.do_validate() |
| 674 | obj.save() |
| 675 | return obj |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 676 | |
| 677 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 678 | def update_object(self, data={}, **kwargs): |
| 679 | """\ |
| 680 | Updates the object with the given data (a dictionary mapping |
| 681 | field names to values). Merges any extra keyword args into |
| 682 | data. |
| 683 | """ |
Prashanth B | 489b91d | 2014-03-15 12:17:16 -0700 | [diff] [blame] | 684 | data = dict(data) |
| 685 | data.update(kwargs) |
| 686 | data = self.prepare_data_args(data) |
| 687 | self.convert_human_readable_values(data) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 688 | for field_name, value in data.iteritems(): |
showard | b0a7303 | 2009-03-27 18:35:41 +0000 | [diff] [blame] | 689 | setattr(self, field_name, value) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 690 | self.do_validate() |
| 691 | self.save() |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 692 | |
| 693 | |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 694 | # see query_objects() |
| 695 | _SPECIAL_FILTER_KEYS = ('query_start', 'query_limit', 'sort_by', |
| 696 | 'extra_args', 'extra_where', 'no_distinct') |
| 697 | |
| 698 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 699 | @classmethod |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 700 | def _extract_special_params(cls, filter_data): |
| 701 | """ |
| 702 | @returns a tuple of dicts (special_params, regular_filters), where |
| 703 | special_params contains the parameters we handle specially and |
| 704 | regular_filters is the remaining data to be handled by Django. |
| 705 | """ |
| 706 | regular_filters = dict(filter_data) |
| 707 | special_params = {} |
| 708 | for key in cls._SPECIAL_FILTER_KEYS: |
| 709 | if key in regular_filters: |
| 710 | special_params[key] = regular_filters.pop(key) |
| 711 | return special_params, regular_filters |
| 712 | |
| 713 | |
| 714 | @classmethod |
| 715 | def apply_presentation(cls, query, filter_data): |
| 716 | """ |
| 717 | Apply presentation parameters -- sorting and paging -- to the given |
| 718 | query. |
| 719 | @returns new query with presentation applied |
| 720 | """ |
| 721 | special_params, _ = cls._extract_special_params(filter_data) |
| 722 | sort_by = special_params.get('sort_by', None) |
| 723 | if sort_by: |
| 724 | assert isinstance(sort_by, list) or isinstance(sort_by, tuple) |
showard | 8b0ea22 | 2009-12-23 19:23:03 +0000 | [diff] [blame] | 725 | query = query.extra(order_by=sort_by) |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 726 | |
| 727 | query_start = special_params.get('query_start', None) |
| 728 | query_limit = special_params.get('query_limit', None) |
| 729 | if query_start is not None: |
| 730 | if query_limit is None: |
| 731 | raise ValueError('Cannot pass query_start without query_limit') |
| 732 | # query_limit is passed as a page size |
showard | 7074b74 | 2009-10-12 20:30:04 +0000 | [diff] [blame] | 733 | query_limit += query_start |
| 734 | return query[query_start:query_limit] |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 735 | |
| 736 | |
| 737 | @classmethod |
| 738 | def query_objects(cls, filter_data, valid_only=True, initial_query=None, |
| 739 | apply_presentation=True): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 740 | """\ |
| 741 | Returns a QuerySet object for querying the given model_class |
| 742 | with the given filter_data. Optional special arguments in |
| 743 | filter_data include: |
| 744 | -query_start: index of first return to return |
| 745 | -query_limit: maximum number of results to return |
| 746 | -sort_by: list of fields to sort on. prefixing a '-' onto a |
| 747 | field name changes the sort to descending order. |
| 748 | -extra_args: keyword args to pass to query.extra() (see Django |
| 749 | DB layer documentation) |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 750 | -extra_where: extra WHERE clause to append |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 751 | -no_distinct: if True, a DISTINCT will not be added to the SELECT |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 752 | """ |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 753 | special_params, regular_filters = cls._extract_special_params( |
| 754 | filter_data) |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 755 | |
showard | 7ac7b7a | 2008-07-21 20:24:29 +0000 | [diff] [blame] | 756 | if initial_query is None: |
| 757 | if valid_only: |
| 758 | initial_query = cls.get_valid_manager() |
| 759 | else: |
| 760 | initial_query = cls.objects |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 761 | |
| 762 | query = initial_query.filter(**regular_filters) |
| 763 | |
| 764 | use_distinct = not special_params.get('no_distinct', False) |
showard | 7ac7b7a | 2008-07-21 20:24:29 +0000 | [diff] [blame] | 765 | if use_distinct: |
| 766 | query = query.distinct() |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 767 | |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 768 | extra_args = special_params.get('extra_args', {}) |
| 769 | extra_where = special_params.get('extra_where', None) |
| 770 | if extra_where: |
| 771 | # escape %'s |
| 772 | extra_where = cls.objects.escape_user_sql(extra_where) |
| 773 | extra_args.setdefault('where', []).append(extra_where) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 774 | if extra_args: |
| 775 | query = query.extra(**extra_args) |
Jakob Juelich | 7bef841 | 2014-10-14 19:11:54 -0700 | [diff] [blame^] | 776 | # TODO: Use readonly connection for these queries. |
| 777 | # This has been disabled, because it's not used anyway, as the |
| 778 | # configured readonly user is the same as the real user anyway. |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 779 | |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 780 | if apply_presentation: |
| 781 | query = cls.apply_presentation(query, filter_data) |
| 782 | |
| 783 | return query |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 784 | |
| 785 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 786 | @classmethod |
showard | 585c2ab | 2008-07-23 19:29:49 +0000 | [diff] [blame] | 787 | def query_count(cls, filter_data, initial_query=None): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 788 | """\ |
| 789 | Like query_objects, but retreive only the count of results. |
| 790 | """ |
| 791 | filter_data.pop('query_start', None) |
| 792 | filter_data.pop('query_limit', None) |
showard | 585c2ab | 2008-07-23 19:29:49 +0000 | [diff] [blame] | 793 | query = cls.query_objects(filter_data, initial_query=initial_query) |
| 794 | return query.count() |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 795 | |
| 796 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 797 | @classmethod |
| 798 | def clean_object_dicts(cls, field_dicts): |
| 799 | """\ |
| 800 | Take a list of dicts corresponding to object (as returned by |
| 801 | query.values()) and clean the data to be more suitable for |
| 802 | returning to the user. |
| 803 | """ |
showard | e732ee7 | 2008-09-23 19:15:43 +0000 | [diff] [blame] | 804 | for field_dict in field_dicts: |
| 805 | cls.clean_foreign_keys(field_dict) |
showard | 21baa45 | 2008-10-21 00:08:39 +0000 | [diff] [blame] | 806 | cls._convert_booleans(field_dict) |
showard | e732ee7 | 2008-09-23 19:15:43 +0000 | [diff] [blame] | 807 | cls.convert_human_readable_values(field_dict, |
| 808 | to_human_readable=True) |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 809 | |
| 810 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 811 | @classmethod |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 812 | def list_objects(cls, filter_data, initial_query=None): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 813 | """\ |
| 814 | Like query_objects, but return a list of dictionaries. |
| 815 | """ |
showard | 7ac7b7a | 2008-07-21 20:24:29 +0000 | [diff] [blame] | 816 | query = cls.query_objects(filter_data, initial_query=initial_query) |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 817 | extra_fields = query.query.extra_select.keys() |
| 818 | field_dicts = [model_object.get_object_dict(extra_fields=extra_fields) |
showard | e732ee7 | 2008-09-23 19:15:43 +0000 | [diff] [blame] | 819 | for model_object in query] |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 820 | return field_dicts |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 821 | |
| 822 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 823 | @classmethod |
showard | a4ea574 | 2009-02-17 20:56:23 +0000 | [diff] [blame] | 824 | def smart_get(cls, id_or_name, valid_only=True): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 825 | """\ |
| 826 | smart_get(integer) -> get object by ID |
| 827 | smart_get(string) -> get object by name_field |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 828 | """ |
showard | a4ea574 | 2009-02-17 20:56:23 +0000 | [diff] [blame] | 829 | if valid_only: |
| 830 | manager = cls.get_valid_manager() |
| 831 | else: |
| 832 | manager = cls.objects |
| 833 | |
| 834 | if isinstance(id_or_name, (int, long)): |
| 835 | return manager.get(pk=id_or_name) |
jamesren | 3e9f609 | 2010-03-11 21:32:10 +0000 | [diff] [blame] | 836 | if isinstance(id_or_name, basestring) and hasattr(cls, 'name_field'): |
showard | a4ea574 | 2009-02-17 20:56:23 +0000 | [diff] [blame] | 837 | return manager.get(**{cls.name_field : id_or_name}) |
| 838 | raise ValueError( |
| 839 | 'Invalid positional argument: %s (%s)' % (id_or_name, |
| 840 | type(id_or_name))) |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 841 | |
| 842 | |
showard | be3ec04 | 2008-11-12 18:16:07 +0000 | [diff] [blame] | 843 | @classmethod |
| 844 | def smart_get_bulk(cls, id_or_name_list): |
| 845 | invalid_inputs = [] |
| 846 | result_objects = [] |
| 847 | for id_or_name in id_or_name_list: |
| 848 | try: |
| 849 | result_objects.append(cls.smart_get(id_or_name)) |
| 850 | except cls.DoesNotExist: |
| 851 | invalid_inputs.append(id_or_name) |
| 852 | if invalid_inputs: |
mbligh | 7a3ebe3 | 2008-12-01 17:10:33 +0000 | [diff] [blame] | 853 | raise cls.DoesNotExist('The following %ss do not exist: %s' |
| 854 | % (cls.__name__.lower(), |
| 855 | ', '.join(invalid_inputs))) |
showard | be3ec04 | 2008-11-12 18:16:07 +0000 | [diff] [blame] | 856 | return result_objects |
| 857 | |
| 858 | |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 859 | def get_object_dict(self, extra_fields=None): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 860 | """\ |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 861 | Return a dictionary mapping fields to this object's values. @param |
| 862 | extra_fields: list of extra attribute names to include, in addition to |
| 863 | the fields defined on this object. |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 864 | """ |
showard | 8bfb5cb | 2009-10-07 20:49:15 +0000 | [diff] [blame] | 865 | fields = self.get_field_dict().keys() |
| 866 | if extra_fields: |
| 867 | fields += extra_fields |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 868 | object_dict = dict((field_name, getattr(self, field_name)) |
showard | e732ee7 | 2008-09-23 19:15:43 +0000 | [diff] [blame] | 869 | for field_name in fields) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 870 | self.clean_object_dicts([object_dict]) |
showard | d3dc199 | 2009-04-22 21:01:40 +0000 | [diff] [blame] | 871 | self._postprocess_object_dict(object_dict) |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 872 | return object_dict |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 873 | |
| 874 | |
showard | d3dc199 | 2009-04-22 21:01:40 +0000 | [diff] [blame] | 875 | def _postprocess_object_dict(self, object_dict): |
| 876 | """For subclasses to override.""" |
| 877 | pass |
| 878 | |
| 879 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 880 | @classmethod |
| 881 | def get_valid_manager(cls): |
| 882 | return cls.objects |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 883 | |
| 884 | |
showard | 2bab8f4 | 2008-11-12 18:15:22 +0000 | [diff] [blame] | 885 | def _record_attributes(self, attributes): |
| 886 | """ |
| 887 | See on_attribute_changed. |
| 888 | """ |
| 889 | assert not isinstance(attributes, basestring) |
| 890 | self._recorded_attributes = dict((attribute, getattr(self, attribute)) |
| 891 | for attribute in attributes) |
| 892 | |
| 893 | |
| 894 | def _check_for_updated_attributes(self): |
| 895 | """ |
| 896 | See on_attribute_changed. |
| 897 | """ |
| 898 | for attribute, original_value in self._recorded_attributes.iteritems(): |
| 899 | new_value = getattr(self, attribute) |
| 900 | if original_value != new_value: |
| 901 | self.on_attribute_changed(attribute, original_value) |
| 902 | self._record_attributes(self._recorded_attributes.keys()) |
| 903 | |
| 904 | |
| 905 | def on_attribute_changed(self, attribute, old_value): |
| 906 | """ |
| 907 | Called whenever an attribute is updated. To be overridden. |
| 908 | |
| 909 | To use this method, you must: |
| 910 | * call _record_attributes() from __init__() (after making the super |
| 911 | call) with a list of attributes for which you want to be notified upon |
| 912 | change. |
| 913 | * call _check_for_updated_attributes() from save(). |
| 914 | """ |
| 915 | pass |
| 916 | |
| 917 | |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 918 | def serialize(self, include_dependencies=True): |
Jakob Juelich | 3bb7c80 | 2014-09-02 16:31:11 -0700 | [diff] [blame] | 919 | """Serializes the object with dependencies. |
| 920 | |
| 921 | The variable SERIALIZATION_LINKS_TO_FOLLOW defines which dependencies |
| 922 | this function will serialize with the object. |
| 923 | |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 924 | @param include_dependencies: Whether or not to follow relations to |
| 925 | objects this object depends on. |
| 926 | This parameter is used when uploading |
| 927 | jobs from a shard to the master, as the |
| 928 | master already has all the dependent |
| 929 | objects. |
| 930 | |
Jakob Juelich | 3bb7c80 | 2014-09-02 16:31:11 -0700 | [diff] [blame] | 931 | @returns: Dictionary representation of the object. |
| 932 | """ |
| 933 | serialized = {} |
| 934 | for field in self._meta.concrete_model._meta.local_fields: |
| 935 | if field.rel is None: |
| 936 | serialized[field.name] = field._get_val_from_obj(self) |
| 937 | |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 938 | if include_dependencies: |
| 939 | for link in self.SERIALIZATION_LINKS_TO_FOLLOW: |
| 940 | serialized[link] = self._serialize_relation(link) |
Jakob Juelich | 3bb7c80 | 2014-09-02 16:31:11 -0700 | [diff] [blame] | 941 | |
| 942 | return serialized |
| 943 | |
| 944 | |
| 945 | def _serialize_relation(self, link): |
| 946 | """Serializes dependent objects given the name of the relation. |
| 947 | |
| 948 | @param link: Name of the relation to take objects from. |
| 949 | |
| 950 | @returns For To-Many relationships a list of the serialized related |
| 951 | objects, for To-One relationships the serialized related object. |
| 952 | """ |
| 953 | try: |
| 954 | attr = getattr(self, link) |
| 955 | except AttributeError: |
| 956 | # One-To-One relationships that point to None may raise this |
| 957 | return None |
| 958 | |
| 959 | if attr is None: |
| 960 | return None |
| 961 | if hasattr(attr, 'all'): |
| 962 | return [obj.serialize() for obj in attr.all()] |
| 963 | return attr.serialize() |
| 964 | |
| 965 | |
Jakob Juelich | f88fa93 | 2014-09-03 17:58:04 -0700 | [diff] [blame] | 966 | @classmethod |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 967 | def _split_local_from_foreign_values(cls, data): |
| 968 | """This splits local from foreign values in a serialized object. |
| 969 | |
| 970 | @param data: The serialized object. |
| 971 | |
| 972 | @returns A tuple of two lists, both containing tuples in the form |
| 973 | (link_name, link_value). The first list contains all links |
| 974 | for local fields, the second one contains those for foreign |
| 975 | fields/objects. |
| 976 | """ |
| 977 | links_to_local_values, links_to_related_values = [], [] |
| 978 | for link, value in data.iteritems(): |
| 979 | if link in cls.SERIALIZATION_LINKS_TO_FOLLOW: |
| 980 | # It's a foreign key |
| 981 | links_to_related_values.append((link, value)) |
| 982 | else: |
| 983 | # It's a local attribute |
| 984 | links_to_local_values.append((link, value)) |
| 985 | return links_to_local_values, links_to_related_values |
| 986 | |
| 987 | |
Jakob Juelich | f865d33 | 2014-09-29 10:47:49 -0700 | [diff] [blame] | 988 | @classmethod |
| 989 | def _filter_update_allowed_fields(cls, data): |
| 990 | """Filters data and returns only files that updates are allowed on. |
| 991 | |
| 992 | This is i.e. needed for syncing aborted bits from the master to shards. |
| 993 | |
| 994 | Local links are only allowed to be updated, if they are in |
| 995 | SERIALIZATION_LOCAL_LINKS_TO_UPDATE. |
| 996 | Overwriting existing values is allowed in order to be able to sync i.e. |
| 997 | the aborted bit from the master to a shard. |
| 998 | |
| 999 | The whitelisting mechanism is in place to prevent overwriting local |
| 1000 | status: If all fields were overwritten, jobs would be completely be |
| 1001 | set back to their original (unstarted) state. |
| 1002 | |
| 1003 | @param data: List with tuples of the form (link_name, link_value), as |
| 1004 | returned by _split_local_from_foreign_values. |
| 1005 | |
| 1006 | @returns List of the same format as data, but only containing data for |
| 1007 | fields that updates are allowed on. |
| 1008 | """ |
| 1009 | return [pair for pair in data |
| 1010 | if pair[0] in cls.SERIALIZATION_LOCAL_LINKS_TO_UPDATE] |
| 1011 | |
| 1012 | |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 1013 | def _deserialize_local(self, data): |
| 1014 | """Set local attributes from a list of tuples. |
| 1015 | |
| 1016 | @param data: List of tuples like returned by |
| 1017 | _split_local_from_foreign_values. |
| 1018 | """ |
| 1019 | for link, value in data: |
| 1020 | setattr(self, link, value) |
| 1021 | # Overwridden save() methods are prone to errors, so don't execute them. |
| 1022 | # This is because: |
| 1023 | # - the overwritten methods depend on ACL groups that don't yet exist |
| 1024 | # and don't handle errors |
| 1025 | # - the overwritten methods think this object already exists in the db |
| 1026 | # because the id is already set |
| 1027 | super(type(self), self).save() |
| 1028 | |
| 1029 | |
| 1030 | def _deserialize_relations(self, data): |
| 1031 | """Set foreign attributes from a list of tuples. |
| 1032 | |
| 1033 | This deserialized the related objects using their own deserialize() |
| 1034 | function and then sets the relation. |
| 1035 | |
| 1036 | @param data: List of tuples like returned by |
| 1037 | _split_local_from_foreign_values. |
| 1038 | """ |
| 1039 | for link, value in data: |
| 1040 | self._deserialize_relation(link, value) |
| 1041 | # See comment in _deserialize_local |
| 1042 | super(type(self), self).save() |
| 1043 | |
| 1044 | |
| 1045 | @classmethod |
Jakob Juelich | f88fa93 | 2014-09-03 17:58:04 -0700 | [diff] [blame] | 1046 | def deserialize(cls, data): |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 1047 | """Recursively deserializes and saves an object with it's dependencies. |
Jakob Juelich | f88fa93 | 2014-09-03 17:58:04 -0700 | [diff] [blame] | 1048 | |
| 1049 | This takes the result of the serialize method and creates objects |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 1050 | in the database that are just like the original. |
| 1051 | |
| 1052 | If an object of the same type with the same id already exists, it's |
Jakob Juelich | f865d33 | 2014-09-29 10:47:49 -0700 | [diff] [blame] | 1053 | local values will be left untouched, unless they are explicitly |
| 1054 | whitelisted in SERIALIZATION_LOCAL_LINKS_TO_UPDATE. |
| 1055 | |
| 1056 | Deserialize will always recursively propagate to all related objects |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 1057 | present in data though. |
| 1058 | I.e. this is necessary to add users to an already existing acl-group. |
Jakob Juelich | f88fa93 | 2014-09-03 17:58:04 -0700 | [diff] [blame] | 1059 | |
| 1060 | @param data: Representation of an object and its dependencies, as |
| 1061 | returned by serialize. |
| 1062 | |
| 1063 | @returns: The object represented by data if it didn't exist before, |
| 1064 | otherwise the object that existed before and has the same type |
| 1065 | and id as the one described by data. |
| 1066 | """ |
| 1067 | if data is None: |
| 1068 | return None |
| 1069 | |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 1070 | local, related = cls._split_local_from_foreign_values(data) |
| 1071 | |
Jakob Juelich | f88fa93 | 2014-09-03 17:58:04 -0700 | [diff] [blame] | 1072 | try: |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 1073 | instance = cls.objects.get(id=data['id']) |
Jakob Juelich | f865d33 | 2014-09-29 10:47:49 -0700 | [diff] [blame] | 1074 | local = cls._filter_update_allowed_fields(local) |
Jakob Juelich | f88fa93 | 2014-09-03 17:58:04 -0700 | [diff] [blame] | 1075 | except cls.DoesNotExist: |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 1076 | instance = cls() |
Jakob Juelich | f88fa93 | 2014-09-03 17:58:04 -0700 | [diff] [blame] | 1077 | |
Jakob Juelich | f865d33 | 2014-09-29 10:47:49 -0700 | [diff] [blame] | 1078 | instance._deserialize_local(local) |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 1079 | instance._deserialize_relations(related) |
Jakob Juelich | f88fa93 | 2014-09-03 17:58:04 -0700 | [diff] [blame] | 1080 | |
| 1081 | return instance |
| 1082 | |
| 1083 | |
Jakob Juelich | a94efe6 | 2014-09-18 16:02:49 -0700 | [diff] [blame] | 1084 | def sanity_check_update_from_shard(self, shard, updated_serialized, |
| 1085 | *args, **kwargs): |
| 1086 | """Check if an update sent from a shard is legitimate. |
| 1087 | |
| 1088 | @raises error.UnallowedRecordsSentToMaster if an update is not |
| 1089 | legitimate. |
| 1090 | """ |
| 1091 | raise NotImplementedError( |
| 1092 | 'sanity_check_update_from_shard must be implemented by subclass %s ' |
| 1093 | 'for type %s' % type(self)) |
| 1094 | |
| 1095 | |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 1096 | def update_from_serialized(self, serialized): |
| 1097 | """Updates local fields of an existing object from a serialized form. |
| 1098 | |
| 1099 | This is different than the normal deserialize() in the way that it |
| 1100 | does update local values, which deserialize doesn't, but doesn't |
| 1101 | recursively propagate to related objects, which deserialize() does. |
| 1102 | |
| 1103 | The use case of this function is to update job records on the master |
| 1104 | after the jobs have been executed on a slave, as the master is not |
| 1105 | interested in updates for users, labels, specialtasks, etc. |
| 1106 | |
| 1107 | @param serialized: Representation of an object and its dependencies, as |
| 1108 | returned by serialize. |
| 1109 | |
| 1110 | @raises ValueError: if serialized contains related objects, i.e. not |
| 1111 | only local fields. |
| 1112 | """ |
| 1113 | local, related = ( |
| 1114 | self._split_local_from_foreign_values(serialized)) |
| 1115 | if related: |
| 1116 | raise ValueError('Serialized must not contain foreign ' |
| 1117 | 'objects: %s' % related) |
| 1118 | |
| 1119 | self._deserialize_local(local) |
| 1120 | |
| 1121 | |
Jakob Juelich | f88fa93 | 2014-09-03 17:58:04 -0700 | [diff] [blame] | 1122 | def custom_deserialize_relation(self, link, data): |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 1123 | """Allows overriding the deserialization behaviour by subclasses.""" |
Jakob Juelich | f88fa93 | 2014-09-03 17:58:04 -0700 | [diff] [blame] | 1124 | raise NotImplementedError( |
| 1125 | 'custom_deserialize_relation must be implemented by subclass %s ' |
| 1126 | 'for relation %s' % (type(self), link)) |
| 1127 | |
| 1128 | |
| 1129 | def _deserialize_relation(self, link, data): |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 1130 | """Deserializes related objects and sets references on this object. |
| 1131 | |
| 1132 | Relations that point to a list of objects are handled automatically. |
| 1133 | For many-to-one or one-to-one relations custom_deserialize_relation |
| 1134 | must be overridden by the subclass. |
| 1135 | |
| 1136 | Related objects are deserialized using their deserialize() method. |
| 1137 | Thereby they and their dependencies are created if they don't exist |
| 1138 | and saved to the database. |
| 1139 | |
| 1140 | @param link: Name of the relation. |
| 1141 | @param data: Serialized representation of the related object(s). |
| 1142 | This means a list of dictionaries for to-many relations, |
| 1143 | just a dictionary for to-one relations. |
| 1144 | """ |
Jakob Juelich | f88fa93 | 2014-09-03 17:58:04 -0700 | [diff] [blame] | 1145 | field = getattr(self, link) |
| 1146 | |
| 1147 | if field and hasattr(field, 'all'): |
| 1148 | self._deserialize_2m_relation(link, data, field.model) |
| 1149 | else: |
| 1150 | self.custom_deserialize_relation(link, data) |
| 1151 | |
| 1152 | |
| 1153 | def _deserialize_2m_relation(self, link, data, related_class): |
Jakob Juelich | 116ff0f | 2014-09-17 18:25:16 -0700 | [diff] [blame] | 1154 | """Deserialize related objects for one to-many relationship. |
| 1155 | |
| 1156 | @param link: Name of the relation. |
| 1157 | @param data: Serialized representation of the related objects. |
| 1158 | This is a list with of dictionaries. |
| 1159 | """ |
Jakob Juelich | f88fa93 | 2014-09-03 17:58:04 -0700 | [diff] [blame] | 1160 | relation_set = getattr(self, link) |
| 1161 | for serialized in data: |
| 1162 | relation_set.add(related_class.deserialize(serialized)) |
| 1163 | |
| 1164 | |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 1165 | class ModelWithInvalid(ModelExtensions): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 1166 | """ |
| 1167 | Overrides model methods save() and delete() to support invalidation in |
| 1168 | place of actual deletion. Subclasses must have a boolean "invalid" |
| 1169 | field. |
| 1170 | """ |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 1171 | |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 1172 | def save(self, *args, **kwargs): |
showard | ddb9099 | 2009-02-11 23:39:32 +0000 | [diff] [blame] | 1173 | first_time = (self.id is None) |
| 1174 | if first_time: |
| 1175 | # see if this object was previously added and invalidated |
| 1176 | my_name = getattr(self, self.name_field) |
| 1177 | filters = {self.name_field : my_name, 'invalid' : True} |
| 1178 | try: |
| 1179 | old_object = self.__class__.objects.get(**filters) |
showard | afd97de | 2009-10-01 18:45:09 +0000 | [diff] [blame] | 1180 | self.resurrect_object(old_object) |
showard | ddb9099 | 2009-02-11 23:39:32 +0000 | [diff] [blame] | 1181 | except self.DoesNotExist: |
| 1182 | # no existing object |
| 1183 | pass |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 1184 | |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 1185 | super(ModelWithInvalid, self).save(*args, **kwargs) |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 1186 | |
| 1187 | |
showard | afd97de | 2009-10-01 18:45:09 +0000 | [diff] [blame] | 1188 | def resurrect_object(self, old_object): |
| 1189 | """ |
| 1190 | Called when self is about to be saved for the first time and is actually |
| 1191 | "undeleting" a previously deleted object. Can be overridden by |
| 1192 | subclasses to copy data as desired from the deleted entry (but this |
| 1193 | superclass implementation must normally be called). |
| 1194 | """ |
| 1195 | self.id = old_object.id |
| 1196 | |
| 1197 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 1198 | def clean_object(self): |
| 1199 | """ |
| 1200 | This method is called when an object is marked invalid. |
| 1201 | Subclasses should override this to clean up relationships that |
showard | afd97de | 2009-10-01 18:45:09 +0000 | [diff] [blame] | 1202 | should no longer exist if the object were deleted. |
| 1203 | """ |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 1204 | pass |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 1205 | |
| 1206 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 1207 | def delete(self): |
Dale Curtis | 74a314b | 2011-06-23 14:55:46 -0700 | [diff] [blame] | 1208 | self.invalid = self.invalid |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 1209 | assert not self.invalid |
| 1210 | self.invalid = True |
| 1211 | self.save() |
| 1212 | self.clean_object() |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 1213 | |
| 1214 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 1215 | @classmethod |
| 1216 | def get_valid_manager(cls): |
| 1217 | return cls.valid_objects |
showard | 7c78528 | 2008-05-29 19:45:12 +0000 | [diff] [blame] | 1218 | |
| 1219 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 1220 | class Manipulator(object): |
| 1221 | """ |
| 1222 | Force default manipulators to look only at valid objects - |
| 1223 | otherwise they will match against invalid objects when checking |
| 1224 | uniqueness. |
| 1225 | """ |
| 1226 | @classmethod |
| 1227 | def _prepare(cls, model): |
| 1228 | super(ModelWithInvalid.Manipulator, cls)._prepare(model) |
| 1229 | cls.manager = model.valid_objects |
showard | f8b1904 | 2009-05-12 17:22:49 +0000 | [diff] [blame] | 1230 | |
| 1231 | |
| 1232 | class ModelWithAttributes(object): |
| 1233 | """ |
| 1234 | Mixin class for models that have an attribute model associated with them. |
| 1235 | The attribute model is assumed to have its value field named "value". |
| 1236 | """ |
| 1237 | |
| 1238 | def _get_attribute_model_and_args(self, attribute): |
| 1239 | """ |
| 1240 | Subclasses should override this to return a tuple (attribute_model, |
| 1241 | keyword_args), where attribute_model is a model class and keyword_args |
| 1242 | is a dict of args to pass to attribute_model.objects.get() to get an |
| 1243 | instance of the given attribute on this object. |
| 1244 | """ |
Dale Curtis | 74a314b | 2011-06-23 14:55:46 -0700 | [diff] [blame] | 1245 | raise NotImplementedError |
showard | f8b1904 | 2009-05-12 17:22:49 +0000 | [diff] [blame] | 1246 | |
| 1247 | |
| 1248 | def set_attribute(self, attribute, value): |
| 1249 | attribute_model, get_args = self._get_attribute_model_and_args( |
| 1250 | attribute) |
| 1251 | attribute_object, _ = attribute_model.objects.get_or_create(**get_args) |
| 1252 | attribute_object.value = value |
| 1253 | attribute_object.save() |
| 1254 | |
| 1255 | |
| 1256 | def delete_attribute(self, attribute): |
| 1257 | attribute_model, get_args = self._get_attribute_model_and_args( |
| 1258 | attribute) |
| 1259 | try: |
| 1260 | attribute_model.objects.get(**get_args).delete() |
showard | 1624542 | 2009-09-08 16:28:15 +0000 | [diff] [blame] | 1261 | except attribute_model.DoesNotExist: |
showard | f8b1904 | 2009-05-12 17:22:49 +0000 | [diff] [blame] | 1262 | pass |
| 1263 | |
| 1264 | |
| 1265 | def set_or_delete_attribute(self, attribute, value): |
| 1266 | if value is None: |
| 1267 | self.delete_attribute(attribute) |
| 1268 | else: |
| 1269 | self.set_attribute(attribute, value) |
showard | 26b7ec7 | 2009-12-21 22:43:57 +0000 | [diff] [blame] | 1270 | |
| 1271 | |
| 1272 | class ModelWithHashManager(dbmodels.Manager): |
| 1273 | """Manager for use with the ModelWithHash abstract model class""" |
| 1274 | |
| 1275 | def create(self, **kwargs): |
| 1276 | raise Exception('ModelWithHash manager should use get_or_create() ' |
| 1277 | 'instead of create()') |
| 1278 | |
| 1279 | |
| 1280 | def get_or_create(self, **kwargs): |
| 1281 | kwargs['the_hash'] = self.model._compute_hash(**kwargs) |
| 1282 | return super(ModelWithHashManager, self).get_or_create(**kwargs) |
| 1283 | |
| 1284 | |
| 1285 | class ModelWithHash(dbmodels.Model): |
| 1286 | """Superclass with methods for dealing with a hash column""" |
| 1287 | |
| 1288 | the_hash = dbmodels.CharField(max_length=40, unique=True) |
| 1289 | |
| 1290 | objects = ModelWithHashManager() |
| 1291 | |
| 1292 | class Meta: |
| 1293 | abstract = True |
| 1294 | |
| 1295 | |
| 1296 | @classmethod |
| 1297 | def _compute_hash(cls, **kwargs): |
| 1298 | raise NotImplementedError('Subclasses must override _compute_hash()') |
| 1299 | |
| 1300 | |
| 1301 | def save(self, force_insert=False, **kwargs): |
| 1302 | """Prevents saving the model in most cases |
| 1303 | |
| 1304 | We want these models to be immutable, so the generic save() operation |
| 1305 | will not work. These models should be instantiated through their the |
| 1306 | model.objects.get_or_create() method instead. |
| 1307 | |
| 1308 | The exception is that save(force_insert=True) will be allowed, since |
| 1309 | that creates a new row. However, the preferred way to make instances of |
| 1310 | these models is through the get_or_create() method. |
| 1311 | """ |
| 1312 | if not force_insert: |
| 1313 | # Allow a forced insert to happen; if it's a duplicate, the unique |
| 1314 | # constraint will catch it later anyways |
| 1315 | raise Exception('ModelWithHash is immutable') |
| 1316 | super(ModelWithHash, self).save(force_insert=force_insert, **kwargs) |