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

Revision 2644, 5.6 kB (checked in by jerome, 18 years ago)

Changed copyright messages' years

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: pgstorage.py 1725 2005-09-03 12:20:30Z jerome $
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.cursor = self.database.cursor()
49        self.closed = 0
50        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
51           
52    def close(self) :   
53        """Closes the database connection."""
54        if not self.closed :
55            self.cursor.close()
56            self.database.close()
57            self.closed = 1
58            self.tool.logdebug("Database closed.")
59       
60    def beginTransaction(self) :   
61        """Starts a transaction."""
62        self.database.begin()
63        self.tool.logdebug("Transaction begins...")
64       
65    def commitTransaction(self) :   
66        """Commits a transaction."""
67        self.database.commit()
68        self.tool.logdebug("Transaction committed.")
69       
70    def rollbackTransaction(self) :     
71        """Rollbacks a transaction."""
72        self.database.rollback()
73        self.tool.logdebug("Transaction aborted.")
74       
75    def doRawSearch(self, query) :
76        """Does a raw search query."""
77        query = query.strip()   
78        if not query.endswith(';') :   
79            query += ';'
80        try :
81            self.tool.logdebug("QUERY : %s" % query)
82            self.cursor.execute(query)
83        except self.database.Error, msg :   
84            raise PyKotaStorageError, str(msg)
85        else :   
86            # This returns a list of lists. Integers are returned as longs.
87            return self.cursor.fetchall()
88           
89    def doSearch(self, query) :       
90        """Does a search query."""
91        result = self.doRawSearch(query)
92        if result :
93            rows = []
94            fields = {}
95            for i in range(len(self.cursor.description)) :
96                fields[i] = self.cursor.description[i][0]
97            for row in result :
98                rowdict = {}
99                for field in fields.keys() :
100                    value = row[field]
101                    try :
102                        value = value.encode("UTF-8")
103                    except:
104                        pass
105                    rowdict[fields[field]] = value
106                rows.append(rowdict)
107            # returns a list of dicts
108            return rows
109
110    def doModify(self, query) :
111        """Does a (possibly multiple) modify query."""
112        query = query.strip()   
113        if not query.endswith(';') :   
114            query += ';'
115        try :
116            self.tool.logdebug("QUERY : %s" % query)
117            self.cursor.execute(query)
118        except self.database.Error, msg :   
119            raise PyKotaStorageError, str(msg)
120           
121    def doQuote(self, field) :
122        """Quotes a field for use as a string in SQL queries."""
123        if type(field) == type(0.0) :
124            return field
125        elif type(field) == type(0) :
126            return field
127        elif type(field) == type(0L) :
128            return field
129        elif field is not None :
130            return (self.database.string_literal(field)).encode("UTF-8")
131        else :
132            self.tool.logdebug("WARNING: field has no type, returning NULL")
133            return "NULL"
134
135    def prepareRawResult(self, result) :
136        """Prepares a raw result by including the headers."""
137        if result :
138            entries = [tuple([f[0] for f in self.cursor.description])]
139            for entry in result :
140                row = []
141                for value in entry :
142                    try :
143                        value = value.encode("UTF-8")
144                    except :
145                        pass
146                    row.append(value)
147                entries.append(tuple(row))
148            return entries
Note: See TracBrowser for help on using the browser.