import changeset into sql models
[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 import datetime
19
20 from sqlalchemy import (
21 Column, Integer, Unicode, UnicodeText, DateTime, Boolean, ForeignKey,
22 UniqueConstraint)
23 from sqlalchemy.orm import relationship
24 from sqlalchemy.orm.collections import attribute_mapped_collection
25 from sqlalchemy.sql.expression import desc
26 from sqlalchemy.ext.associationproxy import association_proxy
27
28 from mediagoblin.db.sql.extratypes import PathTupleWithSlashes
29 from mediagoblin.db.sql.base import Base, DictReadAttrProxy
30 from mediagoblin.db.mixin import UserMixin, MediaEntryMixin
31
32 # It's actually kind of annoying how sqlalchemy-migrate does this, if
33 # I understand it right, but whatever. Anyway, don't remove this :P
34 #
35 # We could do migration calls more manually instead of relying on
36 # this import-based meddling...
37 from migrate import changeset
38
39
40 class SimpleFieldAlias(object):
41 """An alias for any field"""
42 def __init__(self, fieldname):
43 self.fieldname = fieldname
44
45 def __get__(self, instance, cls):
46 return getattr(instance, self.fieldname)
47
48 def __set__(self, instance, val):
49 setattr(instance, self.fieldname, val)
50
51
52 class User(Base, UserMixin):
53 __tablename__ = "users"
54
55 id = Column(Integer, primary_key=True)
56 username = Column(Unicode, nullable=False, unique=True)
57 email = Column(Unicode, nullable=False)
58 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
59 pw_hash = Column(Unicode, nullable=False)
60 email_verified = Column(Boolean)
61 status = Column(Unicode, default=u"needs_email_verification", nullable=False)
62 verification_key = Column(Unicode)
63 is_admin = Column(Boolean, default=False, nullable=False)
64 url = Column(Unicode)
65 bio = Column(UnicodeText) # ??
66 bio_html = Column(UnicodeText) # ??
67 fp_verification_key = Column(Unicode)
68 fp_token_expire = Column(DateTime)
69
70 ## TODO
71 # plugin data would be in a separate model
72
73 _id = SimpleFieldAlias("id")
74
75
76 class MediaEntry(Base, MediaEntryMixin):
77 __tablename__ = "media_entries"
78
79 id = Column(Integer, primary_key=True)
80 uploader = Column(Integer, ForeignKey('users.id'), nullable=False)
81 title = Column(Unicode, nullable=False)
82 slug = Column(Unicode)
83 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
84 description = Column(UnicodeText) # ??
85 description_html = Column(UnicodeText) # ??
86 media_type = Column(Unicode, nullable=False)
87 state = Column(Unicode, nullable=False) # or use sqlalchemy.types.Enum?
88 license = Column(Unicode)
89
90 fail_error = Column(Unicode)
91 fail_metadata = Column(UnicodeText)
92
93 queued_media_file = Column(PathTupleWithSlashes)
94
95 queued_task_id = Column(Unicode)
96
97 __table_args__ = (
98 UniqueConstraint('uploader', 'slug'),
99 {})
100
101 get_uploader = relationship(User)
102
103 media_files_helper = relationship("MediaFile",
104 collection_class=attribute_mapped_collection("name"),
105 cascade="all, delete-orphan"
106 )
107 media_files = association_proxy('media_files_helper', 'file_path',
108 creator=lambda k, v: MediaFile(name=k, file_path=v)
109 )
110
111 tags_helper = relationship("MediaTag",
112 cascade="all, delete-orphan"
113 )
114 tags = association_proxy("tags_helper", "dict_view",
115 creator=lambda v: MediaTag(name=v["name"], slug=v["slug"])
116 )
117
118 ## TODO
119 # media_data
120 # attachment_files
121 # fail_error
122
123 def get_comments(self, ascending=False):
124 order_col = MediaComment.created
125 if not ascending:
126 order_col = desc(order_col)
127 return MediaComment.query.filter_by(
128 media_entry=self.id).order_by(order_col)
129
130 def url_to_prev(self, urlgen):
131 """get the next 'newer' entry by this user"""
132 media = MediaEntry.query.filter(
133 (MediaEntry.uploader == self.uploader)
134 & (MediaEntry.state == 'processed')
135 & (MediaEntry.id > self.id)).order_by(MediaEntry.id).first()
136
137 if media is not None:
138 return media.url_for_self(urlgen)
139
140 def url_to_next(self, urlgen):
141 """get the next 'older' entry by this user"""
142 media = MediaEntry.query.filter(
143 (MediaEntry.uploader == self.uploader)
144 & (MediaEntry.state == 'processed')
145 & (MediaEntry.id < self.id)).order_by(desc(MediaEntry.id)).first()
146
147 if media is not None:
148 return media.url_for_self(urlgen)
149
150
151 class MediaFile(Base):
152 __tablename__ = "mediafiles"
153
154 media_entry = Column(
155 Integer, ForeignKey(MediaEntry.id),
156 nullable=False, primary_key=True)
157 name = Column(Unicode, primary_key=True)
158 file_path = Column(PathTupleWithSlashes)
159
160 def __repr__(self):
161 return "<MediaFile %s: %r>" % (self.name, self.file_path)
162
163
164 class Tag(Base):
165 __tablename__ = "tags"
166
167 id = Column(Integer, primary_key=True)
168 slug = Column(Unicode, nullable=False, unique=True)
169
170 def __repr__(self):
171 return "<Tag %r: %r>" % (self.id, self.slug)
172
173 @classmethod
174 def find_or_new(cls, slug):
175 t = cls.query.filter_by(slug=slug).first()
176 if t is not None:
177 return t
178 return cls(slug=slug)
179
180
181 class MediaTag(Base):
182 __tablename__ = "media_tags"
183
184 id = Column(Integer, primary_key=True)
185 media_entry = Column(
186 Integer, ForeignKey(MediaEntry.id),
187 nullable=False)
188 tag = Column(Integer, ForeignKey('tags.id'), nullable=False)
189 name = Column(Unicode)
190 # created = Column(DateTime, nullable=False, default=datetime.datetime.now)
191
192 __table_args__ = (
193 UniqueConstraint('tag', 'media_entry'),
194 {})
195
196 tag_helper = relationship(Tag)
197 slug = association_proxy('tag_helper', 'slug',
198 creator=Tag.find_or_new
199 )
200
201 def __init__(self, name, slug):
202 Base.__init__(self)
203 self.name = name
204 self.tag_helper = Tag.find_or_new(slug)
205
206 @property
207 def dict_view(self):
208 """A dict like view on this object"""
209 return DictReadAttrProxy(self)
210
211
212 class MediaComment(Base):
213 __tablename__ = "media_comments"
214
215 id = Column(Integer, primary_key=True)
216 media_entry = Column(
217 Integer, ForeignKey('media_entries.id'), nullable=False)
218 author = Column(Integer, ForeignKey('users.id'), nullable=False)
219 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
220 content = Column(UnicodeText, nullable=False)
221 content_html = Column(UnicodeText)
222
223 get_author = relationship(User)
224
225
226 MODELS = [
227 User, MediaEntry, Tag, MediaTag, MediaComment]
228
229
230 ######################################################
231 # Special, migrations-tracking table
232 #
233 # Not listed in MODELS because this is special and not
234 # really migrated, but used for migrations (for now)
235 ######################################################
236
237 class MigrationData(Base):
238 __tablename__ = "migrations"
239
240 name = Column(Unicode, primary_key=True)
241 version = Column(Integer, nullable=False, default=0)
242
243 ######################################################
244
245
246 def show_table_init():
247 from sqlalchemy import create_engine
248 engine = create_engine('sqlite:///:memory:', echo=True)
249
250 Base.metadata.create_all(engine)
251
252
253 if __name__ == '__main__':
254 show_table_init()