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