/[glsr]/trunk/site/script.py
Gentoo

Contents of /trunk/site/script.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 162 - (show annotations) (download) (as text)
Sat Oct 22 06:11:00 2005 UTC (8 years, 10 months ago) by hadfield
File MIME type: text/x-python
File size: 11897 byte(s)
re-created the news section. moved news off of the front page and replaced it with the latest script additions.
1 # Copyright 2005 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
3 #
4
5 """The DB access module for the script and subscript table.
6
7 Implements all functions necessary for creating, modifying, and managing
8 scripts and subscripts.
9 """
10
11 __revision__ = "$Id$"
12 __authors__ = ["Scott Hadfield <hadfield@gentoo.org>",
13 "Ian Leitch <port001@gentoo.org>"]
14 __modulename__ = "script"
15
16 from time import strftime, gmtime
17 import types
18
19 from glsr.setup import config
20 from glsr.core.db.mysql import SQLdb
21
22 def create_script(submitter_id, name = "",
23 descr = "", version = "1.0", language = 0,
24 category = 0, body = "", changelog = ""):
25 """Add a new script to the database."""
26
27 sql_handle = SQLdb(config.db)
28
29 # Add the script to the database
30 sql_handle.query(
31 "INSERT INTO %(prefix)sscript " % {'prefix': config.db['prefix']} +
32 "(script_submitter_id, script_category_id, script_language_id," +
33 " script_rank, script_name, script_descr)" +
34 " VALUES (%s, %s, %s, 0, %s, %s)",
35 (submitter_id, category, language, name, descr), fetch = "none")
36
37 # Get the scripts id
38 results = sql_handle.query("SELECT LAST_INSERT_ID() as id", fetch = "one")
39
40 assert(results.has_key("id"))
41 subscript_id = create_subscript(results["id"], version, body, changelog)
42
43 return (results["id"], subscript_id)
44
45 def create_subscript(parent_id, version, body, changelog):
46 """Add a new subscript to the database."""
47
48 # FIXME: Default status should be based on the config.
49 status = "published"
50
51
52 sql_handle = SQLdb(config.db)
53
54 results = sql_handle.query(
55 "INSERT INTO %(prefix)ssubscript " % {'prefix': config.db['prefix']} +
56 "(subscript_parent_id, subscript_version, subscript_body," +
57 " subscript_changelog, subscript_date, subscript_status)" +
58 " VALUES (%s, %s, %s, %s, NOW(), %s)",
59 (parent_id, version, body, changelog, status), fetch = "one")
60
61 # Get the subscripts id
62 results = sql_handle.query("SELECT LAST_INSERT_ID() as id",
63 fetch = "one")
64 assert(results.has_key("id"))
65
66 return results["id"]
67
68 def list_subscripts(script_restrict = None, subscript_restrict = None):
69 """Returns a list of each script combined with its current subscript."""
70 pass
71
72 def _list_scripts(columns = None, constraints = None):
73 """Return selected columns from all rows in the script table.
74
75 This is copied from the user.list_all method.
76 """
77 # FIXME: Sanity checks on column names and contrainst keys.
78 # Without this we could have mysql injection attacks.
79
80 if columns is None:
81 return []
82 else:
83 columns = ", ".join(columns)
84
85 where_clause = ""
86 if constraints is not None:
87 where_clause = " AND ".join(["script_%s = %%s" % key
88 for key in constraints])
89 if where_clause != "":
90 where_clause = "WHERE " + where_clause
91 else:
92 constraints = {}
93
94 results = SQLdb(config.db).query(
95 "SELECT %(columns)s FROM %(prefix)sscript %(where)s" %
96 {'columns': columns, 'prefix': config.db['prefix'],
97 'where': where_clause}, constraints.values(), fetch="all")
98
99 return results
100
101 def list_scripts(script_columns = None, subscript_columns = None,
102 script_constraints = None, subscript_constraints = None,
103 get_subscript = True):
104 """Returns a list of each script combined with its current subscript."""
105
106 if script_columns != None:
107 if len(script_columns) == 0:
108 script_columns = ['*']
109 elif "script_id" not in script_columns:
110 script_columns.append("script_id")
111 else:
112 script_columns = ['*']
113
114 script_arr = _list_scripts(script_columns, script_constraints)
115
116 if not get_subscript:
117 return script_arr
118
119 retval = []
120 for record in script_arr:
121 script = Script(record["script_id"])
122 subscript = script.current()
123 subscript_record = subscript.get_columns(["*"])
124
125 for column, value in subscript_record.iteritems():
126 record.update({column: value})
127
128 retval.append(record)
129
130 return retval
131
132 def search(columns = None, terms = None):
133 """Search for scripts in the DB.
134
135 Terms should be a dictionary of (field, value) pairs. If 'value' is a
136 ListType then they will be OR'd
137 (i.e. field = value[0] OR field = value[1]...)
138
139 Searchable values include: language, category, status, name, descr,
140 submitter
141 """
142
143 # FIXME: Needs some more sanity checking on incoming columns and terms.
144 # Potential for mysql injection.
145
146 if columns is None:
147 return []
148 else:
149 columns = ", ".join(columns)
150
151 if terms is None:
152 return []
153
154 where_clause = __mk_query(["language", "category"], terms)
155 if where_clause != "":
156 where_clause = "WHERE " + where_clause
157
158 # FIXME: Use the columns variable instead of 'select *'
159 scripts = SQLdb(config.db).query(
160 "SELECT * FROM %(prefix)sscript %(where)s" %
161 {'columns': columns, 'prefix': config.db["prefix"],
162 'where': where_clause})
163
164 # FIXME: This won't work because submitter is not in the script table,
165 # submitter_id is. Thus we can't obtain a partial match on the
166 # submitter name so easily.
167 found = []
168 for script in scripts:
169 for key in ["name", "descr", "submitter"]:
170 if key in terms.keys():
171 if script["script_" + key].find(terms[key]) != -1:
172 found.append(script)
173
174 # Get the subscripts
175 where_clause = __mk_query(["status"], terms)
176 if where_clause != "":
177 where_clause = "AND " + where_clause
178
179 # Since 'found' will be modified in the loop, we need to copy it's size.
180 found_len = len(found)
181 for i in range(found_len):
182
183 qstr = ("SELECT subscript_version, subscript_date, subscript_status," +
184 " subscript_approvedby" +
185 "FROM %(prefix)ssubscript " % {'prefix': config.db["prefix"]} +
186 "WHERE status != 'draft'" +
187 " AND parent = %s " % found[i]["subscript_id"] +
188 where_clause)
189
190 if "current" in terms.keys():
191 subscript = SQLdb(config.db).query(qstr + " ORDER BY version",
192 fetch = "one")
193 found[i].update(subscript)
194
195 else:
196 subscripts = SQLdb(config.db).query(qstr, fetch = "all")
197
198 for subscript in subscripts[1:]:
199 found.append(found[i])
200 found[len(found)].update(subscript)
201
202 found[i].update(subscripts[0])
203
204 return found
205
206 def brief_listing(count):
207
208 qstr = ("SELECT script_id, user_alias, script_name " +
209 "FROM glsr_script, glsr_subscript, glsr_user " +
210 "WHERE script_id = subscript_parent_id" +
211 " AND subscript_status = 'published'" +
212 " AND script_submitter_id = user_id " +
213 "ORDER BY subscript_date DESC")
214 results = SQLdb(config.db).query(qstr)
215 return results[:count]
216
217 def listing(count):
218
219 qstr = ("SELECT script_id, user_alias, script_name, script_descr," +
220 " subscript_version, subscript_date " +
221 "FROM glsr_script, glsr_subscript, glsr_user " +
222 "WHERE script_id = subscript_parent_id" +
223 " AND subscript_status = 'published'" +
224 " AND script_submitter_id = user_id " +
225 "ORDER BY subscript_date DESC")
226 results = SQLdb(config.db).query(qstr)
227 return results[:count]
228
229 def __mk_query(fields, terms):
230
231 qstr = ""
232 for (key,value) in terms.items():
233 if key in fields:
234 if qstr != "":
235 qstr = qstr + " AND "
236 qstr = qstr + __mk_query_str(key, terms)
237
238 return qstr
239
240 def __mk_query_str(field, terms):
241
242 import string
243
244 qstr = field + " IN "
245 if type(terms[field]) == types.ListType:
246
247 if not len(terms[field]):
248 return ""
249
250 newlist = map(lambda x: "'%s'" % x, terms[field])
251 value = string.join(newlist, "," % field)
252
253 else:
254 value = terms[field]
255
256 return "%s (%s)" % (qstr, value)
257
258
259 class Script:
260 """Defines the get and set attributes for a Script."""
261
262 def __init__(self, script_id):
263
264 self._db = SQLdb(config.db)
265 self._script_id = script_id
266
267 def _get_attr(self, attr):
268 """Return the value of the specified attribute, or DB field."""
269
270 result = self._db.query(
271 "SELECT %(attr)s FROM %(prefix)sscript " %
272 {'attr': attr, 'prefix': config.db['prefix']} +
273 "WHERE script_id = %s", str(self._script_id), fetch='one')
274
275 if result != None:
276 return result[attr]
277
278 return None
279
280 def approve(self):
281 """Mark script as approved"""
282 self.current().approve()
283
284 def get_author(self):
285 """Return the script submitters username."""
286
287 from glsr.site import user
288 submitter_id = self._get_attr("script_submitter_id")
289 user_obj = user.User(submitter_id)
290 return user_obj.get_alias()
291
292 def get_category(self):
293 """Return the name of the category this script is in."""
294
295 from glsr.site import category
296 category_id = self._get_attr("script_category_id")
297 cat_obj = category.Category(category_id)
298 return cat_obj.name()
299
300 def get_language(self):
301 """Return the name of the language this script is written in."""
302 from glsr.site import language
303 language_id = self._get_attr("script_language_id")
304 lang_obj = language.Language(language_id)
305 return lang_obj.name()
306
307 def current(self):
308 """Returns the id of the current subscript."""
309
310 # FIXME: This returns most recent script, but should be stable as well.
311 # In other words, the newest script might be a draft or
312 # non-approved
313 result = self._db.query(
314 "SELECT subscript_id FROM %(prefix)ssubscript " %
315 {'prefix': config.db['prefix']} +
316 "WHERE subscript_parent_id = %s ORDER BY subscript_date DESC",
317 self._script_id, fetch='one')
318
319 assert(result is not None)
320
321 return Subscript(result["subscript_id"])
322
323 def get_columns(self, columns):
324
325 columns = ", ".join(columns)
326
327 result = self._db.query(
328 "SELECT %(columns)s FROM %(prefix)sscript " %
329 {'columns': columns, 'prefix': config.db['prefix']} +
330 "WHERE script_id = %s", self._script_id, fetch = "one")
331
332 assert(result is not None)
333
334 return result
335
336 def list_subscripts(self, constraint = None):
337 """Returns a list of all subscripts."""
338 pass
339
340 class Subscript:
341
342 def __init__(self, subscript_id):
343
344 self._db = SQLdb(config.db)
345 self._subscript_id = subscript_id
346
347 def get_columns(self, columns):
348
349 columns = ", ".join(columns)
350
351 result = self._db.query(
352 "SELECT %(columns)s FROM %(prefix)ssubscript " %
353 {'columns': columns, 'prefix': config.db['prefix']} +
354 "WHERE subscript_id = %s", self._subscript_id, fetch = "one")
355
356 assert(result is not None)
357
358 return result
359
360 def get_id(self):
361 return self._subscript_id
362
363 def modify(self, script_id, parent_id, details):
364 """Add a new subscript."""
365 pass
366
367 def approve(self):
368 """Mark script as approved."""
369 pass
370
371 def parent_id(self):
372 """Return the parent id for this subscript."""
373 pass

Properties

Name Value
svn:keywords Id

  ViewVC Help
Powered by ViewVC 1.1.20