remove a blank line
[mediagoblin.git] / mediagoblin / db / 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 import logging
22 import datetime
23
24 from sqlalchemy import Column, Integer, Unicode, UnicodeText, DateTime, \
25 Boolean, ForeignKey, UniqueConstraint, PrimaryKeyConstraint, \
26 SmallInteger
27 from sqlalchemy.orm import relationship, backref, with_polymorphic
28 from sqlalchemy.orm.collections import attribute_mapped_collection
29 from sqlalchemy.sql.expression import desc
30 from sqlalchemy.ext.associationproxy import association_proxy
31 from sqlalchemy.util import memoized_property
32
33 from mediagoblin.db.extratypes import (PathTupleWithSlashes, JSONEncoded,
34 MutationDict)
35 from mediagoblin.db.base import Base, DictReadAttrProxy
36 from mediagoblin.db.mixin import UserMixin, MediaEntryMixin, \
37 MediaCommentMixin, CollectionMixin, CollectionItemMixin
38 from mediagoblin.tools.files import delete_media_files
39 from mediagoblin.tools.common import import_component
40
41 # It's actually kind of annoying how sqlalchemy-migrate does this, if
42 # I understand it right, but whatever. Anyway, don't remove this :P
43 #
44 # We could do migration calls more manually instead of relying on
45 # this import-based meddling...
46 from migrate import changeset
47
48 _log = logging.getLogger(__name__)
49
50
51
52 class User(Base, UserMixin):
53 """
54 TODO: We should consider moving some rarely used fields
55 into some sort of "shadow" table.
56 """
57 __tablename__ = "core__users"
58
59 id = Column(Integer, primary_key=True)
60 username = Column(Unicode, nullable=False, unique=True)
61 # Note: no db uniqueness constraint on email because it's not
62 # reliable (many email systems case insensitive despite against
63 # the RFC) and because it would be a mess to implement at this
64 # point.
65 email = Column(Unicode, nullable=False)
66 pw_hash = Column(Unicode)
67 email_verified = Column(Boolean, default=False)
68 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
69 status = Column(Unicode, default=u"needs_email_verification", nullable=False)
70 # Intented to be nullable=False, but migrations would not work for it
71 # set to nullable=True implicitly.
72 wants_comment_notification = Column(Boolean, default=True)
73 wants_notifications = Column(Boolean, default=True)
74 license_preference = Column(Unicode)
75 is_admin = Column(Boolean, default=False, nullable=False)
76 url = Column(Unicode)
77 bio = Column(UnicodeText) # ??
78 uploaded = Column(Integer, default=0)
79 upload_limit = Column(Integer)
80
81 ## TODO
82 # plugin data would be in a separate model
83
84 def __repr__(self):
85 return '<{0} #{1} {2} {3} "{4}">'.format(
86 self.__class__.__name__,
87 self.id,
88 'verified' if self.email_verified else 'non-verified',
89 'admin' if self.is_admin else 'user',
90 self.username)
91
92 def delete(self, **kwargs):
93 """Deletes a User and all related entries/comments/files/..."""
94 # Collections get deleted by relationships.
95
96 media_entries = MediaEntry.query.filter(MediaEntry.uploader == self.id)
97 for media in media_entries:
98 # TODO: Make sure that "MediaEntry.delete()" also deletes
99 # all related files/Comments
100 media.delete(del_orphan_tags=False, commit=False)
101
102 # Delete now unused tags
103 # TODO: import here due to cyclic imports!!! This cries for refactoring
104 from mediagoblin.db.util import clean_orphan_tags
105 clean_orphan_tags(commit=False)
106
107 # Delete user, pass through commit=False/True in kwargs
108 super(User, self).delete(**kwargs)
109 _log.info('Deleted user "{0}" account'.format(self.username))
110
111
112 class Client(Base):
113 """
114 Model representing a client - Used for API Auth
115 """
116 __tablename__ = "core__clients"
117
118 id = Column(Unicode, nullable=True, primary_key=True)
119 secret = Column(Unicode, nullable=False)
120 expirey = Column(DateTime, nullable=True)
121 application_type = Column(Unicode, nullable=False)
122 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
123 updated = Column(DateTime, nullable=False, default=datetime.datetime.now)
124
125 # optional stuff
126 redirect_uri = Column(JSONEncoded, nullable=True)
127 logo_url = Column(Unicode, nullable=True)
128 application_name = Column(Unicode, nullable=True)
129 contacts = Column(JSONEncoded, nullable=True)
130
131 def __repr__(self):
132 if self.application_name:
133 return "<Client {0} - {1}>".format(self.application_name, self.id)
134 else:
135 return "<Client {0}>".format(self.id)
136
137 class RequestToken(Base):
138 """
139 Model for representing the request tokens
140 """
141 __tablename__ = "core__request_tokens"
142
143 token = Column(Unicode, primary_key=True)
144 secret = Column(Unicode, nullable=False)
145 client = Column(Unicode, ForeignKey(Client.id))
146 user = Column(Integer, ForeignKey(User.id), nullable=True)
147 used = Column(Boolean, default=False)
148 authenticated = Column(Boolean, default=False)
149 verifier = Column(Unicode, nullable=True)
150 callback = Column(Unicode, nullable=False, default=u"oob")
151 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
152 updated = Column(DateTime, nullable=False, default=datetime.datetime.now)
153
154 class AccessToken(Base):
155 """
156 Model for representing the access tokens
157 """
158 __tablename__ = "core__access_tokens"
159
160 token = Column(Unicode, nullable=False, primary_key=True)
161 secret = Column(Unicode, nullable=False)
162 user = Column(Integer, ForeignKey(User.id))
163 request_token = Column(Unicode, ForeignKey(RequestToken.token))
164 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
165 updated = Column(DateTime, nullable=False, default=datetime.datetime.now)
166
167
168 class NonceTimestamp(Base):
169 """
170 A place the timestamp and nonce can be stored - this is for OAuth1
171 """
172 __tablename__ = "core__nonce_timestamps"
173
174 nonce = Column(Unicode, nullable=False, primary_key=True)
175 timestamp = Column(DateTime, nullable=False, primary_key=True)
176
177
178 class MediaEntry(Base, MediaEntryMixin):
179 """
180 TODO: Consider fetching the media_files using join
181 """
182 __tablename__ = "core__media_entries"
183
184 id = Column(Integer, primary_key=True)
185 uploader = Column(Integer, ForeignKey(User.id), nullable=False, index=True)
186 title = Column(Unicode, nullable=False)
187 slug = Column(Unicode)
188 created = Column(DateTime, nullable=False, default=datetime.datetime.now,
189 index=True)
190 description = Column(UnicodeText) # ??
191 media_type = Column(Unicode, nullable=False)
192 state = Column(Unicode, default=u'unprocessed', nullable=False)
193 # or use sqlalchemy.types.Enum?
194 license = Column(Unicode)
195 collected = Column(Integer, default=0)
196 file_size = Column(Integer, default=0)
197
198 fail_error = Column(Unicode)
199 fail_metadata = Column(JSONEncoded)
200
201 transcoding_progress = Column(SmallInteger)
202
203 queued_media_file = Column(PathTupleWithSlashes)
204
205 queued_task_id = Column(Unicode)
206
207 __table_args__ = (
208 UniqueConstraint('uploader', 'slug'),
209 {})
210
211 get_uploader = relationship(User)
212
213 media_files_helper = relationship("MediaFile",
214 collection_class=attribute_mapped_collection("name"),
215 cascade="all, delete-orphan"
216 )
217 media_files = association_proxy('media_files_helper', 'file_path',
218 creator=lambda k, v: MediaFile(name=k, file_path=v)
219 )
220
221 attachment_files_helper = relationship("MediaAttachmentFile",
222 cascade="all, delete-orphan",
223 order_by="MediaAttachmentFile.created"
224 )
225 attachment_files = association_proxy("attachment_files_helper", "dict_view",
226 creator=lambda v: MediaAttachmentFile(
227 name=v["name"], filepath=v["filepath"])
228 )
229
230 tags_helper = relationship("MediaTag",
231 cascade="all, delete-orphan" # should be automatically deleted
232 )
233 tags = association_proxy("tags_helper", "dict_view",
234 creator=lambda v: MediaTag(name=v["name"], slug=v["slug"])
235 )
236
237 collections_helper = relationship("CollectionItem",
238 cascade="all, delete-orphan"
239 )
240 collections = association_proxy("collections_helper", "in_collection")
241
242 ## TODO
243 # fail_error
244
245 def get_comments(self, ascending=False):
246 order_col = MediaComment.created
247 if not ascending:
248 order_col = desc(order_col)
249 return self.all_comments.order_by(order_col)
250
251 def url_to_prev(self, urlgen):
252 """get the next 'newer' entry by this user"""
253 media = MediaEntry.query.filter(
254 (MediaEntry.uploader == self.uploader)
255 & (MediaEntry.state == u'processed')
256 & (MediaEntry.id > self.id)).order_by(MediaEntry.id).first()
257
258 if media is not None:
259 return media.url_for_self(urlgen)
260
261 def url_to_next(self, urlgen):
262 """get the next 'older' entry by this user"""
263 media = MediaEntry.query.filter(
264 (MediaEntry.uploader == self.uploader)
265 & (MediaEntry.state == u'processed')
266 & (MediaEntry.id < self.id)).order_by(desc(MediaEntry.id)).first()
267
268 if media is not None:
269 return media.url_for_self(urlgen)
270
271 def get_file_metadata(self, file_key, metadata_key=None):
272 """
273 Return the file_metadata dict of a MediaFile. If metadata_key is given,
274 return the value of the key.
275 """
276 media_file = MediaFile.query.filter_by(media_entry=self.id,
277 name=unicode(file_key)).first()
278
279 if media_file:
280 if metadata_key:
281 return media_file.file_metadata.get(metadata_key, None)
282
283 return media_file.file_metadata
284
285 def set_file_metadata(self, file_key, **kwargs):
286 """
287 Update the file_metadata of a MediaFile.
288 """
289 media_file = MediaFile.query.filter_by(media_entry=self.id,
290 name=unicode(file_key)).first()
291
292 file_metadata = media_file.file_metadata or {}
293
294 for key, value in kwargs.iteritems():
295 file_metadata[key] = value
296
297 media_file.file_metadata = file_metadata
298 media_file.save()
299
300 @property
301 def media_data(self):
302 return getattr(self, self.media_data_ref)
303
304 def media_data_init(self, **kwargs):
305 """
306 Initialize or update the contents of a media entry's media_data row
307 """
308 media_data = self.media_data
309
310 if media_data is None:
311 # Get the correct table:
312 table = import_component(self.media_type + '.models:DATA_MODEL')
313 # No media data, so actually add a new one
314 media_data = table(**kwargs)
315 # Get the relationship set up.
316 media_data.get_media_entry = self
317 else:
318 # Update old media data
319 for field, value in kwargs.iteritems():
320 setattr(media_data, field, value)
321
322 @memoized_property
323 def media_data_ref(self):
324 return import_component(self.media_type + '.models:BACKREF_NAME')
325
326 def __repr__(self):
327 safe_title = self.title.encode('ascii', 'replace')
328
329 return '<{classname} {id}: {title}>'.format(
330 classname=self.__class__.__name__,
331 id=self.id,
332 title=safe_title)
333
334 def delete(self, del_orphan_tags=True, **kwargs):
335 """Delete MediaEntry and all related files/attachments/comments
336
337 This will *not* automatically delete unused collections, which
338 can remain empty...
339
340 :param del_orphan_tags: True/false if we delete unused Tags too
341 :param commit: True/False if this should end the db transaction"""
342 # User's CollectionItems are automatically deleted via "cascade".
343 # Comments on this Media are deleted by cascade, hopefully.
344
345 # Delete all related files/attachments
346 try:
347 delete_media_files(self)
348 except OSError, error:
349 # Returns list of files we failed to delete
350 _log.error('No such files from the user "{1}" to delete: '
351 '{0}'.format(str(error), self.get_uploader))
352 _log.info('Deleted Media entry id "{0}"'.format(self.id))
353 # Related MediaTag's are automatically cleaned, but we might
354 # want to clean out unused Tag's too.
355 if del_orphan_tags:
356 # TODO: Import here due to cyclic imports!!!
357 # This cries for refactoring
358 from mediagoblin.db.util import clean_orphan_tags
359 clean_orphan_tags(commit=False)
360 # pass through commit=False/True in kwargs
361 super(MediaEntry, self).delete(**kwargs)
362
363
364 class FileKeynames(Base):
365 """
366 keywords for various places.
367 currently the MediaFile keys
368 """
369 __tablename__ = "core__file_keynames"
370 id = Column(Integer, primary_key=True)
371 name = Column(Unicode, unique=True)
372
373 def __repr__(self):
374 return "<FileKeyname %r: %r>" % (self.id, self.name)
375
376 @classmethod
377 def find_or_new(cls, name):
378 t = cls.query.filter_by(name=name).first()
379 if t is not None:
380 return t
381 return cls(name=name)
382
383
384 class MediaFile(Base):
385 """
386 TODO: Highly consider moving "name" into a new table.
387 TODO: Consider preloading said table in software
388 """
389 __tablename__ = "core__mediafiles"
390
391 media_entry = Column(
392 Integer, ForeignKey(MediaEntry.id),
393 nullable=False)
394 name_id = Column(SmallInteger, ForeignKey(FileKeynames.id), nullable=False)
395 file_path = Column(PathTupleWithSlashes)
396 file_metadata = Column(MutationDict.as_mutable(JSONEncoded))
397
398 __table_args__ = (
399 PrimaryKeyConstraint('media_entry', 'name_id'),
400 {})
401
402 def __repr__(self):
403 return "<MediaFile %s: %r>" % (self.name, self.file_path)
404
405 name_helper = relationship(FileKeynames, lazy="joined", innerjoin=True)
406 name = association_proxy('name_helper', 'name',
407 creator=FileKeynames.find_or_new
408 )
409
410
411 class MediaAttachmentFile(Base):
412 __tablename__ = "core__attachment_files"
413
414 id = Column(Integer, primary_key=True)
415 media_entry = Column(
416 Integer, ForeignKey(MediaEntry.id),
417 nullable=False)
418 name = Column(Unicode, nullable=False)
419 filepath = Column(PathTupleWithSlashes)
420 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
421
422 @property
423 def dict_view(self):
424 """A dict like view on this object"""
425 return DictReadAttrProxy(self)
426
427
428 class Tag(Base):
429 __tablename__ = "core__tags"
430
431 id = Column(Integer, primary_key=True)
432 slug = Column(Unicode, nullable=False, unique=True)
433
434 def __repr__(self):
435 return "<Tag %r: %r>" % (self.id, self.slug)
436
437 @classmethod
438 def find_or_new(cls, slug):
439 t = cls.query.filter_by(slug=slug).first()
440 if t is not None:
441 return t
442 return cls(slug=slug)
443
444
445 class MediaTag(Base):
446 __tablename__ = "core__media_tags"
447
448 id = Column(Integer, primary_key=True)
449 media_entry = Column(
450 Integer, ForeignKey(MediaEntry.id),
451 nullable=False, index=True)
452 tag = Column(Integer, ForeignKey(Tag.id), nullable=False, index=True)
453 name = Column(Unicode)
454 # created = Column(DateTime, nullable=False, default=datetime.datetime.now)
455
456 __table_args__ = (
457 UniqueConstraint('tag', 'media_entry'),
458 {})
459
460 tag_helper = relationship(Tag)
461 slug = association_proxy('tag_helper', 'slug',
462 creator=Tag.find_or_new
463 )
464
465 def __init__(self, name=None, slug=None):
466 Base.__init__(self)
467 if name is not None:
468 self.name = name
469 if slug is not None:
470 self.tag_helper = Tag.find_or_new(slug)
471
472 @property
473 def dict_view(self):
474 """A dict like view on this object"""
475 return DictReadAttrProxy(self)
476
477
478 class MediaComment(Base, MediaCommentMixin):
479 __tablename__ = "core__media_comments"
480
481 id = Column(Integer, primary_key=True)
482 media_entry = Column(
483 Integer, ForeignKey(MediaEntry.id), nullable=False, index=True)
484 author = Column(Integer, ForeignKey(User.id), nullable=False)
485 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
486 content = Column(UnicodeText, nullable=False)
487
488 # Cascade: Comments are owned by their creator. So do the full thing.
489 # lazy=dynamic: People might post a *lot* of comments,
490 # so make the "posted_comments" a query-like thing.
491 get_author = relationship(User,
492 backref=backref("posted_comments",
493 lazy="dynamic",
494 cascade="all, delete-orphan"))
495 get_entry = relationship(MediaEntry,
496 backref=backref("comments",
497 lazy="dynamic",
498 cascade="all, delete-orphan"))
499
500 # Cascade: Comments are somewhat owned by their MediaEntry.
501 # So do the full thing.
502 # lazy=dynamic: MediaEntries might have many comments,
503 # so make the "all_comments" a query-like thing.
504 get_media_entry = relationship(MediaEntry,
505 backref=backref("all_comments",
506 lazy="dynamic",
507 cascade="all, delete-orphan"))
508
509
510 class Collection(Base, CollectionMixin):
511 """An 'album' or 'set' of media by a user.
512
513 On deletion, contained CollectionItems get automatically reaped via
514 SQL cascade"""
515 __tablename__ = "core__collections"
516
517 id = Column(Integer, primary_key=True)
518 title = Column(Unicode, nullable=False)
519 slug = Column(Unicode)
520 created = Column(DateTime, nullable=False, default=datetime.datetime.now,
521 index=True)
522 description = Column(UnicodeText)
523 creator = Column(Integer, ForeignKey(User.id), nullable=False)
524 # TODO: No of items in Collection. Badly named, can we migrate to num_items?
525 items = Column(Integer, default=0)
526
527 # Cascade: Collections are owned by their creator. So do the full thing.
528 get_creator = relationship(User,
529 backref=backref("collections",
530 cascade="all, delete-orphan"))
531
532 __table_args__ = (
533 UniqueConstraint('creator', 'slug'),
534 {})
535
536 def get_collection_items(self, ascending=False):
537 #TODO, is this still needed with self.collection_items being available?
538 order_col = CollectionItem.position
539 if not ascending:
540 order_col = desc(order_col)
541 return CollectionItem.query.filter_by(
542 collection=self.id).order_by(order_col)
543
544
545 class CollectionItem(Base, CollectionItemMixin):
546 __tablename__ = "core__collection_items"
547
548 id = Column(Integer, primary_key=True)
549 media_entry = Column(
550 Integer, ForeignKey(MediaEntry.id), nullable=False, index=True)
551 collection = Column(Integer, ForeignKey(Collection.id), nullable=False)
552 note = Column(UnicodeText, nullable=True)
553 added = Column(DateTime, nullable=False, default=datetime.datetime.now)
554 position = Column(Integer)
555
556 # Cascade: CollectionItems are owned by their Collection. So do the full thing.
557 in_collection = relationship(Collection,
558 backref=backref(
559 "collection_items",
560 cascade="all, delete-orphan"))
561
562 get_media_entry = relationship(MediaEntry)
563
564 __table_args__ = (
565 UniqueConstraint('collection', 'media_entry'),
566 {})
567
568 @property
569 def dict_view(self):
570 """A dict like view on this object"""
571 return DictReadAttrProxy(self)
572
573
574 class ProcessingMetaData(Base):
575 __tablename__ = 'core__processing_metadata'
576
577 id = Column(Integer, primary_key=True)
578 media_entry_id = Column(Integer, ForeignKey(MediaEntry.id), nullable=False,
579 index=True)
580 media_entry = relationship(MediaEntry,
581 backref=backref('processing_metadata',
582 cascade='all, delete-orphan'))
583 callback_url = Column(Unicode)
584
585 @property
586 def dict_view(self):
587 """A dict like view on this object"""
588 return DictReadAttrProxy(self)
589
590
591 class CommentSubscription(Base):
592 __tablename__ = 'core__comment_subscriptions'
593 id = Column(Integer, primary_key=True)
594
595 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
596
597 media_entry_id = Column(Integer, ForeignKey(MediaEntry.id), nullable=False)
598 media_entry = relationship(MediaEntry,
599 backref=backref('comment_subscriptions',
600 cascade='all, delete-orphan'))
601
602 user_id = Column(Integer, ForeignKey(User.id), nullable=False)
603 user = relationship(User,
604 backref=backref('comment_subscriptions',
605 cascade='all, delete-orphan'))
606
607 notify = Column(Boolean, nullable=False, default=True)
608 send_email = Column(Boolean, nullable=False, default=True)
609
610 def __repr__(self):
611 return ('<{classname} #{id}: {user} {media} notify: '
612 '{notify} email: {email}>').format(
613 id=self.id,
614 classname=self.__class__.__name__,
615 user=self.user,
616 media=self.media_entry,
617 notify=self.notify,
618 email=self.send_email)
619
620
621 class Notification(Base):
622 __tablename__ = 'core__notifications'
623 id = Column(Integer, primary_key=True)
624 type = Column(Unicode)
625
626 created = Column(DateTime, nullable=False, default=datetime.datetime.now)
627
628 user_id = Column(Integer, ForeignKey('core__users.id'), nullable=False,
629 index=True)
630 seen = Column(Boolean, default=lambda: False, index=True)
631 user = relationship(
632 User,
633 backref=backref('notifications', cascade='all, delete-orphan'))
634
635 __mapper_args__ = {
636 'polymorphic_identity': 'notification',
637 'polymorphic_on': type
638 }
639
640 def __repr__(self):
641 return '<{klass} #{id}: {user}: {subject} ({seen})>'.format(
642 id=self.id,
643 klass=self.__class__.__name__,
644 user=self.user,
645 subject=getattr(self, 'subject', None),
646 seen='unseen' if not self.seen else 'seen')
647
648
649 class CommentNotification(Notification):
650 __tablename__ = 'core__comment_notifications'
651 id = Column(Integer, ForeignKey(Notification.id), primary_key=True)
652
653 subject_id = Column(Integer, ForeignKey(MediaComment.id))
654 subject = relationship(
655 MediaComment,
656 backref=backref('comment_notifications', cascade='all, delete-orphan'))
657
658 __mapper_args__ = {
659 'polymorphic_identity': 'comment_notification'
660 }
661
662
663 class ProcessingNotification(Notification):
664 __tablename__ = 'core__processing_notifications'
665
666 id = Column(Integer, ForeignKey(Notification.id), primary_key=True)
667
668 subject_id = Column(Integer, ForeignKey(MediaEntry.id))
669 subject = relationship(
670 MediaEntry,
671 backref=backref('processing_notifications',
672 cascade='all, delete-orphan'))
673
674 __mapper_args__ = {
675 'polymorphic_identity': 'processing_notification'
676 }
677
678
679 with_polymorphic(
680 Notification,
681 [ProcessingNotification, CommentNotification])
682
683 MODELS = [
684 User, Client, RequestToken, AccessToken, NonceTimestamp, MediaEntry, Tag,
685 MediaTag, MediaComment, Collection, CollectionItem, MediaFile, FileKeynames,
686 MediaAttachmentFile, ProcessingMetaData, Notification, CommentNotification,
687 ProcessingNotification, CommentSubscription]
688
689 """
690 Foundations are the default rows that are created immediately after the tables
691 are initialized. Each entry to this dictionary should be in the format of:
692 ModelConstructorObject:List of Dictionaries
693 (Each Dictionary represents a row on the Table to be created, containing each
694 of the columns' names as a key string, and each of the columns' values as a
695 value)
696
697 ex. [NOTE THIS IS NOT BASED OFF OF OUR USER TABLE]
698 user_foundations = [{'name':u'Joanna', 'age':24},
699 {'name':u'Andrea', 'age':41}]
700
701 FOUNDATIONS = {User:user_foundations}
702 """
703 FOUNDATIONS = {}
704
705 ######################################################
706 # Special, migrations-tracking table
707 #
708 # Not listed in MODELS because this is special and not
709 # really migrated, but used for migrations (for now)
710 ######################################################
711
712 class MigrationData(Base):
713 __tablename__ = "core__migrations"
714
715 name = Column(Unicode, primary_key=True)
716 version = Column(Integer, nullable=False, default=0)
717
718 ######################################################
719
720
721 def show_table_init(engine_uri):
722 if engine_uri is None:
723 engine_uri = 'sqlite:///:memory:'
724 from sqlalchemy import create_engine
725 engine = create_engine(engine_uri, echo=True)
726
727 Base.metadata.create_all(engine)
728
729
730 if __name__ == '__main__':
731 from sys import argv
732 print repr(argv)
733 if len(argv) == 2:
734 uri = argv[1]
735 else:
736 uri = None
737 show_table_init(uri)