Debian Codegraph @

oslo_db/sqlalchemy/models.py

raw symbols SCIP
1 # Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
2 # Copyright 2010 United States Government as represented by the
3 # Administrator of the National Aeronautics and Space Administration.
4 # Copyright 2011 Piston Cloud Computing, Inc.
5 # Copyright 2012 Cloudscaling Group, Inc.
6 # All Rights Reserved.
7 #
8 # Licensed under the Apache License, Version 2.0 (the "License"); you may
9 # not use this file except in compliance with the License. You may obtain
10 # a copy of the License at
11 #
12 # http://www.apache.org/licenses/LICENSE-2.0
13 #
14 # Unless required by applicable law or agreed to in writing, software
15 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 # License for the specific language governing permissions and limitations
18 # under the License.
19 """
20 SQLAlchemy models.
21 """
22
23 import debtcollector.removals
24 from oslo_utils import timeutils
25 from sqlalchemy import Column
26 from sqlalchemy import DateTime
27 from sqlalchemy.orm import object_mapper
28
29 from oslo_db.sqlalchemy import types
30
31
32 class ModelBase:
33 """Base class for models."""
34 __table_initialized__ = False
35
36 def save(self, session):
37 """Save this object."""
38 session.add(self)
39 session.flush()
40
41 def __setitem__(self, key, value):
42 setattr(self, key, value)
43
44 def __getitem__(self, key):
45 return getattr(self, key)
46
47 def __contains__(self, key):
48 # Don't use hasattr() because hasattr() catches any exception, not only
49 # AttributeError. We want to passthrough SQLAlchemy exceptions
50 # (ex: sqlalchemy.orm.exc.DetachedInstanceError).
51 try:
52 getattr(self, key)
53 except AttributeError:
54 return False
55 else:
56 return True
57
58 def get(self, key, default=None):
59 return getattr(self, key, default)
60
61 @property
62 def _extra_keys(self):
63 """Specifies custom fields
64
65 Subclasses can override this property to return a list
66 of custom fields that should be included in their dict
67 representation.
68
69 For reference check tests/db/sqlalchemy/test_models.py
70 """
71 return []
72
73 def __iter__(self):
74 columns = list(dict(object_mapper(self).columns).keys())
75 # NOTE(russellb): Allow models to specify other keys that can be looked
76 # up, beyond the actual db columns. An example would be the 'name'
77 # property for an Instance.
78 columns.extend(self._extra_keys)
79
80 return ModelIterator(self, iter(columns))
81
82 def update(self, values):
83 """Make the model object behave like a dict."""
84 for k, v in values.items():
85 setattr(self, k, v)
86
87 def _as_dict(self):
88 """Make the model object behave like a dict.
89
90 Includes attributes from joins.
91 """
92 local = {key: value for key, value in self}
93 joined = {k: v for k, v in self.__dict__.items() if not k[0] == '_'}
94 local.update(joined)
95 return local
96
97 @debtcollector.removals.remove(
98 message='This method is deprecated in favor of the items() method',
99 version='17.1.0'
100 )
101 def iteritems(self):
102 """Make the model object behave like a dict."""
103 return self._as_dict().items()
104
105 def items(self):
106 """Make the model object behave like a dict."""
107 return self._as_dict().items()
108
109 def keys(self):
110 """Make the model object behave like a dict."""
111 return [key for key, value in self.items()]
112
113
114 class ModelIterator:
115
116 def __init__(self, model, columns):
117 self.model = model
118 self.i = columns
119
120 def __iter__(self):
121 return self
122
123 def __next__(self):
124 n = next(self.i)
125 return n, getattr(self.model, n)
126
127
128 class TimestampMixin:
129 created_at = Column(DateTime, default=lambda: timeutils.utcnow())
130 updated_at = Column(DateTime, onupdate=lambda: timeutils.utcnow())
131
132
133 class SoftDeleteMixin:
134 deleted_at = Column(DateTime)
135 deleted = Column(types.SoftDeleteInteger, default=0)
136
137 def soft_delete(self, session):
138 """Mark this object as deleted."""
139 self.deleted = self.id
140 self.deleted_at = timeutils.utcnow()
141 self.save(session=session)