##// END OF EJS Templates
Models code cleanups
marcink -
r759:a7f50911 beta
parent child Browse files
Show More
@@ -1,32 +1,57 b''
1 """The application's model objects"""
1 # -*- coding: utf-8 -*-
2 """
3 package.rhodecode.model.__init__
4 ~~~~~~~~~~~~~~
5 The application's model objects
6
7 :created_on: Nov 25, 2010
8 :author: marcink
9 :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
10 :license: GPLv3, see COPYING for more details.
11
12
13 :example:
14 from paste.deploy import appconfig
15 from pylons import config
16 from sqlalchemy import engine_from_config
17 from rhodecode.config.environment import load_environment
18
19 conf = appconfig('config:development.ini', relative_to = './../../')
20 load_environment(conf.global_conf, conf.local_conf)
21
22 engine = engine_from_config(config, 'sqlalchemy.')
23 init_model(engine)
24 #RUN YOUR CODE HERE
25
26 """
27 # This program is free software; you can redistribute it and/or
28 # modify it under the terms of the GNU General Public License
29 # as published by the Free Software Foundation; version 2
30 # of the License or (at your opinion) any later version of the license.
31 #
32 # This program is distributed in the hope that it will be useful,
33 # but WITHOUT ANY WARRANTY; without even the implied warranty of
34 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 # GNU General Public License for more details.
36 #
37 # You should have received a copy of the GNU General Public License
38 # along with this program; if not, write to the Free Software
39 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
40 # MA 02110-1301, USA.
41
2 42 import logging
3 43 from rhodecode.model import meta
4 44 log = logging.getLogger(__name__)
5 45
6 46 def init_model(engine):
7 47 """Call me before using any of the tables or classes in the model"""
8 log.info("INITIALIZING DB MODELS")
48 log.info("initializing db models for %s", engine)
9 49 meta.Base.metadata.bind = engine
10 #meta.Base2.metadata.bind = engine2
11
12 #THIS IS A TEST FOR EXECUTING SCRIPT AND LOAD PYLONS APPLICATION GLOBALS
13 #from paste.deploy import appconfig
14 #from pylons import config
15 #from sqlalchemy import engine_from_config
16 #from rhodecode.config.environment import load_environment
17 #
18 #conf = appconfig('config:development.ini', relative_to = './../../')
19 #load_environment(conf.global_conf, conf.local_conf)
20 #
21 #engine = engine_from_config(config, 'sqlalchemy.')
22 #init_model(engine)
23 # DO SOMETHING
24
25 50
26 51 class BaseModel(object):
27 52
28 53 def __init__(self, sa=None):
29 54 if sa is not None:
30 55 self.sa = sa
31 56 else:
32 57 self.sa = meta.Session()
@@ -1,187 +1,215 b''
1 from rhodecode.model.meta import Base
1 # -*- coding: utf-8 -*-
2 """
3 package.rhodecode.model.db
4 ~~~~~~~~~~~~~~
5
6 Database Models for RhodeCode
7 :created_on: Apr 08, 2010
8 :author: marcink
9 :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
10 :license: GPLv3, see COPYING for more details.
11 """
12 # This program is free software; you can redistribute it and/or
13 # modify it under the terms of the GNU General Public License
14 # as published by the Free Software Foundation; version 2
15 # of the License or (at your opinion) any later version of the license.
16 #
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # GNU General Public License for more details.
21 #
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
25 # MA 02110-1301, USA.
26 import logging
27 import datetime
28
2 29 from sqlalchemy import *
30 from sqlalchemy.exc import DatabaseError
3 31 from sqlalchemy.orm import relation, backref
4 32 from sqlalchemy.orm.session import Session
5 from vcs.utils.lazy import LazyProperty
6 import logging
33
34 from rhodecode.model.meta import Base
35
7 36 log = logging.getLogger(__name__)
8 37
9 38 class RhodeCodeSettings(Base):
10 39 __tablename__ = 'rhodecode_settings'
11 40 __table_args__ = (UniqueConstraint('app_settings_name'), {'useexisting':True})
12 41 app_settings_id = Column("app_settings_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
13 42 app_settings_name = Column("app_settings_name", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
14 43 app_settings_value = Column("app_settings_value", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
15 44
16 45 def __init__(self, k, v):
17 46 self.app_settings_name = k
18 47 self.app_settings_value = v
19 48
20 49 def __repr__(self):
21 50 return "<RhodeCodeSetting('%s:%s')>" % (self.app_settings_name,
22 51 self.app_settings_value)
23 52
24 53 class RhodeCodeUi(Base):
25 54 __tablename__ = 'rhodecode_ui'
26 55 __table_args__ = {'useexisting':True}
27 56 ui_id = Column("ui_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
28 57 ui_section = Column("ui_section", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
29 58 ui_key = Column("ui_key", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
30 59 ui_value = Column("ui_value", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
31 60 ui_active = Column("ui_active", BOOLEAN(), nullable=True, unique=None, default=True)
32 61
33 62
34 63 class User(Base):
35 64 __tablename__ = 'users'
36 65 __table_args__ = (UniqueConstraint('username'), UniqueConstraint('email'), {'useexisting':True})
37 66 user_id = Column("user_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
38 67 username = Column("username", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
39 68 password = Column("password", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
40 69 active = Column("active", BOOLEAN(), nullable=True, unique=None, default=None)
41 70 admin = Column("admin", BOOLEAN(), nullable=True, unique=None, default=False)
42 71 name = Column("name", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
43 72 lastname = Column("lastname", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
44 73 email = Column("email", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
45 74 last_login = Column("last_login", DATETIME(timezone=False), nullable=True, unique=None, default=None)
46 75 is_ldap = Column("is_ldap", BOOLEAN(), nullable=False, unique=None, default=False)
47 76
48 77 user_log = relation('UserLog', cascade='all')
49 78 user_perms = relation('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
50 79
51 80 repositories = relation('Repository')
52 81 user_followers = relation('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
53 82
54 @LazyProperty
83 @property
55 84 def full_contact(self):
56 85 return '%s %s <%s>' % (self.name, self.lastname, self.email)
57 86
58 87 def __repr__(self):
59 88 return "<User('id:%s:%s')>" % (self.user_id, self.username)
60 89
61 90 def update_lastlogin(self):
62 91 """Update user lastlogin"""
63 import datetime
64 92
65 93 try:
66 94 session = Session.object_session(self)
67 95 self.last_login = datetime.datetime.now()
68 96 session.add(self)
69 97 session.commit()
70 98 log.debug('updated user %s lastlogin', self.username)
71 except Exception:
99 except (DatabaseError,):
72 100 session.rollback()
73 101
74 102
75 103 class UserLog(Base):
76 104 __tablename__ = 'user_logs'
77 105 __table_args__ = {'useexisting':True}
78 106 user_log_id = Column("user_log_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
79 107 user_id = Column("user_id", INTEGER(), ForeignKey(u'users.user_id'), nullable=False, unique=None, default=None)
80 108 repository_id = Column("repository_id", INTEGER(length=None, convert_unicode=False, assert_unicode=None), ForeignKey(u'repositories.repo_id'), nullable=False, unique=None, default=None)
81 109 repository_name = Column("repository_name", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
82 110 user_ip = Column("user_ip", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
83 111 action = Column("action", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
84 112 action_date = Column("action_date", DATETIME(timezone=False), nullable=True, unique=None, default=None)
85 113
86 114 user = relation('User')
87 115 repository = relation('Repository')
88 116
89 117 class Repository(Base):
90 118 __tablename__ = 'repositories'
91 119 __table_args__ = (UniqueConstraint('repo_name'), {'useexisting':True},)
92 120 repo_id = Column("repo_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
93 121 repo_name = Column("repo_name", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
94 122 repo_type = Column("repo_type", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default=None)
95 123 user_id = Column("user_id", INTEGER(), ForeignKey(u'users.user_id'), nullable=False, unique=False, default=None)
96 124 private = Column("private", BOOLEAN(), nullable=True, unique=None, default=None)
97 125 description = Column("description", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
98 126 fork_id = Column("fork_id", INTEGER(), ForeignKey(u'repositories.repo_id'), nullable=True, unique=False, default=None)
99 127
100 128 user = relation('User')
101 129 fork = relation('Repository', remote_side=repo_id)
102 130 repo_to_perm = relation('RepoToPerm', cascade='all')
103 131 stats = relation('Statistics', cascade='all', uselist=False)
104 132
105 133 repo_followers = relation('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all')
106 134
107 135
108 136 def __repr__(self):
109 137 return "<Repository('%s:%s')>" % (self.repo_id, self.repo_name)
110 138
111 139 class Permission(Base):
112 140 __tablename__ = 'permissions'
113 141 __table_args__ = {'useexisting':True}
114 142 permission_id = Column("permission_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
115 143 permission_name = Column("permission_name", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
116 144 permission_longname = Column("permission_longname", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
117 145
118 146 def __repr__(self):
119 147 return "<Permission('%s:%s')>" % (self.permission_id, self.permission_name)
120 148
121 149 class RepoToPerm(Base):
122 150 __tablename__ = 'repo_to_perm'
123 151 __table_args__ = (UniqueConstraint('user_id', 'repository_id'), {'useexisting':True})
124 152 repo_to_perm_id = Column("repo_to_perm_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
125 153 user_id = Column("user_id", INTEGER(), ForeignKey(u'users.user_id'), nullable=False, unique=None, default=None)
126 154 permission_id = Column("permission_id", INTEGER(), ForeignKey(u'permissions.permission_id'), nullable=False, unique=None, default=None)
127 155 repository_id = Column("repository_id", INTEGER(), ForeignKey(u'repositories.repo_id'), nullable=False, unique=None, default=None)
128 156
129 157 user = relation('User')
130 158 permission = relation('Permission')
131 159 repository = relation('Repository')
132 160
133 161 class UserToPerm(Base):
134 162 __tablename__ = 'user_to_perm'
135 163 __table_args__ = (UniqueConstraint('user_id', 'permission_id'), {'useexisting':True})
136 164 user_to_perm_id = Column("user_to_perm_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
137 165 user_id = Column("user_id", INTEGER(), ForeignKey(u'users.user_id'), nullable=False, unique=None, default=None)
138 166 permission_id = Column("permission_id", INTEGER(), ForeignKey(u'permissions.permission_id'), nullable=False, unique=None, default=None)
139 167
140 168 user = relation('User')
141 169 permission = relation('Permission')
142 170
143 171 class Statistics(Base):
144 172 __tablename__ = 'statistics'
145 173 __table_args__ = (UniqueConstraint('repository_id'), {'useexisting':True})
146 174 stat_id = Column("stat_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
147 175 repository_id = Column("repository_id", INTEGER(), ForeignKey(u'repositories.repo_id'), nullable=False, unique=True, default=None)
148 176 stat_on_revision = Column("stat_on_revision", INTEGER(), nullable=False)
149 177 commit_activity = Column("commit_activity", BLOB(), nullable=False)#JSON data
150 178 commit_activity_combined = Column("commit_activity_combined", BLOB(), nullable=False)#JSON data
151 179 languages = Column("languages", BLOB(), nullable=False)#JSON data
152 180
153 181 repository = relation('Repository', single_parent=True)
154 182
155 183 class UserFollowing(Base):
156 184 __tablename__ = 'user_followings'
157 185 __table_args__ = (UniqueConstraint('user_id', 'follows_repository_id'),
158 186 UniqueConstraint('user_id', 'follows_user_id')
159 187 , {'useexisting':True})
160 188
161 189 user_following_id = Column("user_following_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
162 190 user_id = Column("user_id", INTEGER(), ForeignKey(u'users.user_id'), nullable=False, unique=None, default=None)
163 191 follows_repo_id = Column("follows_repository_id", INTEGER(), ForeignKey(u'repositories.repo_id'), nullable=True, unique=None, default=None)
164 192 follows_user_id = Column("follows_user_id", INTEGER(), ForeignKey(u'users.user_id'), nullable=True, unique=None, default=None)
165 193
166 194 user = relation('User', primaryjoin='User.user_id==UserFollowing.user_id')
167 195
168 196 follows_user = relation('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
169 197 follows_repository = relation('Repository')
170 198
171 199
172 200 class CacheInvalidation(Base):
173 201 __tablename__ = 'cache_invalidation'
174 202 __table_args__ = (UniqueConstraint('cache_key'), {'useexisting':True})
175 203 cache_id = Column("cache_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
176 204 cache_key = Column("cache_key", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
177 205 cache_args = Column("cache_args", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
178 206 cache_active = Column("cache_active", BOOLEAN(), nullable=True, unique=None, default=False)
179 207
180 208
181 209 def __init__(self, cache_key, cache_args=''):
182 210 self.cache_key = cache_key
183 211 self.cache_args = cache_args
184 212 self.cache_active = False
185 213
186 214 def __repr__(self):
187 215 return "<CacheInvalidation('%s:%s')>" % (self.cache_id, self.cache_key)
@@ -1,96 +1,101 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 # Model for permissions
4 # Copyright (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
1 # -*- coding: utf-8 -*-
2 """
3 package.rhodecode.model.permission
4 ~~~~~~~~~~~~~~
5 5
6 permissions model for RhodeCode
7 :created_on: Aug 20, 2010
8 :author: marcink
9 :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
10 :license: GPLv3, see COPYING for more details.
11 """
6 12 # This program is free software; you can redistribute it and/or
7 13 # modify it under the terms of the GNU General Public License
8 14 # as published by the Free Software Foundation; version 2
9 15 # of the License or (at your opinion) any later version of the license.
10 16 #
11 17 # This program is distributed in the hope that it will be useful,
12 18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 20 # GNU General Public License for more details.
15 21 #
16 22 # You should have received a copy of the GNU General Public License
17 23 # along with this program; if not, write to the Free Software
18 24 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 25 # MA 02110-1301, USA.
20 """
21 Created on Aug 20, 2010
22 Model for permissions
23 :author: marcink
24 """
26
27 import logging
28 import traceback
29
30 from sqlalchemy.exc import DatabaseError
25 31
26 32 from rhodecode.model import BaseModel
27 33 from rhodecode.model.db import User, Permission, UserToPerm, RepoToPerm
28 34 from rhodecode.model.caching_query import FromCache
29 import logging
30 import traceback
35
31 36 log = logging.getLogger(__name__)
32 37
33 38
34 39 class PermissionModel(BaseModel):
35 40
36 41 def get_permission(self, permission_id, cache=False):
37 42 perm = self.sa.query(Permission)
38 43 if cache:
39 44 perm = perm.options(FromCache("sql_cache_short",
40 45 "get_permission_%s" % permission_id))
41 46 return perm.get(permission_id)
42 47
43 48 def get_permission_by_name(self, name, cache=False):
44 49 perm = self.sa.query(Permission)\
45 50 .filter(Permission.permission_name == name)
46 51 if cache:
47 52 perm = perm.options(FromCache("sql_cache_short",
48 53 "get_permission_%s" % name))
49 54 return perm.scalar()
50 55
51 56 def update(self, form_result):
52 57 perm_user = self.sa.query(User)\
53 58 .filter(User.username == form_result['perm_user_name']).scalar()
54 59 u2p = self.sa.query(UserToPerm).filter(UserToPerm.user == perm_user).all()
55 60 if len(u2p) != 3:
56 61 raise Exception('Defined: %s should be 3 permissions for default'
57 62 ' user. This should not happen please verify'
58 63 ' your database' % len(u2p))
59 64
60 65 try:
61 66 #stage 1 change defaults
62 67 for p in u2p:
63 68 if p.permission.permission_name.startswith('repository.'):
64 69 p.permission = self.get_permission_by_name(
65 70 form_result['default_perm'])
66 71 self.sa.add(p)
67 72
68 73 if p.permission.permission_name.startswith('hg.register.'):
69 74 p.permission = self.get_permission_by_name(
70 75 form_result['default_register'])
71 76 self.sa.add(p)
72 77
73 78 if p.permission.permission_name.startswith('hg.create.'):
74 79 p.permission = self.get_permission_by_name(
75 80 form_result['default_create'])
76 81 self.sa.add(p)
77 82
78 83 #stage 2 update all default permissions for repos if checked
79 84 if form_result['overwrite_default'] == True:
80 85 for r2p in self.sa.query(RepoToPerm)\
81 86 .filter(RepoToPerm.user == perm_user).all():
82 87 r2p.permission = self.get_permission_by_name(
83 88 form_result['default_perm'])
84 89 self.sa.add(r2p)
85 90
86 91 #stage 3 set anonymous access
87 92 if perm_user.username == 'default':
88 93 perm_user.active = bool(form_result['anonymous'])
89 94 self.sa.add(perm_user)
90 95
91 96
92 97 self.sa.commit()
93 except:
98 except (DatabaseError,):
94 99 log.error(traceback.format_exc())
95 100 self.sa.rollback()
96 101 raise
General Comments 0
You need to be logged in to leave comments. Login now