root / pykota / trunk / pykota / storages / mysqlstorage.py @ 2649

Revision 2649, 5.6 kB (checked in by matt, 18 years ago)

Need autocommit on for INNODB tables

  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
7# (c) 2005, 2006 Matt Hyclak <hyclak@math.ohiou.edu>
8# This program is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program; if not, write to the Free Software
20# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21#
22# $Id$
23#
24#
25
26from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
27from pykota.storages.sql import SQLStorage
28
29try :
30    import MySQLdb
31except ImportError :   
32    import sys
33    # TODO : to translate or not to translate ?
34    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the MySQL module installed correctly." % sys.version.split()[0]
35
36class Storage(BaseStorage, SQLStorage) :
37    def __init__(self, pykotatool, host, dbname, user, passwd) :
38        """Opens the MySQL database connection."""
39        BaseStorage.__init__(self, pykotatool)
40        try :
41            (host, port) = host.split(":")
42            port = int(port)
43        except ValueError :   
44            port = -1           # Use the default MySQL port
45       
46        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
47        self.database = MySQLdb.connect(host=host, port=port, db=dbname, user=user, passwd=passwd)
48        self.database.autocommit(1)
49        self.cursor = self.database.cursor()
50        self.closed = 0
51        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
52           
53    def close(self) :   
54        """Closes the database connection."""
55        if not self.closed :
56            self.cursor.close()
57            self.database.close()
58            self.closed = 1
59            self.tool.logdebug("Database closed.")
60       
61    def beginTransaction(self) :   
62        """Starts a transaction."""
63        self.cursor.execute("BEGIN;")
64        self.tool.logdebug("Transaction begins...")
65       
66    def commitTransaction(self) :   
67        """Commits a transaction."""
68        self.database.commit()
69        self.tool.logdebug("Transaction committed.")
70       
71    def rollbackTransaction(self) :     
72        """Rollbacks a transaction."""
73        self.database.rollback()
74        self.tool.logdebug("Transaction aborted.")
75       
76    def doRawSearch(self, query) :
77        """Does a raw search query."""
78        query = query.strip()   
79        if not query.endswith(';') :   
80            query += ';'
81        try :
82            self.tool.logdebug("QUERY : %s" % query)
83            self.cursor.execute(query)
84        except self.database.Error, msg :   
85            raise PyKotaStorageError, str(msg)
86        else :   
87            # This returns a list of lists. Integers are returned as longs.
88            return self.cursor.fetchall()
89           
90    def doSearch(self, query) :       
91        """Does a search query."""
92        result = self.doRawSearch(query)
93        if result :
94            rows = []
95            fields = {}
96            for i in range(len(self.cursor.description)) :
97                fields[i] = self.cursor.description[i][0]
98            for row in result :
99                rowdict = {}
100                for field in fields.keys() :
101                    value = row[field]
102                    try :
103                        value = value.encode("UTF-8")
104                    except:
105                        pass
106                    rowdict[fields[field]] = value
107                rows.append(rowdict)
108            # returns a list of dicts
109            return rows
110
111    def doModify(self, query) :
112        """Does a (possibly multiple) modify query."""
113        query = query.strip()   
114        if not query.endswith(';') :   
115            query += ';'
116        try :
117            self.tool.logdebug("QUERY : %s" % query)
118            self.cursor.execute(query)
119        except self.database.Error, msg :   
120            raise PyKotaStorageError, str(msg)
121           
122    def doQuote(self, field) :
123        """Quotes a field for use as a string in SQL queries."""
124        if type(field) == type(0.0) :
125            return field
126        elif type(field) == type(0) :
127            return field
128        elif type(field) == type(0L) :
129            return field
130        elif field is not None :
131            return (self.database.string_literal(field)).encode("UTF-8")
132        else :
133            self.tool.logdebug("WARNING: field has no type, returning NULL")
134            return "NULL"
135
136    def prepareRawResult(self, result) :
137        """Prepares a raw result by including the headers."""
138        if result :
139            entries = [tuple([f[0] for f in self.cursor.description])]
140            for entry in result :
141                row = []
142                for value in entry :
143                    try :
144                        value = value.encode("UTF-8")
145                    except :
146                        pass
147                    row.append(value)
148                entries.append(tuple(row))
149            return entries
Note: See TracBrowser for help on using the browser.