1 from datetime
import datetime
3 from sqlalchemy
import and_
, Column
, ForeignKey
, Index
4 from sqlalchemy
.orm
import relation
5 from sqlalchemy
.types
import DateTime
, Integer
, Unicode
7 from spline
.model
.meta
import TableBase
8 from splinext
.users
import model
as users_model
13 class Forum(TableBase
):
14 __tablename__
= 'forums'
15 id = Column(Integer
, primary_key
=True, autoincrement
=True, nullable
=False)
16 name
= Column(Unicode(133), nullable
=False)
18 class Thread(TableBase
):
19 __tablename__
= 'threads'
20 id = Column(Integer
, primary_key
=True, autoincrement
=True, nullable
=False)
21 forum_id
= Column(Integer
, ForeignKey('forums.id'), nullable
=False)
22 icon
= Column(Unicode(32), nullable
=True)
23 subject
= Column(Unicode(133), nullable
=False)
24 post_count
= Column(Integer
, nullable
=False, default
=0, index
=True)
26 def specific_post(self
, position
):
27 """Returns post number `position` in this thread.
29 Positions are one-indexed. Negative indexes are allowed.
32 # Handle negative indexes
34 position
= self
.post_count
+ position
+ 1
36 return self
.posts
.filter_by(position
=position
).one()
38 class Post(TableBase
):
39 __tablename__
= 'posts'
40 id = Column(Integer
, primary_key
=True, autoincrement
=True, nullable
=False)
41 thread_id
= Column(Integer
, ForeignKey('threads.id'), nullable
=False)
42 position
= Column(Integer
, nullable
=False)
43 author_user_id
= Column(Integer
, ForeignKey('users.id'), nullable
=False)
44 posted_time
= Column(DateTime
, nullable
=False, index
=True, default
=datetime
.now
)
45 content
= Column(Unicode(5120), nullable
=False)
47 Index('thread_position', Post
.thread_id
, Post
.position
, unique
=True)
50 # XXX sort by time, how?
51 Forum
.threads
= relation(Thread
, order_by
=Thread
.id.desc(), lazy
='dynamic', backref
='forum')
53 Thread
.posts
= relation(Post
, order_by
=Post
.position
.asc(), lazy
='dynamic', backref
='thread')
54 Thread
.first_post
= relation(Post
, primaryjoin
=and_(Post
.thread_id
== Thread
.id, Post
.position
== 1), uselist
=False)
55 Thread
.last_post
= relation(Post
, primaryjoin
=and_(Post
.thread_id
== Thread
.id, Post
.position
== Thread
.post_count
), uselist
=False)
57 Post
.author
= relation(users_model
.User
, backref
='posts')