Add index=True for some columns.
[mediagoblin.git] / mediagoblin / db / sql / models.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """
18 TODO: indexes on foreignkeys, where useful.
19 """
20
21
22 import datetime
23 import sys
24
25 from sqlalchemy import (
26 Column, Integer, Unicode, UnicodeText, DateTime, Boolean, ForeignKey,
27 UniqueConstraint, PrimaryKeyConstraint, SmallInteger)
28 from sqlalchemy.orm import relationship
29 from sqlalchemy.orm.collections import attribute_mapped_collection
30 from sqlalchemy.sql.expression import desc
31 from sqlalchemy.ext.associationproxy import association_proxy
32 from sqlalchemy.util import memoized_property
33
34 from mediagoblin.db.sql.extratypes import PathTupleWithSlashes, JSONEncoded
35 from mediagoblin.db.sql.base import Base, DictReadAttrProxy
36 from mediagoblin.db.mixin import UserMixin, MediaEntryMixin, MediaCommentMixin
37 from mediagoblin.db.sql.base import Session
38
39 # It's actually kind of annoying how sqlalchemy-migrate does this, if
40 # I understand it right, but whatever. Anyway, don't remove this :P
41 #
42 # We could do migration calls more manually instead of relying on
43 # this import-based meddling...
44 from migrate import changeset
45
46
47 class SimpleFieldAlias(object):
48 """An alias for any field"""
49 def __init__(self, fieldname):
50 self.fieldname = fieldname
51
52 def __get__(self, instance, cls):
53 return getattr(instance, self.fieldname)
54
55 def __set__(self, instance, val):
56 setattr(instance, self.fieldname, val)
57
58
59 class User(Base, UserMixin):
60 """
61 TODO: We should consider moving some rarely used fields
62 into some sort of "shadow" table.
63 """
64 __tablename__ = "core__users"
65
66 id = Column(Integer, primary_key=True)
67 username = Column(Unicode, nullable=False, unique=True)
68 email = Column(Unicode, nullable=False)
69 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
70 pw_hash = Column(Unicode, nullable=False)
71 email_verified = Column(Boolean, default=False)
72 status = Column(Unicode, default=u"needs_email_verification", nullable=False)
73 verification_key = Column(Unicode)
74 is_admin = Column(Boolean, default=False, nullable=False)
75 url = Column(Unicode)
76 bio = Column(UnicodeText) # ??
77 fp_verification_key = Column(Unicode)
78 fp_token_expire = Column(DateTime)
79
80 ## TODO
81 # plugin data would be in a separate model
82
83 _id = SimpleFieldAlias("id")
84
85
86 class MediaEntry(Base, MediaEntryMixin):
87 """
88 TODO: Consider fetching the media_files using join
89 """
90 __tablename__ = "core__media_entries"
91
92 id = Column(Integer, primary_key=True)
93 uploader = Column(Integer, ForeignKey(User.id), nullable=False, index=True)
94 title = Column(Unicode, nullable=False)
95 slug = Column(Unicode)
96 created = Column(DateTime, nullable=False, default=datetime.datetime.now,
97 index=True)
98 description = Column(UnicodeText) # ??
99 media_type = Column(Unicode, nullable=False)
100 state = Column(Unicode, default=u'unprocessed', nullable=False)
101 # or use sqlalchemy.types.Enum?
102 license = Column(Unicode)
103
104 fail_error = Column(Unicode)
105 fail_metadata = Column(JSONEncoded)
106
107 queued_media_file = Column(PathTupleWithSlashes)
108
109 queued_task_id = Column(Unicode)
110
111 __table_args__ = (
112 UniqueConstraint('uploader', 'slug'),
113 {})
114
115 get_uploader = relationship(User)
116
117 media_files_helper = relationship("MediaFile",
118 collection_class=attribute_mapped_collection("name"),
119 cascade="all, delete-orphan"
120 )
121 media_files = association_proxy('media_files_helper', 'file_path',
122 creator=lambda k, v: MediaFile(name=k, file_path=v)
123 )
124
125 attachment_files_helper = relationship("MediaAttachmentFile",
126 cascade="all, delete-orphan",
127 order_by="MediaAttachmentFile.created"
128 )
129 attachment_files = association_proxy("attachment_files_helper", "dict_view",
130 creator=lambda v: MediaAttachmentFile(
131 name=v["name"], filepath=v["filepath"])
132 )
133
134 tags_helper = relationship("MediaTag",
135 cascade="all, delete-orphan"
136 )
137 tags = association_proxy("tags_helper", "dict_view",
138 creator=lambda v: MediaTag(name=v["name"], slug=v["slug"])
139 )
140
141 ## TODO
142 # media_data
143 # fail_error
144
145 _id = SimpleFieldAlias("id")
146
147 def get_comments(self, ascending=False):
148 order_col = MediaComment.created
149 if not ascending:
150 order_col = desc(order_col)
151 return MediaComment.query.filter_by(
152 media_entry=self.id).order_by(order_col)
153
154 def url_to_prev(self, urlgen):
155 """get the next 'newer' entry by this user"""
156 media = MediaEntry.query.filter(
157 (MediaEntry.uploader == self.uploader)
158 & (MediaEntry.state == 'processed')
159 & (MediaEntry.id > self.id)).order_by(MediaEntry.id).first()
160
161 if media is not None:
162 return media.url_for_self(urlgen)
163
164 def url_to_next(self, urlgen):
165 """get the next 'older' entry by this user"""
166 media = MediaEntry.query.filter(
167 (MediaEntry.uploader == self.uploader)
168 & (MediaEntry.state == 'processed')
169 & (MediaEntry.id < self.id)).order_by(desc(MediaEntry.id)).first()
170
171 if media is not None:
172 return media.url_for_self(urlgen)
173
174 #@memoized_property
175 @property
176 def media_data(self):
177 session = Session()
178
179 return session.query(self.media_data_table).filter_by(
180 media_entry=self.id).first()
181
182 def media_data_init(self, **kwargs):
183 """
184 Initialize or update the contents of a media entry's media_data row
185 """
186 session = Session()
187
188 media_data = session.query(self.media_data_table).filter_by(
189 media_entry=self.id).first()
190
191 # No media data, so actually add a new one
192 if not media_data:
193 media_data = self.media_data_table(
194 **kwargs)
195 session.add(media_data)
196 # Update old media data
197 else:
198 for field, value in kwargs.iteritems():
199 setattr(media_data, field, value)
200
201 @memoized_property
202 def media_data_table(self):
203 # TODO: memoize this
204 models_module = self.media_type + '.models'
205 __import__(models_module)
206 return sys.modules[models_module].DATA_MODEL
207
208
209 class FileKeynames(Base):
210 """
211 keywords for various places.
212 currently the MediaFile keys
213 """
214 __tablename__ = "core__file_keynames"
215 id = Column(Integer, primary_key=True)
216 name = Column(Unicode, unique=True)
217
218 def __repr__(self):
219 return "<FileKeyname %r: %r>" % (self.id, self.name)
220
221 @classmethod
222 def find_or_new(cls, name):
223 t = cls.query.filter_by(name=name).first()
224 if t is not None:
225 return t
226 return cls(name=name)
227
228
229 class MediaFile(Base):
230 """
231 TODO: Highly consider moving "name" into a new table.
232 TODO: Consider preloading said table in software
233 """
234 __tablename__ = "core__mediafiles"
235
236 media_entry = Column(
237 Integer, ForeignKey(MediaEntry.id),
238 nullable=False)
239 name_id = Column(SmallInteger, ForeignKey(FileKeynames.id), nullable=False)
240 file_path = Column(PathTupleWithSlashes)
241
242 __table_args__ = (
243 PrimaryKeyConstraint('media_entry', 'name_id'),
244 {})
245
246 def __repr__(self):
247 return "<MediaFile %s: %r>" % (self.name, self.file_path)
248
249 name_helper = relationship(FileKeynames, lazy="joined", innerjoin=True)
250 name = association_proxy('name_helper', 'name',
251 creator=FileKeynames.find_or_new
252 )
253
254
255 class MediaAttachmentFile(Base):
256 __tablename__ = "core__attachment_files"
257
258 id = Column(Integer, primary_key=True)
259 media_entry = Column(
260 Integer, ForeignKey(MediaEntry.id),
261 nullable=False)
262 name = Column(Unicode, nullable=False)
263 filepath = Column(PathTupleWithSlashes)
264 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
265
266 @property
267 def dict_view(self):
268 """A dict like view on this object"""
269 return DictReadAttrProxy(self)
270
271
272 class Tag(Base):
273 __tablename__ = "core__tags"
274
275 id = Column(Integer, primary_key=True)
276 slug = Column(Unicode, nullable=False, unique=True)
277
278 def __repr__(self):
279 return "<Tag %r: %r>" % (self.id, self.slug)
280
281 @classmethod
282 def find_or_new(cls, slug):
283 t = cls.query.filter_by(slug=slug).first()
284 if t is not None:
285 return t
286 return cls(slug=slug)
287
288
289 class MediaTag(Base):
290 __tablename__ = "core__media_tags"
291
292 id = Column(Integer, primary_key=True)
293 media_entry = Column(
294 Integer, ForeignKey(MediaEntry.id),
295 nullable=False, index=True)
296 tag = Column(Integer, ForeignKey(Tag.id), nullable=False, index=True)
297 name = Column(Unicode)
298 # created = Column(DateTime, nullable=False, default=datetime.datetime.now)
299
300 __table_args__ = (
301 UniqueConstraint('tag', 'media_entry'),
302 {})
303
304 tag_helper = relationship(Tag)
305 slug = association_proxy('tag_helper', 'slug',
306 creator=Tag.find_or_new
307 )
308
309 def __init__(self, name=None, slug=None):
310 Base.__init__(self)
311 if name is not None:
312 self.name = name
313 if slug is not None:
314 self.tag_helper = Tag.find_or_new(slug)
315
316 @property
317 def dict_view(self):
318 """A dict like view on this object"""
319 return DictReadAttrProxy(self)
320
321
322 class MediaComment(Base, MediaCommentMixin):
323 __tablename__ = "core__media_comments"
324
325 id = Column(Integer, primary_key=True)
326 media_entry = Column(
327 Integer, ForeignKey(MediaEntry.id), nullable=False, index=True)
328 author = Column(Integer, ForeignKey(User.id), nullable=False)
329 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
330 content = Column(UnicodeText, nullable=False)
331
332 get_author = relationship(User)
333
334 _id = SimpleFieldAlias("id")
335
336
337 MODELS = [
338 User, MediaEntry, Tag, MediaTag, MediaComment, MediaFile, FileKeynames,
339 MediaAttachmentFile]
340
341
342 ######################################################
343 # Special, migrations-tracking table
344 #
345 # Not listed in MODELS because this is special and not
346 # really migrated, but used for migrations (for now)
347 ######################################################
348
349 class MigrationData(Base):
350 __tablename__ = "core__migrations"
351
352 name = Column(Unicode, primary_key=True)
353 version = Column(Integer, nullable=False, default=0)
354
355 ######################################################
356
357
358 def show_table_init(engine_uri):
359 if engine_uri is None:
360 engine_uri = 'sqlite:///:memory:'
361 from sqlalchemy import create_engine
362 engine = create_engine(engine_uri, echo=True)
363
364 Base.metadata.create_all(engine)
365
366
367 if __name__ == '__main__':
368 from sys import argv
369 print repr(argv)
370 if len(argv) == 2:
371 uri = argv[1]
372 else:
373 uri = None
374 show_table_init(uri)