/[glsr]/trunk/core/db/mysql.py
Gentoo

Contents of /trunk/core/db/mysql.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 177 - (show annotations) (download) (as text)
Sat Nov 5 21:34:50 2005 UTC (13 years ago) by hadfield
File MIME type: text/x-python
File size: 4713 byte(s)
simple code touch ups and minor bug fixes.
1 # Copyright 2004-2005 Ian Leitch
2 # Copyright 1999-2005 Gentoo Technologies, Inc.
3 # Distributed under the terms of the GNU General Public License v2
4 #
5
6 """The mysql glsr db wrapper."""
7
8 __revision__ = '$Id$'
9 __modulename__ = 'mysql'
10
11 import MySQLdb
12 from _mysql_exceptions import MySQLError, OperationalError
13 import types
14
15 #from Logging import logwrite
16 #from GLSRException import MySQLModuleError
17 #from Function import start_timer, stop_timer, eval_timer
18
19 # The default mysql port if none is specified
20 DEFAULT_PORT = 3306
21
22 class SQLdb:
23 """The mysql glsr db wrapper class."""
24
25 def __init__(self, parameters):
26 """Initialize the MySQL object.
27
28 'parameters' should be a dict containing the following variables:
29 host - The database host server
30 port - The port the database is running on. (optional)
31 user - The username to connect with
32 passwd - The password to connect with
33 db - The name of the database
34 """
35
36 self._db = None
37 self._cursor = None
38 self._args = None
39 self._query = None
40 self._parameters = parameters
41
42 # Set the port number appropriately
43 if not self._parameters.has_key("port") \
44 or not isinstance(self._parameters["port"], types.IntType):
45 self._parameters["port"] = DEFAULT_PORT
46
47 def __del__(self):
48 """The class destructor. Closes the connection and cursor objects."""
49 self.close()
50
51 def _connect(self):
52 """Connect to the mysql database."""
53
54 try:
55 # Don't reconnect if we already have an open connection
56 if self._db is None:
57
58 self._db = MySQLdb.connect(
59 host = self._parameters["host"],
60 port = self._parameters["port"],
61 user = self._parameters["user"],
62 passwd = self._parameters["passwd"],
63 db = self._parameters["db"])
64
65 if self._cursor is None:
66 self._cursor = self._db.cursor(MySQLdb.cursors.DictCursor)
67
68 except OperationalError, errmsg:
69 raise MySQLModuleError(
70 "Caught an OperationError exception from module 'MySQLdb'" +
71 ": '%s'" % errmsg)
72
73 def _init_query(self):
74 """Initialize the DB connection and execute the query."""
75
76 self._connect()
77
78 try:
79 self._cursor.execute(self._query, self._args)
80 self._db.commit()
81
82 except MySQLError, errmsg:
83 raise MySQLModuleError(
84 "Caught an MySQLError exception from module 'MySQLdb'%s",
85 "%s<br />\nQuery: %s<br />\nValues: %s" %
86 (errmsg, self._query, self._args))
87
88 def _get_result(self, fetch):
89 """Fetch the specified number of results."""
90
91 from types import IntType
92
93 retval = None
94
95 if fetch == "one":
96 retval = self._cursor.fetchone()
97
98 elif isinstance(fetch, IntType):
99 retval = self._cursor.fetchmany(fetch)
100
101 elif fetch == "none":
102 retval = None
103
104 else:
105 retval = self._cursor.fetchall()
106
107 return retval
108
109 def query(self, query, args = None, fetch = "all"):
110 """The base query method
111
112 Runs the specified query with 'args'.
113 Returns a list of dictionaries of {column: value} pairs.
114 Each dictionary in the list represents one record for the query.
115 e.g ({uid: 1043, name: Ian}, {uid: 3456, Scott})
116 """
117
118 self._query = query
119 self._args = args
120
121 #t_start = start_timer()
122
123 self._init_query()
124 result = self._get_result(fetch)
125
126 #logwrite("%s, Args: %s, Timing: %.5f(s)" %
127 # (self._query, self._args,
128 # eval_timer(t_start, stop_timer()))
129 # __modulename__, "Query")
130
131 return result
132
133 def close(self):
134 """Close the db connection."""
135
136 if self._cursor is not None:
137 self._cursor.close()
138 self._cursor = None
139
140 if self._db is not None:
141 self._db.close()
142 self._db = None
143
144 def rowcount(self):
145 """Returns the number of rows the last execute produced or affected."""
146
147 if self._cursor is not None:
148 return self._cursor.rowcount
149
150
151 # FIXME: This exception is only here until exception handling is properly setup
152 class MySQLModuleError(Exception): pass

Properties

Name Value
svn:keywords Id

  ViewVC Help
Powered by ViewVC 1.1.20