##// END OF EJS Templates
adde short cache for repo_path
marcink -
r1368:04b43168 beta
parent child Browse files
Show More
@@ -1,703 +1,705 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 rhodecode.model.db
3 rhodecode.model.db
4 ~~~~~~~~~~~~~~~~~~
4 ~~~~~~~~~~~~~~~~~~
5
5
6 Database Models for RhodeCode
6 Database Models for RhodeCode
7
7
8 :created_on: Apr 08, 2010
8 :created_on: Apr 08, 2010
9 :author: marcink
9 :author: marcink
10 :copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
10 :copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
11 :license: GPLv3, see COPYING for more details.
11 :license: GPLv3, see COPYING for more details.
12 """
12 """
13 # This program is free software: you can redistribute it and/or modify
13 # This program is free software: you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation, either version 3 of the License, or
15 # the Free Software Foundation, either version 3 of the License, or
16 # (at your option) any later version.
16 # (at your option) any later version.
17 #
17 #
18 # This program is distributed in the hope that it will be useful,
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
21 # GNU General Public License for more details.
22 #
22 #
23 # You should have received a copy of the GNU General Public License
23 # You should have received a copy of the GNU General Public License
24 # along with this program. If not, see <http://www.gnu.org/licenses/>.
24 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25
25
26 import os
26 import os
27 import logging
27 import logging
28 import datetime
28 import datetime
29 import traceback
29 import traceback
30 from datetime import date
30 from datetime import date
31
31
32 from sqlalchemy import *
32 from sqlalchemy import *
33 from sqlalchemy.exc import DatabaseError
33 from sqlalchemy.exc import DatabaseError
34 from sqlalchemy.orm import relationship, backref, joinedload
34 from sqlalchemy.orm import relationship, backref, joinedload
35 from sqlalchemy.orm.interfaces import MapperExtension
35 from sqlalchemy.orm.interfaces import MapperExtension
36
36
37 from beaker.cache import cache_region, region_invalidate
37 from beaker.cache import cache_region, region_invalidate
38
38
39
40 from vcs import get_backend
39 from vcs import get_backend
41 from vcs.utils.helpers import get_scm
40 from vcs.utils.helpers import get_scm
42 from vcs.exceptions import RepositoryError, VCSError
41 from vcs.exceptions import RepositoryError, VCSError
43 from vcs.utils.lazy import LazyProperty
42 from vcs.utils.lazy import LazyProperty
44 from vcs.nodes import FileNode
43 from vcs.nodes import FileNode
45
44
46 from rhodecode.lib import str2bool
45 from rhodecode.lib import str2bool
47 from rhodecode.model.meta import Base, Session
46 from rhodecode.model.meta import Base, Session
48 from rhodecode.model.caching_query import FromCache
47 from rhodecode.model.caching_query import FromCache
49
48
50 log = logging.getLogger(__name__)
49 log = logging.getLogger(__name__)
51
50
52 #==============================================================================
51 #==============================================================================
53 # MAPPER EXTENSIONS
52 # MAPPER EXTENSIONS
54 #==============================================================================
53 #==============================================================================
55
54
56 class RepositoryMapper(MapperExtension):
55 class RepositoryMapper(MapperExtension):
57 def after_update(self, mapper, connection, instance):
56 def after_update(self, mapper, connection, instance):
58 pass
57 pass
59
58
60
59
61 class RhodeCodeSettings(Base):
60 class RhodeCodeSettings(Base):
62 __tablename__ = 'rhodecode_settings'
61 __tablename__ = 'rhodecode_settings'
63 __table_args__ = (UniqueConstraint('app_settings_name'), {'extend_existing':True})
62 __table_args__ = (UniqueConstraint('app_settings_name'), {'extend_existing':True})
64 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
63 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
65 app_settings_name = Column("app_settings_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
64 app_settings_name = Column("app_settings_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
66 app_settings_value = Column("app_settings_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
65 app_settings_value = Column("app_settings_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
67
66
68 def __init__(self, k='', v=''):
67 def __init__(self, k='', v=''):
69 self.app_settings_name = k
68 self.app_settings_name = k
70 self.app_settings_value = v
69 self.app_settings_value = v
71
70
72 def __repr__(self):
71 def __repr__(self):
73 return "<%s('%s:%s')>" % (self.__class__.__name__,
72 return "<%s('%s:%s')>" % (self.__class__.__name__,
74 self.app_settings_name, self.app_settings_value)
73 self.app_settings_name, self.app_settings_value)
75
74
76
75
77 @classmethod
76 @classmethod
78 def get_by_name(cls, ldap_key):
77 def get_by_name(cls, ldap_key):
79 return Session.query(cls)\
78 return Session.query(cls)\
80 .filter(cls.app_settings_name == ldap_key).scalar()
79 .filter(cls.app_settings_name == ldap_key).scalar()
81
80
82 @classmethod
81 @classmethod
83 def get_app_settings(cls, cache=False):
82 def get_app_settings(cls, cache=False):
84
83
85 ret = Session.query(cls)
84 ret = Session.query(cls)
86
85
87 if cache:
86 if cache:
88 ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
87 ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
89
88
90 if not ret:
89 if not ret:
91 raise Exception('Could not get application settings !')
90 raise Exception('Could not get application settings !')
92 settings = {}
91 settings = {}
93 for each in ret:
92 for each in ret:
94 settings['rhodecode_' + each.app_settings_name] = \
93 settings['rhodecode_' + each.app_settings_name] = \
95 each.app_settings_value
94 each.app_settings_value
96
95
97 return settings
96 return settings
98
97
99 @classmethod
98 @classmethod
100 def get_ldap_settings(cls, cache=False):
99 def get_ldap_settings(cls, cache=False):
101 ret = Session.query(cls)\
100 ret = Session.query(cls)\
102 .filter(cls.app_settings_name.startswith('ldap_'))\
101 .filter(cls.app_settings_name.startswith('ldap_'))\
103 .all()
102 .all()
104 fd = {}
103 fd = {}
105 for row in ret:
104 for row in ret:
106 fd.update({row.app_settings_name:row.app_settings_value})
105 fd.update({row.app_settings_name:row.app_settings_value})
107 return fd
106 return fd
108
107
109
108
110 class RhodeCodeUi(Base):
109 class RhodeCodeUi(Base):
111 __tablename__ = 'rhodecode_ui'
110 __tablename__ = 'rhodecode_ui'
112 __table_args__ = {'extend_existing':True}
111 __table_args__ = {'extend_existing':True}
113 ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
112 ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
114 ui_section = Column("ui_section", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
113 ui_section = Column("ui_section", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
115 ui_key = Column("ui_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
114 ui_key = Column("ui_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
116 ui_value = Column("ui_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
115 ui_value = Column("ui_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
117 ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
116 ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
118
117
119
118
120 @classmethod
119 @classmethod
121 def get_by_key(cls, key):
120 def get_by_key(cls, key):
122 return Session.query(cls).filter(cls.ui_key == key)
121 return Session.query(cls).filter(cls.ui_key == key)
123
122
124
123
125 class User(Base):
124 class User(Base):
126 __tablename__ = 'users'
125 __tablename__ = 'users'
127 __table_args__ = (UniqueConstraint('username'), UniqueConstraint('email'), {'extend_existing':True})
126 __table_args__ = (UniqueConstraint('username'), UniqueConstraint('email'), {'extend_existing':True})
128 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
127 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
129 username = Column("username", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
128 username = Column("username", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
130 password = Column("password", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
129 password = Column("password", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
131 active = Column("active", Boolean(), nullable=True, unique=None, default=None)
130 active = Column("active", Boolean(), nullable=True, unique=None, default=None)
132 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
131 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
133 name = Column("name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
132 name = Column("name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
134 lastname = Column("lastname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
133 lastname = Column("lastname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
135 email = Column("email", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
134 email = Column("email", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
136 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
135 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
137 ldap_dn = Column("ldap_dn", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
136 ldap_dn = Column("ldap_dn", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
138 api_key = Column("api_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
137 api_key = Column("api_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
139
138
140 user_log = relationship('UserLog', cascade='all')
139 user_log = relationship('UserLog', cascade='all')
141 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
140 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
142
141
143 repositories = relationship('Repository')
142 repositories = relationship('Repository')
144 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
143 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
145 repo_to_perm = relationship('RepoToPerm', primaryjoin='RepoToPerm.user_id==User.user_id', cascade='all')
144 repo_to_perm = relationship('RepoToPerm', primaryjoin='RepoToPerm.user_id==User.user_id', cascade='all')
146
145
147 group_member = relationship('UsersGroupMember', cascade='all')
146 group_member = relationship('UsersGroupMember', cascade='all')
148
147
149 @property
148 @property
150 def full_contact(self):
149 def full_contact(self):
151 return '%s %s <%s>' % (self.name, self.lastname, self.email)
150 return '%s %s <%s>' % (self.name, self.lastname, self.email)
152
151
153 @property
152 @property
154 def short_contact(self):
153 def short_contact(self):
155 return '%s %s' % (self.name, self.lastname)
154 return '%s %s' % (self.name, self.lastname)
156
155
157
156
158 @property
157 @property
159 def is_admin(self):
158 def is_admin(self):
160 return self.admin
159 return self.admin
161
160
162 def __repr__(self):
161 def __repr__(self):
163 return 'ahmmm'
162 return 'ahmmm'
164 return "<%s('id:%s:%s')>" % (self.__class__.__name__,
163 return "<%s('id:%s:%s')>" % (self.__class__.__name__,
165 self.user_id, self.username)
164 self.user_id, self.username)
166
165
167 @classmethod
166 @classmethod
168 def by_username(cls, username):
167 def by_username(cls, username):
169 return Session.query(cls).filter(cls.username == username).one()
168 return Session.query(cls).filter(cls.username == username).one()
170
169
171
170
172 def update_lastlogin(self):
171 def update_lastlogin(self):
173 """Update user lastlogin"""
172 """Update user lastlogin"""
174
173
175 try:
174 try:
176 session = Session.object_session(self)
175 session = Session.object_session(self)
177 self.last_login = datetime.datetime.now()
176 self.last_login = datetime.datetime.now()
178 session.add(self)
177 session.add(self)
179 session.commit()
178 session.commit()
180 log.debug('updated user %s lastlogin', self.username)
179 log.debug('updated user %s lastlogin', self.username)
181 except (DatabaseError,):
180 except (DatabaseError,):
182 session.rollback()
181 session.rollback()
183
182
184
183
185 class UserLog(Base):
184 class UserLog(Base):
186 __tablename__ = 'user_logs'
185 __tablename__ = 'user_logs'
187 __table_args__ = {'extend_existing':True}
186 __table_args__ = {'extend_existing':True}
188 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
187 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
189 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
188 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
190 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
189 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
191 repository_name = Column("repository_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
190 repository_name = Column("repository_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
192 user_ip = Column("user_ip", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
191 user_ip = Column("user_ip", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
193 action = Column("action", UnicodeText(length=1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
192 action = Column("action", UnicodeText(length=1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
194 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
193 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
195
194
196 @property
195 @property
197 def action_as_day(self):
196 def action_as_day(self):
198 return date(*self.action_date.timetuple()[:3])
197 return date(*self.action_date.timetuple()[:3])
199
198
200 user = relationship('User')
199 user = relationship('User')
201 repository = relationship('Repository')
200 repository = relationship('Repository')
202
201
203
202
204 class UsersGroup(Base):
203 class UsersGroup(Base):
205 __tablename__ = 'users_groups'
204 __tablename__ = 'users_groups'
206 __table_args__ = {'extend_existing':True}
205 __table_args__ = {'extend_existing':True}
207
206
208 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
207 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
209 users_group_name = Column("users_group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
208 users_group_name = Column("users_group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
210 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
209 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
211
210
212 members = relationship('UsersGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
211 members = relationship('UsersGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
213
212
214
213
215 @classmethod
214 @classmethod
216 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
215 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
217 if case_insensitive:
216 if case_insensitive:
218 gr = Session.query(cls)\
217 gr = Session.query(cls)\
219 .filter(cls.users_group_name.ilike(group_name))
218 .filter(cls.users_group_name.ilike(group_name))
220 else:
219 else:
221 gr = Session.query(UsersGroup)\
220 gr = Session.query(UsersGroup)\
222 .filter(UsersGroup.users_group_name == group_name)
221 .filter(UsersGroup.users_group_name == group_name)
223 if cache:
222 if cache:
224 gr = gr.options(FromCache("sql_cache_short",
223 gr = gr.options(FromCache("sql_cache_short",
225 "get_user_%s" % group_name))
224 "get_user_%s" % group_name))
226 return gr.scalar()
225 return gr.scalar()
227
226
228 class UsersGroupMember(Base):
227 class UsersGroupMember(Base):
229 __tablename__ = 'users_groups_members'
228 __tablename__ = 'users_groups_members'
230 __table_args__ = {'extend_existing':True}
229 __table_args__ = {'extend_existing':True}
231
230
232 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
231 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
233 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
232 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
234 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
233 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
235
234
236 user = relationship('User', lazy='joined')
235 user = relationship('User', lazy='joined')
237 users_group = relationship('UsersGroup')
236 users_group = relationship('UsersGroup')
238
237
239 def __init__(self, gr_id='', u_id=''):
238 def __init__(self, gr_id='', u_id=''):
240 self.users_group_id = gr_id
239 self.users_group_id = gr_id
241 self.user_id = u_id
240 self.user_id = u_id
242
241
243 class Repository(Base):
242 class Repository(Base):
244 __tablename__ = 'repositories'
243 __tablename__ = 'repositories'
245 __table_args__ = (UniqueConstraint('repo_name'), {'extend_existing':True},)
244 __table_args__ = (UniqueConstraint('repo_name'), {'extend_existing':True},)
246 __mapper_args__ = {'extension':RepositoryMapper()}
245 __mapper_args__ = {'extension':RepositoryMapper()}
247
246
248 repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
247 repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
249 repo_name = Column("repo_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
248 repo_name = Column("repo_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
250 clone_uri = Column("clone_uri", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
249 clone_uri = Column("clone_uri", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
251 repo_type = Column("repo_type", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default='hg')
250 repo_type = Column("repo_type", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default='hg')
252 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
251 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
253 private = Column("private", Boolean(), nullable=True, unique=None, default=None)
252 private = Column("private", Boolean(), nullable=True, unique=None, default=None)
254 enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
253 enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
255 enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
254 enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
256 description = Column("description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
255 description = Column("description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
257 created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
256 created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
258
257
259 fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
258 fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
260 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
259 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
261
260
262
261
263 user = relationship('User')
262 user = relationship('User')
264 fork = relationship('Repository', remote_side=repo_id)
263 fork = relationship('Repository', remote_side=repo_id)
265 group = relationship('Group')
264 group = relationship('Group')
266 repo_to_perm = relationship('RepoToPerm', cascade='all', order_by='RepoToPerm.repo_to_perm_id')
265 repo_to_perm = relationship('RepoToPerm', cascade='all', order_by='RepoToPerm.repo_to_perm_id')
267 users_group_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
266 users_group_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
268 stats = relationship('Statistics', cascade='all', uselist=False)
267 stats = relationship('Statistics', cascade='all', uselist=False)
269
268
270 followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all')
269 followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all')
271
270
272 logs = relationship('UserLog', cascade='all')
271 logs = relationship('UserLog', cascade='all')
273
272
274 def __repr__(self):
273 def __repr__(self):
275 return "<%s('%s:%s')>" % (self.__class__.__name__,
274 return "<%s('%s:%s')>" % (self.__class__.__name__,
276 self.repo_id, self.repo_name)
275 self.repo_id, self.repo_name)
277
276
278 @classmethod
277 @classmethod
279 def by_repo_name(cls, repo_name):
278 def by_repo_name(cls, repo_name):
280 q = Session.query(cls).filter(cls.repo_name == repo_name)
279 q = Session.query(cls).filter(cls.repo_name == repo_name)
281
280
282 q = q.options(joinedload(Repository.fork))\
281 q = q.options(joinedload(Repository.fork))\
283 .options(joinedload(Repository.user))\
282 .options(joinedload(Repository.user))\
284 .options(joinedload(Repository.group))\
283 .options(joinedload(Repository.group))\
285
284
286 return q.one()
285 return q.one()
287
286
288 @classmethod
287 @classmethod
289 def get_repo_forks(cls, repo_id):
288 def get_repo_forks(cls, repo_id):
290 return Session.query(cls).filter(Repository.fork_id == repo_id)
289 return Session.query(cls).filter(Repository.fork_id == repo_id)
291
290
292 @property
291 @property
293 def just_name(self):
292 def just_name(self):
294 return self.repo_name.split(os.sep)[-1]
293 return self.repo_name.split(os.sep)[-1]
295
294
296 @property
295 @property
297 def groups_with_parents(self):
296 def groups_with_parents(self):
298 groups = []
297 groups = []
299 if self.group is None:
298 if self.group is None:
300 return groups
299 return groups
301
300
302 cur_gr = self.group
301 cur_gr = self.group
303 groups.insert(0, cur_gr)
302 groups.insert(0, cur_gr)
304 while 1:
303 while 1:
305 gr = getattr(cur_gr, 'parent_group', None)
304 gr = getattr(cur_gr, 'parent_group', None)
306 cur_gr = cur_gr.parent_group
305 cur_gr = cur_gr.parent_group
307 if gr is None:
306 if gr is None:
308 break
307 break
309 groups.insert(0, gr)
308 groups.insert(0, gr)
310
309
311 return groups
310 return groups
312
311
313 @property
312 @property
314 def groups_and_repo(self):
313 def groups_and_repo(self):
315 return self.groups_with_parents, self.just_name
314 return self.groups_with_parents, self.just_name
316
315
317 @LazyProperty
316 @LazyProperty
318 def repo_path(self):
317 def repo_path(self):
319 """
318 """
320 Returns base full path for that repository means where it actually
319 Returns base full path for that repository means where it actually
321 exists on a filesystem
320 exists on a filesystem
322 """
321 """
323
322 q = Session.query(RhodeCodeUi).filter(RhodeCodeUi.ui_key == '/')
324 q = Session.query(RhodeCodeUi).filter(RhodeCodeUi.ui_key == '/').one()
323 q.options(FromCache("sql_cache_short", "repository_repo_path"))
325 return q.ui_value
324 return q.one().ui_value
326
325
327 @property
326 @property
328 def repo_full_path(self):
327 def repo_full_path(self):
329 p = [self.repo_path]
328 p = [self.repo_path]
330 # we need to split the name by / since this is how we store the
329 # we need to split the name by / since this is how we store the
331 # names in the database, but that eventually needs to be converted
330 # names in the database, but that eventually needs to be converted
332 # into a valid system path
331 # into a valid system path
333 p += self.repo_name.split('/')
332 p += self.repo_name.split('/')
334 return os.path.join(*p)
333 return os.path.join(*p)
335
334
336 @property
335 @property
337 def _ui(self):
336 def _ui(self):
338 """
337 """
339 Creates an db based ui object for this repository
338 Creates an db based ui object for this repository
340 """
339 """
341 from mercurial import ui
340 from mercurial import ui
342 from mercurial import config
341 from mercurial import config
343 baseui = ui.ui()
342 baseui = ui.ui()
344
343
345 #clean the baseui object
344 #clean the baseui object
346 baseui._ocfg = config.config()
345 baseui._ocfg = config.config()
347 baseui._ucfg = config.config()
346 baseui._ucfg = config.config()
348 baseui._tcfg = config.config()
347 baseui._tcfg = config.config()
349
348
350
349
351 ret = Session.query(RhodeCodeUi)\
350 ret = Session.query(RhodeCodeUi)\
352 .options(FromCache("sql_cache_short",
351 .options(FromCache("sql_cache_short",
353 "repository_repo_ui")).all()
352 "repository_repo_ui")).all()
354
353
355 hg_ui = ret
354 hg_ui = ret
356 for ui_ in hg_ui:
355 for ui_ in hg_ui:
357 if ui_.ui_active:
356 if ui_.ui_active:
358 log.debug('settings ui from db[%s]%s:%s', ui_.ui_section,
357 log.debug('settings ui from db[%s]%s:%s', ui_.ui_section,
359 ui_.ui_key, ui_.ui_value)
358 ui_.ui_key, ui_.ui_value)
360 baseui.setconfig(ui_.ui_section, ui_.ui_key, ui_.ui_value)
359 baseui.setconfig(ui_.ui_section, ui_.ui_key, ui_.ui_value)
361
360
362 return baseui
361 return baseui
363
362
364 #==========================================================================
363 #==========================================================================
365 # SCM CACHE INSTANCE
364 # SCM CACHE INSTANCE
366 #==========================================================================
365 #==========================================================================
367
366
368 @property
367 @property
369 def invalidate(self):
368 def invalidate(self):
370 """
369 """
371 Returns Invalidation object if this repo should be invalidated
370 Returns Invalidation object if this repo should be invalidated
372 None otherwise. `cache_active = False` means that this cache
371 None otherwise. `cache_active = False` means that this cache
373 state is not valid and needs to be invalidated
372 state is not valid and needs to be invalidated
374 """
373 """
375 return Session.query(CacheInvalidation)\
374 return Session.query(CacheInvalidation)\
376 .filter(CacheInvalidation.cache_key == self.repo_name)\
375 .filter(CacheInvalidation.cache_key == self.repo_name)\
377 .filter(CacheInvalidation.cache_active == False)\
376 .filter(CacheInvalidation.cache_active == False)\
378 .scalar()
377 .scalar()
379
378
380 @property
379 @property
381 def set_invalidate(self):
380 def set_invalidate(self):
382 """
381 """
383 set a cache for invalidation for this instance
382 set a cache for invalidation for this instance
384 """
383 """
385 inv = Session.query(CacheInvalidation)\
384 inv = Session.query(CacheInvalidation)\
386 .filter(CacheInvalidation.cache_key == self.repo_name)\
385 .filter(CacheInvalidation.cache_key == self.repo_name)\
387 .scalar()
386 .scalar()
388
387
389 if inv is None:
388 if inv is None:
390 inv = CacheInvalidation(self.repo_name)
389 inv = CacheInvalidation(self.repo_name)
391 inv.cache_active = True
390 inv.cache_active = True
392 Session.add(inv)
391 Session.add(inv)
393 Session.commit()
392 Session.commit()
394
393
395 @property
394 @property
396 def scm_instance(self):
395 def scm_instance(self):
397 return self.__get_instance(self.repo_name)
396 return self.__get_instance(self.repo_name)
398
397
399 @property
398 @property
400 def scm_instance_cached(self):
399 def scm_instance_cached(self):
401 @cache_region('long_term')
400 @cache_region('long_term')
402 def _c(repo_name):
401 def _c(repo_name):
403 return self.__get_instance(repo_name)
402 return self.__get_instance(repo_name)
404
403
405 inv = self.invalidate
404 inv = self.invalidate
406 if inv:
405 if inv:
407 region_invalidate(_c, None, self.repo_name)
406 region_invalidate(_c, None, self.repo_name)
408 #update our cache
407 #update our cache
409 inv.cache_key.cache_active = True
408 inv.cache_key.cache_active = True
410 Session.add(inv)
409 Session.add(inv)
411 Session.commit()
410 Session.commit()
412
411
413 return _c(self.repo_name)
412 return _c(self.repo_name)
414
413
415 def __get_instance(self, repo_name):
414 def __get_instance(self, repo_name):
415
416 repo_full_path = self.repo_full_path
417
416 try:
418 try:
417 alias = get_scm(self.repo_full_path)[0]
419 alias = get_scm(repo_full_path)[0]
418 log.debug('Creating instance of %s repository', alias)
420 log.debug('Creating instance of %s repository', alias)
419 backend = get_backend(alias)
421 backend = get_backend(alias)
420 except VCSError:
422 except VCSError:
421 log.error(traceback.format_exc())
423 log.error(traceback.format_exc())
422 log.error('Perhaps this repository is in db and not in '
424 log.error('Perhaps this repository is in db and not in '
423 'filesystem run rescan repositories with '
425 'filesystem run rescan repositories with '
424 '"destroy old data " option from admin panel')
426 '"destroy old data " option from admin panel')
425 return
427 return
426
428
427 if alias == 'hg':
429 if alias == 'hg':
428 repo = backend(self.repo_full_path, create=False,
430 repo = backend(repo_full_path, create=False,
429 baseui=self._ui)
431 baseui=self._ui)
430 #skip hidden web repository
432 #skip hidden web repository
431 if repo._get_hidden():
433 if repo._get_hidden():
432 return
434 return
433 else:
435 else:
434 repo = backend(self.repo_full_path, create=False)
436 repo = backend(repo_full_path, create=False)
435
437
436 return repo
438 return repo
437
439
438
440
439 class Group(Base):
441 class Group(Base):
440 __tablename__ = 'groups'
442 __tablename__ = 'groups'
441 __table_args__ = (UniqueConstraint('group_name', 'group_parent_id'),
443 __table_args__ = (UniqueConstraint('group_name', 'group_parent_id'),
442 CheckConstraint('group_id != group_parent_id'), {'extend_existing':True},)
444 CheckConstraint('group_id != group_parent_id'), {'extend_existing':True},)
443 __mapper_args__ = {'order_by':'group_name'}
445 __mapper_args__ = {'order_by':'group_name'}
444
446
445 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
447 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
446 group_name = Column("group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
448 group_name = Column("group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
447 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
449 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
448 group_description = Column("group_description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
450 group_description = Column("group_description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
449
451
450 parent_group = relationship('Group', remote_side=group_id)
452 parent_group = relationship('Group', remote_side=group_id)
451
453
452
454
453 def __init__(self, group_name='', parent_group=None):
455 def __init__(self, group_name='', parent_group=None):
454 self.group_name = group_name
456 self.group_name = group_name
455 self.parent_group = parent_group
457 self.parent_group = parent_group
456
458
457 def __repr__(self):
459 def __repr__(self):
458 return "<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
460 return "<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
459 self.group_name)
461 self.group_name)
460
462
461 @classmethod
463 @classmethod
462 def url_sep(cls):
464 def url_sep(cls):
463 return '/'
465 return '/'
464
466
465 @property
467 @property
466 def parents(self):
468 def parents(self):
467 parents_limit = 5
469 parents_limit = 5
468 groups = []
470 groups = []
469 if self.parent_group is None:
471 if self.parent_group is None:
470 return groups
472 return groups
471 cur_gr = self.parent_group
473 cur_gr = self.parent_group
472 groups.insert(0, cur_gr)
474 groups.insert(0, cur_gr)
473 cnt = 0
475 cnt = 0
474 while 1:
476 while 1:
475 cnt += 1
477 cnt += 1
476 gr = getattr(cur_gr, 'parent_group', None)
478 gr = getattr(cur_gr, 'parent_group', None)
477 cur_gr = cur_gr.parent_group
479 cur_gr = cur_gr.parent_group
478 if gr is None:
480 if gr is None:
479 break
481 break
480 if cnt == parents_limit:
482 if cnt == parents_limit:
481 # this will prevent accidental infinit loops
483 # this will prevent accidental infinit loops
482 log.error('group nested more than %s' %
484 log.error('group nested more than %s' %
483 parents_limit)
485 parents_limit)
484 break
486 break
485
487
486 groups.insert(0, gr)
488 groups.insert(0, gr)
487 return groups
489 return groups
488
490
489
491
490 @property
492 @property
491 def full_path(self):
493 def full_path(self):
492 return Group.url_sep().join([g.group_name for g in self.parents] +
494 return Group.url_sep().join([g.group_name for g in self.parents] +
493 [self.group_name])
495 [self.group_name])
494
496
495 @property
497 @property
496 def repositories(self):
498 def repositories(self):
497 return Session.query(Repository).filter(Repository.group == self)
499 return Session.query(Repository).filter(Repository.group == self)
498
500
499 class Permission(Base):
501 class Permission(Base):
500 __tablename__ = 'permissions'
502 __tablename__ = 'permissions'
501 __table_args__ = {'extend_existing':True}
503 __table_args__ = {'extend_existing':True}
502 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
504 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
503 permission_name = Column("permission_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
505 permission_name = Column("permission_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
504 permission_longname = Column("permission_longname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
506 permission_longname = Column("permission_longname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
505
507
506 def __repr__(self):
508 def __repr__(self):
507 return "<%s('%s:%s')>" % (self.__class__.__name__,
509 return "<%s('%s:%s')>" % (self.__class__.__name__,
508 self.permission_id, self.permission_name)
510 self.permission_id, self.permission_name)
509
511
510 @classmethod
512 @classmethod
511 def get_by_key(cls, key):
513 def get_by_key(cls, key):
512 return Session.query(cls).filter(cls.permission_name == key).scalar()
514 return Session.query(cls).filter(cls.permission_name == key).scalar()
513
515
514 class RepoToPerm(Base):
516 class RepoToPerm(Base):
515 __tablename__ = 'repo_to_perm'
517 __tablename__ = 'repo_to_perm'
516 __table_args__ = (UniqueConstraint('user_id', 'repository_id'), {'extend_existing':True})
518 __table_args__ = (UniqueConstraint('user_id', 'repository_id'), {'extend_existing':True})
517 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
519 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
518 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
520 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
519 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
521 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
520 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
522 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
521
523
522 user = relationship('User')
524 user = relationship('User')
523 permission = relationship('Permission')
525 permission = relationship('Permission')
524 repository = relationship('Repository')
526 repository = relationship('Repository')
525
527
526 class UserToPerm(Base):
528 class UserToPerm(Base):
527 __tablename__ = 'user_to_perm'
529 __tablename__ = 'user_to_perm'
528 __table_args__ = (UniqueConstraint('user_id', 'permission_id'), {'extend_existing':True})
530 __table_args__ = (UniqueConstraint('user_id', 'permission_id'), {'extend_existing':True})
529 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
531 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
530 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
532 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
531 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
533 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
532
534
533 user = relationship('User')
535 user = relationship('User')
534 permission = relationship('Permission')
536 permission = relationship('Permission')
535
537
536 @classmethod
538 @classmethod
537 def has_perm(cls, user_id, perm):
539 def has_perm(cls, user_id, perm):
538 if not isinstance(perm, Permission):
540 if not isinstance(perm, Permission):
539 raise Exception('perm needs to be an instance of Permission class')
541 raise Exception('perm needs to be an instance of Permission class')
540
542
541 return Session.query(cls).filter(cls.user_id == user_id)\
543 return Session.query(cls).filter(cls.user_id == user_id)\
542 .filter(cls.permission == perm).scalar() is not None
544 .filter(cls.permission == perm).scalar() is not None
543
545
544 @classmethod
546 @classmethod
545 def grant_perm(cls, user_id, perm):
547 def grant_perm(cls, user_id, perm):
546 if not isinstance(perm, Permission):
548 if not isinstance(perm, Permission):
547 raise Exception('perm needs to be an instance of Permission class')
549 raise Exception('perm needs to be an instance of Permission class')
548
550
549 new = cls()
551 new = cls()
550 new.user_id = user_id
552 new.user_id = user_id
551 new.permission = perm
553 new.permission = perm
552 try:
554 try:
553 Session.add(new)
555 Session.add(new)
554 Session.commit()
556 Session.commit()
555 except:
557 except:
556 Session.rollback()
558 Session.rollback()
557
559
558
560
559 @classmethod
561 @classmethod
560 def revoke_perm(cls, user_id, perm):
562 def revoke_perm(cls, user_id, perm):
561 if not isinstance(perm, Permission):
563 if not isinstance(perm, Permission):
562 raise Exception('perm needs to be an instance of Permission class')
564 raise Exception('perm needs to be an instance of Permission class')
563
565
564 try:
566 try:
565 Session.query(cls).filter(cls.user_id == user_id)\
567 Session.query(cls).filter(cls.user_id == user_id)\
566 .filter(cls.permission == perm).delete()
568 .filter(cls.permission == perm).delete()
567 Session.commit()
569 Session.commit()
568 except:
570 except:
569 Session.rollback()
571 Session.rollback()
570
572
571 class UsersGroupRepoToPerm(Base):
573 class UsersGroupRepoToPerm(Base):
572 __tablename__ = 'users_group_repo_to_perm'
574 __tablename__ = 'users_group_repo_to_perm'
573 __table_args__ = (UniqueConstraint('users_group_id', 'permission_id'), {'extend_existing':True})
575 __table_args__ = (UniqueConstraint('users_group_id', 'permission_id'), {'extend_existing':True})
574 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
576 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
575 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
577 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
576 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
578 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
577 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
579 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
578
580
579 users_group = relationship('UsersGroup')
581 users_group = relationship('UsersGroup')
580 permission = relationship('Permission')
582 permission = relationship('Permission')
581 repository = relationship('Repository')
583 repository = relationship('Repository')
582
584
583
585
584 class UsersGroupToPerm(Base):
586 class UsersGroupToPerm(Base):
585 __tablename__ = 'users_group_to_perm'
587 __tablename__ = 'users_group_to_perm'
586 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
588 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
587 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
589 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
588 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
590 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
589
591
590 users_group = relationship('UsersGroup')
592 users_group = relationship('UsersGroup')
591 permission = relationship('Permission')
593 permission = relationship('Permission')
592
594
593
595
594 @classmethod
596 @classmethod
595 def has_perm(cls, users_group_id, perm):
597 def has_perm(cls, users_group_id, perm):
596 if not isinstance(perm, Permission):
598 if not isinstance(perm, Permission):
597 raise Exception('perm needs to be an instance of Permission class')
599 raise Exception('perm needs to be an instance of Permission class')
598
600
599 return Session.query(cls).filter(cls.users_group_id ==
601 return Session.query(cls).filter(cls.users_group_id ==
600 users_group_id)\
602 users_group_id)\
601 .filter(cls.permission == perm)\
603 .filter(cls.permission == perm)\
602 .scalar() is not None
604 .scalar() is not None
603
605
604 @classmethod
606 @classmethod
605 def grant_perm(cls, users_group_id, perm):
607 def grant_perm(cls, users_group_id, perm):
606 if not isinstance(perm, Permission):
608 if not isinstance(perm, Permission):
607 raise Exception('perm needs to be an instance of Permission class')
609 raise Exception('perm needs to be an instance of Permission class')
608
610
609 new = cls()
611 new = cls()
610 new.users_group_id = users_group_id
612 new.users_group_id = users_group_id
611 new.permission = perm
613 new.permission = perm
612 try:
614 try:
613 Session.add(new)
615 Session.add(new)
614 Session.commit()
616 Session.commit()
615 except:
617 except:
616 Session.rollback()
618 Session.rollback()
617
619
618
620
619 @classmethod
621 @classmethod
620 def revoke_perm(cls, users_group_id, perm):
622 def revoke_perm(cls, users_group_id, perm):
621 if not isinstance(perm, Permission):
623 if not isinstance(perm, Permission):
622 raise Exception('perm needs to be an instance of Permission class')
624 raise Exception('perm needs to be an instance of Permission class')
623
625
624 try:
626 try:
625 Session.query(cls).filter(cls.users_group_id == users_group_id)\
627 Session.query(cls).filter(cls.users_group_id == users_group_id)\
626 .filter(cls.permission == perm).delete()
628 .filter(cls.permission == perm).delete()
627 Session.commit()
629 Session.commit()
628 except:
630 except:
629 Session.rollback()
631 Session.rollback()
630
632
631
633
632 class GroupToPerm(Base):
634 class GroupToPerm(Base):
633 __tablename__ = 'group_to_perm'
635 __tablename__ = 'group_to_perm'
634 __table_args__ = (UniqueConstraint('group_id', 'permission_id'), {'extend_existing':True})
636 __table_args__ = (UniqueConstraint('group_id', 'permission_id'), {'extend_existing':True})
635
637
636 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
638 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
637 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
639 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
638 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
640 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
639 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
641 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
640
642
641 user = relationship('User')
643 user = relationship('User')
642 permission = relationship('Permission')
644 permission = relationship('Permission')
643 group = relationship('Group')
645 group = relationship('Group')
644
646
645 class Statistics(Base):
647 class Statistics(Base):
646 __tablename__ = 'statistics'
648 __tablename__ = 'statistics'
647 __table_args__ = (UniqueConstraint('repository_id'), {'extend_existing':True})
649 __table_args__ = (UniqueConstraint('repository_id'), {'extend_existing':True})
648 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
650 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
649 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
651 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
650 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
652 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
651 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
653 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
652 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
654 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
653 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
655 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
654
656
655 repository = relationship('Repository', single_parent=True)
657 repository = relationship('Repository', single_parent=True)
656
658
657 class UserFollowing(Base):
659 class UserFollowing(Base):
658 __tablename__ = 'user_followings'
660 __tablename__ = 'user_followings'
659 __table_args__ = (UniqueConstraint('user_id', 'follows_repository_id'),
661 __table_args__ = (UniqueConstraint('user_id', 'follows_repository_id'),
660 UniqueConstraint('user_id', 'follows_user_id')
662 UniqueConstraint('user_id', 'follows_user_id')
661 , {'extend_existing':True})
663 , {'extend_existing':True})
662
664
663 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
665 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
664 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
666 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
665 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
667 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
666 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
668 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
667 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
669 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
668
670
669 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
671 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
670
672
671 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
673 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
672 follows_repository = relationship('Repository', order_by='Repository.repo_name')
674 follows_repository = relationship('Repository', order_by='Repository.repo_name')
673
675
674
676
675
677
676 @classmethod
678 @classmethod
677 def get_repo_followers(cls, repo_id):
679 def get_repo_followers(cls, repo_id):
678 return Session.query(cls).filter(cls.follows_repo_id == repo_id)
680 return Session.query(cls).filter(cls.follows_repo_id == repo_id)
679
681
680 class CacheInvalidation(Base):
682 class CacheInvalidation(Base):
681 __tablename__ = 'cache_invalidation'
683 __tablename__ = 'cache_invalidation'
682 __table_args__ = (UniqueConstraint('cache_key'), {'extend_existing':True})
684 __table_args__ = (UniqueConstraint('cache_key'), {'extend_existing':True})
683 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
685 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
684 cache_key = Column("cache_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
686 cache_key = Column("cache_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
685 cache_args = Column("cache_args", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
687 cache_args = Column("cache_args", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
686 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
688 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
687
689
688
690
689 def __init__(self, cache_key, cache_args=''):
691 def __init__(self, cache_key, cache_args=''):
690 self.cache_key = cache_key
692 self.cache_key = cache_key
691 self.cache_args = cache_args
693 self.cache_args = cache_args
692 self.cache_active = False
694 self.cache_active = False
693
695
694 def __repr__(self):
696 def __repr__(self):
695 return "<%s('%s:%s')>" % (self.__class__.__name__,
697 return "<%s('%s:%s')>" % (self.__class__.__name__,
696 self.cache_id, self.cache_key)
698 self.cache_id, self.cache_key)
697
699
698 class DbMigrateVersion(Base):
700 class DbMigrateVersion(Base):
699 __tablename__ = 'db_migrate_version'
701 __tablename__ = 'db_migrate_version'
700 __table_args__ = {'extend_existing':True}
702 __table_args__ = {'extend_existing':True}
701 repository_id = Column('repository_id', String(250), primary_key=True)
703 repository_id = Column('repository_id', String(250), primary_key=True)
702 repository_path = Column('repository_path', Text)
704 repository_path = Column('repository_path', Text)
703 version = Column('version', Integer)
705 version = Column('version', Integer)
General Comments 0
You need to be logged in to leave comments. Login now