Thread creation and some tiny posting polish.
[zzz-spline-forum.git] / splinext / forum / model / __init__.py
1 from datetime import datetime
2
3 from sqlalchemy import and_, Column, ForeignKey, Index
4 from sqlalchemy.orm import relation
5 from sqlalchemy.types import DateTime, Integer, Unicode
6
7 from spline.model.meta import TableBase
8 from splinext.users import model as users_model
9
10
11 ### Core
12
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)
17
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)
25
26 def specific_post(self, position):
27 """Returns post number `position` in this thread.
28
29 Positions are one-indexed. Negative indexes are allowed.
30 """
31
32 # Handle negative indexes
33 if position < 0:
34 position = self.post_count + position + 1
35
36 return self.posts.filter_by(position=position).one()
37
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)
46
47 Index('thread_position', Post.thread_id, Post.position, unique=True)
48
49
50 # XXX sort by time, how?
51 Forum.threads = relation(Thread, order_by=Thread.id.desc(), lazy='dynamic', backref='forum')
52
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)
56
57 Post.author = relation(users_model.User, backref='posts')