##// END OF EJS Templates
fixes #188 - relationship delete of repo_to_perm entry on user removal
marcink -
r1325:89ff3e30 beta
parent child Browse files
Show More
@@ -1,544 +1,545 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 from datetime import date
29 from datetime import date
30
30
31 from sqlalchemy import *
31 from sqlalchemy import *
32 from sqlalchemy.exc import DatabaseError
32 from sqlalchemy.exc import DatabaseError
33 from sqlalchemy.orm import relationship, backref
33 from sqlalchemy.orm import relationship, backref
34 from sqlalchemy.orm.interfaces import MapperExtension
34 from sqlalchemy.orm.interfaces import MapperExtension
35
35
36 from rhodecode.lib import str2bool
36 from rhodecode.lib import str2bool
37 from rhodecode.model.meta import Base, Session
37 from rhodecode.model.meta import Base, Session
38 from rhodecode.model.caching_query import FromCache
38 from rhodecode.model.caching_query import FromCache
39
39
40 log = logging.getLogger(__name__)
40 log = logging.getLogger(__name__)
41
41
42 #==============================================================================
42 #==============================================================================
43 # MAPPER EXTENSIONS
43 # MAPPER EXTENSIONS
44 #==============================================================================
44 #==============================================================================
45
45
46 class RepositoryMapper(MapperExtension):
46 class RepositoryMapper(MapperExtension):
47 def after_update(self, mapper, connection, instance):
47 def after_update(self, mapper, connection, instance):
48 pass
48 pass
49
49
50
50
51 class RhodeCodeSettings(Base):
51 class RhodeCodeSettings(Base):
52 __tablename__ = 'rhodecode_settings'
52 __tablename__ = 'rhodecode_settings'
53 __table_args__ = (UniqueConstraint('app_settings_name'), {'useexisting':True})
53 __table_args__ = (UniqueConstraint('app_settings_name'), {'useexisting':True})
54 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
54 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
55 app_settings_name = Column("app_settings_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
55 app_settings_name = Column("app_settings_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
56 app_settings_value = Column("app_settings_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
56 app_settings_value = Column("app_settings_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
57
57
58 def __init__(self, k='', v=''):
58 def __init__(self, k='', v=''):
59 self.app_settings_name = k
59 self.app_settings_name = k
60 self.app_settings_value = v
60 self.app_settings_value = v
61
61
62 def __repr__(self):
62 def __repr__(self):
63 return "<%s('%s:%s')>" % (self.__class__.__name__,
63 return "<%s('%s:%s')>" % (self.__class__.__name__,
64 self.app_settings_name, self.app_settings_value)
64 self.app_settings_name, self.app_settings_value)
65
65
66
66
67 @classmethod
67 @classmethod
68 def get_by_name(cls, ldap_key):
68 def get_by_name(cls, ldap_key):
69 return Session.query(cls)\
69 return Session.query(cls)\
70 .filter(cls.app_settings_name == ldap_key).scalar()
70 .filter(cls.app_settings_name == ldap_key).scalar()
71
71
72 @classmethod
72 @classmethod
73 def get_app_settings(cls, cache=False):
73 def get_app_settings(cls, cache=False):
74
74
75 ret = Session.query(cls)
75 ret = Session.query(cls)
76
76
77 if cache:
77 if cache:
78 ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
78 ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
79
79
80 if not ret:
80 if not ret:
81 raise Exception('Could not get application settings !')
81 raise Exception('Could not get application settings !')
82 settings = {}
82 settings = {}
83 for each in ret:
83 for each in ret:
84 settings['rhodecode_' + each.app_settings_name] = \
84 settings['rhodecode_' + each.app_settings_name] = \
85 each.app_settings_value
85 each.app_settings_value
86
86
87 return settings
87 return settings
88
88
89 @classmethod
89 @classmethod
90 def get_ldap_settings(cls, cache=False):
90 def get_ldap_settings(cls, cache=False):
91 ret = Session.query(cls)\
91 ret = Session.query(cls)\
92 .filter(cls.app_settings_name.startswith('ldap_'))\
92 .filter(cls.app_settings_name.startswith('ldap_'))\
93 .all()
93 .all()
94 fd = {}
94 fd = {}
95 for row in ret:
95 for row in ret:
96 fd.update({row.app_settings_name:row.app_settings_value})
96 fd.update({row.app_settings_name:row.app_settings_value})
97 return fd
97 return fd
98
98
99
99
100 class RhodeCodeUi(Base):
100 class RhodeCodeUi(Base):
101 __tablename__ = 'rhodecode_ui'
101 __tablename__ = 'rhodecode_ui'
102 __table_args__ = {'useexisting':True}
102 __table_args__ = {'useexisting':True}
103 ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
103 ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
104 ui_section = Column("ui_section", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
104 ui_section = Column("ui_section", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
105 ui_key = Column("ui_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
105 ui_key = Column("ui_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
106 ui_value = Column("ui_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
106 ui_value = Column("ui_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
107 ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
107 ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
108
108
109
109
110 class User(Base):
110 class User(Base):
111 __tablename__ = 'users'
111 __tablename__ = 'users'
112 __table_args__ = (UniqueConstraint('username'), UniqueConstraint('email'), {'useexisting':True})
112 __table_args__ = (UniqueConstraint('username'), UniqueConstraint('email'), {'useexisting':True})
113 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
113 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
114 username = Column("username", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
114 username = Column("username", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
115 password = Column("password", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
115 password = Column("password", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
116 active = Column("active", Boolean(), nullable=True, unique=None, default=None)
116 active = Column("active", Boolean(), nullable=True, unique=None, default=None)
117 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
117 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
118 name = Column("name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
118 name = Column("name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
119 lastname = Column("lastname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
119 lastname = Column("lastname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
120 email = Column("email", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
120 email = Column("email", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
121 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
121 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
122 ldap_dn = Column("ldap_dn", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
122 ldap_dn = Column("ldap_dn", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
123 api_key = Column("api_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
123 api_key = Column("api_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
124
124
125 user_log = relationship('UserLog', cascade='all')
125 user_log = relationship('UserLog', cascade='all')
126 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
126 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
127
127
128 repositories = relationship('Repository')
128 repositories = relationship('Repository')
129 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
129 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
130 repo_to_perm = relationship('RepoToPerm', primaryjoin='RepoToPerm.user_id==User.user_id', cascade='all')
130
131
131 group_member = relationship('UsersGroupMember', cascade='all')
132 group_member = relationship('UsersGroupMember', cascade='all')
132
133
133 @property
134 @property
134 def full_contact(self):
135 def full_contact(self):
135 return '%s %s <%s>' % (self.name, self.lastname, self.email)
136 return '%s %s <%s>' % (self.name, self.lastname, self.email)
136
137
137 @property
138 @property
138 def short_contact(self):
139 def short_contact(self):
139 return '%s %s' % (self.name, self.lastname)
140 return '%s %s' % (self.name, self.lastname)
140
141
141
142
142 @property
143 @property
143 def is_admin(self):
144 def is_admin(self):
144 return self.admin
145 return self.admin
145
146
146 def __repr__(self):
147 def __repr__(self):
147 return "<%s('id:%s:%s')>" % (self.__class__.__name__,
148 return "<%s('id:%s:%s')>" % (self.__class__.__name__,
148 self.user_id, self.username)
149 self.user_id, self.username)
149
150
150 @classmethod
151 @classmethod
151 def by_username(cls, username):
152 def by_username(cls, username):
152 return Session.query(cls).filter(cls.username == username).one()
153 return Session.query(cls).filter(cls.username == username).one()
153
154
154
155
155 def update_lastlogin(self):
156 def update_lastlogin(self):
156 """Update user lastlogin"""
157 """Update user lastlogin"""
157
158
158 try:
159 try:
159 session = Session.object_session(self)
160 session = Session.object_session(self)
160 self.last_login = datetime.datetime.now()
161 self.last_login = datetime.datetime.now()
161 session.add(self)
162 session.add(self)
162 session.commit()
163 session.commit()
163 log.debug('updated user %s lastlogin', self.username)
164 log.debug('updated user %s lastlogin', self.username)
164 except (DatabaseError,):
165 except (DatabaseError,):
165 session.rollback()
166 session.rollback()
166
167
167
168
168 class UserLog(Base):
169 class UserLog(Base):
169 __tablename__ = 'user_logs'
170 __tablename__ = 'user_logs'
170 __table_args__ = {'useexisting':True}
171 __table_args__ = {'useexisting':True}
171 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
172 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
172 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
173 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
173 repository_id = Column("repository_id", Integer(length=None, convert_unicode=False, assert_unicode=None), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
174 repository_id = Column("repository_id", Integer(length=None, convert_unicode=False, assert_unicode=None), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
174 repository_name = Column("repository_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
175 repository_name = Column("repository_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
175 user_ip = Column("user_ip", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
176 user_ip = Column("user_ip", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
176 action = Column("action", UnicodeText(length=1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
177 action = Column("action", UnicodeText(length=1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
177 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
178 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
178
179
179 @property
180 @property
180 def action_as_day(self):
181 def action_as_day(self):
181 return date(*self.action_date.timetuple()[:3])
182 return date(*self.action_date.timetuple()[:3])
182
183
183 user = relationship('User')
184 user = relationship('User')
184 repository = relationship('Repository')
185 repository = relationship('Repository')
185
186
186
187
187 class UsersGroup(Base):
188 class UsersGroup(Base):
188 __tablename__ = 'users_groups'
189 __tablename__ = 'users_groups'
189 __table_args__ = {'useexisting':True}
190 __table_args__ = {'useexisting':True}
190
191
191 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
192 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
192 users_group_name = Column("users_group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
193 users_group_name = Column("users_group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
193 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
194 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
194
195
195 members = relationship('UsersGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
196 members = relationship('UsersGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
196
197
197
198
198 @classmethod
199 @classmethod
199 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
200 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
200 if case_insensitive:
201 if case_insensitive:
201 gr = Session.query(cls)\
202 gr = Session.query(cls)\
202 .filter(cls.users_group_name.ilike(group_name))
203 .filter(cls.users_group_name.ilike(group_name))
203 else:
204 else:
204 gr = Session.query(UsersGroup)\
205 gr = Session.query(UsersGroup)\
205 .filter(UsersGroup.users_group_name == group_name)
206 .filter(UsersGroup.users_group_name == group_name)
206 if cache:
207 if cache:
207 gr = gr.options(FromCache("sql_cache_short",
208 gr = gr.options(FromCache("sql_cache_short",
208 "get_user_%s" % group_name))
209 "get_user_%s" % group_name))
209 return gr.scalar()
210 return gr.scalar()
210
211
211 class UsersGroupMember(Base):
212 class UsersGroupMember(Base):
212 __tablename__ = 'users_groups_members'
213 __tablename__ = 'users_groups_members'
213 __table_args__ = {'useexisting':True}
214 __table_args__ = {'useexisting':True}
214
215
215 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
216 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
216 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
217 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
217 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
218 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
218
219
219 user = relationship('User', lazy='joined')
220 user = relationship('User', lazy='joined')
220 users_group = relationship('UsersGroup')
221 users_group = relationship('UsersGroup')
221
222
222 def __init__(self, gr_id='', u_id=''):
223 def __init__(self, gr_id='', u_id=''):
223 self.users_group_id = gr_id
224 self.users_group_id = gr_id
224 self.user_id = u_id
225 self.user_id = u_id
225
226
226 class Repository(Base):
227 class Repository(Base):
227 __tablename__ = 'repositories'
228 __tablename__ = 'repositories'
228 __table_args__ = (UniqueConstraint('repo_name'), {'useexisting':True},)
229 __table_args__ = (UniqueConstraint('repo_name'), {'useexisting':True},)
229 __mapper_args__ = {'extension':RepositoryMapper()}
230 __mapper_args__ = {'extension':RepositoryMapper()}
230
231
231 repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
232 repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
232 repo_name = Column("repo_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
233 repo_name = Column("repo_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
233 clone_uri = Column("clone_uri", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
234 clone_uri = Column("clone_uri", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
234 repo_type = Column("repo_type", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default='hg')
235 repo_type = Column("repo_type", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default='hg')
235 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
236 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
236 private = Column("private", Boolean(), nullable=True, unique=None, default=None)
237 private = Column("private", Boolean(), nullable=True, unique=None, default=None)
237 enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
238 enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
238 enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
239 enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
239 description = Column("description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
240 description = Column("description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
240 created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
241 created_on = Column('created_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
241
242
242 fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
243 fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
243 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
244 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
244
245
245
246
246 user = relationship('User')
247 user = relationship('User')
247 fork = relationship('Repository', remote_side=repo_id)
248 fork = relationship('Repository', remote_side=repo_id)
248 group = relationship('Group')
249 group = relationship('Group')
249 repo_to_perm = relationship('RepoToPerm', cascade='all', order_by='RepoToPerm.repo_to_perm_id')
250 repo_to_perm = relationship('RepoToPerm', cascade='all', order_by='RepoToPerm.repo_to_perm_id')
250 users_group_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
251 users_group_to_perm = relationship('UsersGroupRepoToPerm', cascade='all')
251 stats = relationship('Statistics', cascade='all', uselist=False)
252 stats = relationship('Statistics', cascade='all', uselist=False)
252
253
253 followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all')
254 followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all')
254
255
255 logs = relationship('UserLog', cascade='all')
256 logs = relationship('UserLog', cascade='all')
256
257
257 def __repr__(self):
258 def __repr__(self):
258 return "<%s('%s:%s')>" % (self.__class__.__name__,
259 return "<%s('%s:%s')>" % (self.__class__.__name__,
259 self.repo_id, self.repo_name)
260 self.repo_id, self.repo_name)
260
261
261 @classmethod
262 @classmethod
262 def by_repo_name(cls, repo_name):
263 def by_repo_name(cls, repo_name):
263 return Session.query(cls).filter(cls.repo_name == repo_name).one()
264 return Session.query(cls).filter(cls.repo_name == repo_name).one()
264
265
265
266
266 @classmethod
267 @classmethod
267 def get_repo_forks(cls, repo_id):
268 def get_repo_forks(cls, repo_id):
268 return Session.query(cls).filter(Repository.fork_id == repo_id)
269 return Session.query(cls).filter(Repository.fork_id == repo_id)
269
270
270 @property
271 @property
271 def just_name(self):
272 def just_name(self):
272 return self.repo_name.split(os.sep)[-1]
273 return self.repo_name.split(os.sep)[-1]
273
274
274 @property
275 @property
275 def groups_with_parents(self):
276 def groups_with_parents(self):
276 groups = []
277 groups = []
277 if self.group is None:
278 if self.group is None:
278 return groups
279 return groups
279
280
280 cur_gr = self.group
281 cur_gr = self.group
281 groups.insert(0, cur_gr)
282 groups.insert(0, cur_gr)
282 while 1:
283 while 1:
283 gr = getattr(cur_gr, 'parent_group', None)
284 gr = getattr(cur_gr, 'parent_group', None)
284 cur_gr = cur_gr.parent_group
285 cur_gr = cur_gr.parent_group
285 if gr is None:
286 if gr is None:
286 break
287 break
287 groups.insert(0, gr)
288 groups.insert(0, gr)
288
289
289 return groups
290 return groups
290
291
291 @property
292 @property
292 def groups_and_repo(self):
293 def groups_and_repo(self):
293 return self.groups_with_parents, self.just_name
294 return self.groups_with_parents, self.just_name
294
295
295
296
296 class Group(Base):
297 class Group(Base):
297 __tablename__ = 'groups'
298 __tablename__ = 'groups'
298 __table_args__ = (UniqueConstraint('group_name'), {'useexisting':True},)
299 __table_args__ = (UniqueConstraint('group_name'), {'useexisting':True},)
299
300
300 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
301 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
301 group_name = Column("group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
302 group_name = Column("group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
302 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
303 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
303
304
304 parent_group = relationship('Group', remote_side=group_id)
305 parent_group = relationship('Group', remote_side=group_id)
305
306
306
307
307 def __init__(self, group_name='', parent_group=None):
308 def __init__(self, group_name='', parent_group=None):
308 self.group_name = group_name
309 self.group_name = group_name
309 self.parent_group = parent_group
310 self.parent_group = parent_group
310
311
311 def __repr__(self):
312 def __repr__(self):
312 return "<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
313 return "<%s('%s:%s')>" % (self.__class__.__name__, self.group_id,
313 self.group_name)
314 self.group_name)
314
315
315 @property
316 @property
316 def parents(self):
317 def parents(self):
317 groups = []
318 groups = []
318 if self.parent_group is None:
319 if self.parent_group is None:
319 return groups
320 return groups
320 cur_gr = self.parent_group
321 cur_gr = self.parent_group
321 groups.insert(0, cur_gr)
322 groups.insert(0, cur_gr)
322 while 1:
323 while 1:
323 gr = getattr(cur_gr, 'parent_group', None)
324 gr = getattr(cur_gr, 'parent_group', None)
324 cur_gr = cur_gr.parent_group
325 cur_gr = cur_gr.parent_group
325 if gr is None:
326 if gr is None:
326 break
327 break
327 groups.insert(0, gr)
328 groups.insert(0, gr)
328 return groups
329 return groups
329
330
330
331
331 @property
332 @property
332 def full_path(self):
333 def full_path(self):
333 return '/'.join([g.group_name for g in self.parents] +
334 return '/'.join([g.group_name for g in self.parents] +
334 [self.group_name])
335 [self.group_name])
335
336
336 @property
337 @property
337 def repositories(self):
338 def repositories(self):
338 return Session.query(Repository).filter(Repository.group == self).all()
339 return Session.query(Repository).filter(Repository.group == self).all()
339
340
340 class Permission(Base):
341 class Permission(Base):
341 __tablename__ = 'permissions'
342 __tablename__ = 'permissions'
342 __table_args__ = {'useexisting':True}
343 __table_args__ = {'useexisting':True}
343 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
344 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
344 permission_name = Column("permission_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
345 permission_name = Column("permission_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
345 permission_longname = Column("permission_longname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
346 permission_longname = Column("permission_longname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
346
347
347 def __repr__(self):
348 def __repr__(self):
348 return "<%s('%s:%s')>" % (self.__class__.__name__,
349 return "<%s('%s:%s')>" % (self.__class__.__name__,
349 self.permission_id, self.permission_name)
350 self.permission_id, self.permission_name)
350
351
351 @classmethod
352 @classmethod
352 def get_by_key(cls, key):
353 def get_by_key(cls, key):
353 return Session.query(cls).filter(cls.permission_name == key).scalar()
354 return Session.query(cls).filter(cls.permission_name == key).scalar()
354
355
355 class RepoToPerm(Base):
356 class RepoToPerm(Base):
356 __tablename__ = 'repo_to_perm'
357 __tablename__ = 'repo_to_perm'
357 __table_args__ = (UniqueConstraint('user_id', 'repository_id'), {'useexisting':True})
358 __table_args__ = (UniqueConstraint('user_id', 'repository_id'), {'useexisting':True})
358 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
359 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
359 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
360 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
360 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
361 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
361 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
362 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
362
363
363 user = relationship('User')
364 user = relationship('User')
364 permission = relationship('Permission')
365 permission = relationship('Permission')
365 repository = relationship('Repository')
366 repository = relationship('Repository')
366
367
367 class UserToPerm(Base):
368 class UserToPerm(Base):
368 __tablename__ = 'user_to_perm'
369 __tablename__ = 'user_to_perm'
369 __table_args__ = (UniqueConstraint('user_id', 'permission_id'), {'useexisting':True})
370 __table_args__ = (UniqueConstraint('user_id', 'permission_id'), {'useexisting':True})
370 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
371 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
371 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
372 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
372 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
373 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
373
374
374 user = relationship('User')
375 user = relationship('User')
375 permission = relationship('Permission')
376 permission = relationship('Permission')
376
377
377 @classmethod
378 @classmethod
378 def has_perm(cls, user_id, perm):
379 def has_perm(cls, user_id, perm):
379 if not isinstance(perm, Permission):
380 if not isinstance(perm, Permission):
380 raise Exception('perm needs to be an instance of Permission class')
381 raise Exception('perm needs to be an instance of Permission class')
381
382
382 return Session.query(cls).filter(cls.user_id == user_id)\
383 return Session.query(cls).filter(cls.user_id == user_id)\
383 .filter(cls.permission == perm).scalar() is not None
384 .filter(cls.permission == perm).scalar() is not None
384
385
385 @classmethod
386 @classmethod
386 def grant_perm(cls, user_id, perm):
387 def grant_perm(cls, user_id, perm):
387 if not isinstance(perm, Permission):
388 if not isinstance(perm, Permission):
388 raise Exception('perm needs to be an instance of Permission class')
389 raise Exception('perm needs to be an instance of Permission class')
389
390
390 new = cls()
391 new = cls()
391 new.user_id = user_id
392 new.user_id = user_id
392 new.permission = perm
393 new.permission = perm
393 try:
394 try:
394 Session.add(new)
395 Session.add(new)
395 Session.commit()
396 Session.commit()
396 except:
397 except:
397 Session.rollback()
398 Session.rollback()
398
399
399
400
400 @classmethod
401 @classmethod
401 def revoke_perm(cls, user_id, perm):
402 def revoke_perm(cls, user_id, perm):
402 if not isinstance(perm, Permission):
403 if not isinstance(perm, Permission):
403 raise Exception('perm needs to be an instance of Permission class')
404 raise Exception('perm needs to be an instance of Permission class')
404
405
405 try:
406 try:
406 Session.query(cls).filter(cls.user_id == user_id)\
407 Session.query(cls).filter(cls.user_id == user_id)\
407 .filter(cls.permission == perm).delete()
408 .filter(cls.permission == perm).delete()
408 Session.commit()
409 Session.commit()
409 except:
410 except:
410 Session.rollback()
411 Session.rollback()
411
412
412 class UsersGroupRepoToPerm(Base):
413 class UsersGroupRepoToPerm(Base):
413 __tablename__ = 'users_group_repo_to_perm'
414 __tablename__ = 'users_group_repo_to_perm'
414 __table_args__ = (UniqueConstraint('users_group_id', 'permission_id'), {'useexisting':True})
415 __table_args__ = (UniqueConstraint('users_group_id', 'permission_id'), {'useexisting':True})
415 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
416 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
416 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
417 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
417 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
418 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
418 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
419 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
419
420
420 users_group = relationship('UsersGroup')
421 users_group = relationship('UsersGroup')
421 permission = relationship('Permission')
422 permission = relationship('Permission')
422 repository = relationship('Repository')
423 repository = relationship('Repository')
423
424
424
425
425 class UsersGroupToPerm(Base):
426 class UsersGroupToPerm(Base):
426 __tablename__ = 'users_group_to_perm'
427 __tablename__ = 'users_group_to_perm'
427 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
428 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
428 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
429 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
429 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
430 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
430
431
431 users_group = relationship('UsersGroup')
432 users_group = relationship('UsersGroup')
432 permission = relationship('Permission')
433 permission = relationship('Permission')
433
434
434
435
435 @classmethod
436 @classmethod
436 def has_perm(cls, users_group_id, perm):
437 def has_perm(cls, users_group_id, perm):
437 if not isinstance(perm, Permission):
438 if not isinstance(perm, Permission):
438 raise Exception('perm needs to be an instance of Permission class')
439 raise Exception('perm needs to be an instance of Permission class')
439
440
440 return Session.query(cls).filter(cls.users_group_id ==
441 return Session.query(cls).filter(cls.users_group_id ==
441 users_group_id)\
442 users_group_id)\
442 .filter(cls.permission == perm)\
443 .filter(cls.permission == perm)\
443 .scalar() is not None
444 .scalar() is not None
444
445
445 @classmethod
446 @classmethod
446 def grant_perm(cls, users_group_id, perm):
447 def grant_perm(cls, users_group_id, perm):
447 if not isinstance(perm, Permission):
448 if not isinstance(perm, Permission):
448 raise Exception('perm needs to be an instance of Permission class')
449 raise Exception('perm needs to be an instance of Permission class')
449
450
450 new = cls()
451 new = cls()
451 new.users_group_id = users_group_id
452 new.users_group_id = users_group_id
452 new.permission = perm
453 new.permission = perm
453 try:
454 try:
454 Session.add(new)
455 Session.add(new)
455 Session.commit()
456 Session.commit()
456 except:
457 except:
457 Session.rollback()
458 Session.rollback()
458
459
459
460
460 @classmethod
461 @classmethod
461 def revoke_perm(cls, users_group_id, perm):
462 def revoke_perm(cls, users_group_id, perm):
462 if not isinstance(perm, Permission):
463 if not isinstance(perm, Permission):
463 raise Exception('perm needs to be an instance of Permission class')
464 raise Exception('perm needs to be an instance of Permission class')
464
465
465 try:
466 try:
466 Session.query(cls).filter(cls.users_group_id == users_group_id)\
467 Session.query(cls).filter(cls.users_group_id == users_group_id)\
467 .filter(cls.permission == perm).delete()
468 .filter(cls.permission == perm).delete()
468 Session.commit()
469 Session.commit()
469 except:
470 except:
470 Session.rollback()
471 Session.rollback()
471
472
472
473
473 class GroupToPerm(Base):
474 class GroupToPerm(Base):
474 __tablename__ = 'group_to_perm'
475 __tablename__ = 'group_to_perm'
475 __table_args__ = (UniqueConstraint('group_id', 'permission_id'), {'useexisting':True})
476 __table_args__ = (UniqueConstraint('group_id', 'permission_id'), {'useexisting':True})
476
477
477 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
478 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
478 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
479 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
479 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
480 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
480 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
481 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
481
482
482 user = relationship('User')
483 user = relationship('User')
483 permission = relationship('Permission')
484 permission = relationship('Permission')
484 group = relationship('Group')
485 group = relationship('Group')
485
486
486 class Statistics(Base):
487 class Statistics(Base):
487 __tablename__ = 'statistics'
488 __tablename__ = 'statistics'
488 __table_args__ = (UniqueConstraint('repository_id'), {'useexisting':True})
489 __table_args__ = (UniqueConstraint('repository_id'), {'useexisting':True})
489 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
490 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
490 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
491 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
491 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
492 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
492 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
493 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
493 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
494 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
494 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
495 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
495
496
496 repository = relationship('Repository', single_parent=True)
497 repository = relationship('Repository', single_parent=True)
497
498
498 class UserFollowing(Base):
499 class UserFollowing(Base):
499 __tablename__ = 'user_followings'
500 __tablename__ = 'user_followings'
500 __table_args__ = (UniqueConstraint('user_id', 'follows_repository_id'),
501 __table_args__ = (UniqueConstraint('user_id', 'follows_repository_id'),
501 UniqueConstraint('user_id', 'follows_user_id')
502 UniqueConstraint('user_id', 'follows_user_id')
502 , {'useexisting':True})
503 , {'useexisting':True})
503
504
504 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
505 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
505 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
506 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
506 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
507 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
507 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
508 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
508 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
509 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
509
510
510 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
511 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
511
512
512 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
513 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
513 follows_repository = relationship('Repository', order_by='Repository.repo_name')
514 follows_repository = relationship('Repository', order_by='Repository.repo_name')
514
515
515
516
516
517
517 @classmethod
518 @classmethod
518 def get_repo_followers(cls, repo_id):
519 def get_repo_followers(cls, repo_id):
519 return Session.query(cls).filter(cls.follows_repo_id == repo_id)
520 return Session.query(cls).filter(cls.follows_repo_id == repo_id)
520
521
521 class CacheInvalidation(Base):
522 class CacheInvalidation(Base):
522 __tablename__ = 'cache_invalidation'
523 __tablename__ = 'cache_invalidation'
523 __table_args__ = (UniqueConstraint('cache_key'), {'useexisting':True})
524 __table_args__ = (UniqueConstraint('cache_key'), {'useexisting':True})
524 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
525 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
525 cache_key = Column("cache_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
526 cache_key = Column("cache_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
526 cache_args = Column("cache_args", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
527 cache_args = Column("cache_args", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
527 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
528 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
528
529
529
530
530 def __init__(self, cache_key, cache_args=''):
531 def __init__(self, cache_key, cache_args=''):
531 self.cache_key = cache_key
532 self.cache_key = cache_key
532 self.cache_args = cache_args
533 self.cache_args = cache_args
533 self.cache_active = False
534 self.cache_active = False
534
535
535 def __repr__(self):
536 def __repr__(self):
536 return "<%s('%s:%s')>" % (self.__class__.__name__,
537 return "<%s('%s:%s')>" % (self.__class__.__name__,
537 self.cache_id, self.cache_key)
538 self.cache_id, self.cache_key)
538
539
539 class DbMigrateVersion(Base):
540 class DbMigrateVersion(Base):
540 __tablename__ = 'db_migrate_version'
541 __tablename__ = 'db_migrate_version'
541 __table_args__ = {'useexisting':True}
542 __table_args__ = {'useexisting':True}
542 repository_id = Column('repository_id', String(250), primary_key=True)
543 repository_id = Column('repository_id', String(250), primary_key=True)
543 repository_path = Column('repository_path', Text)
544 repository_path = Column('repository_path', Text)
544 version = Column('version', Integer)
545 version = Column('version', Integer)
General Comments 0
You need to be logged in to leave comments. Login now