root / pykota / trunk / pykota / storages / pgstorage.py @ 2593

Revision 2593, 5.0 kB (checked in by jerome, 18 years ago)

Added support for SQLite3 database backend.
NEEDS TESTERS !

  • Property svn:eol-style set to native
  • 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 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
26from pykota.storages.sql import SQLStorage
27
28try :
29    import pg
30except ImportError :   
31    import sys
32    # TODO : to translate or not to translate ?
33    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PygreSQL module installed correctly." % sys.version.split()[0]
34else :   
35    try :
36        PGError = pg.Error
37    except AttributeError :   
38        PGError = pg.error
39
40class Storage(BaseStorage, SQLStorage) :
41    def __init__(self, pykotatool, host, dbname, user, passwd) :
42        """Opens the PostgreSQL database connection."""
43        BaseStorage.__init__(self, pykotatool)
44        try :
45            (host, port) = host.split(":")
46            port = int(port)
47        except ValueError :   
48            port = -1         # Use PostgreSQL's default tcp/ip port (5432).
49       
50        self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." % (host, port, dbname, user))
51        self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
52        self.closed = 0
53        self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
54           
55    def close(self) :   
56        """Closes the database connection."""
57        if not self.closed :
58            self.database.close()
59            self.closed = 1
60            self.tool.logdebug("Database closed.")
61       
62    def beginTransaction(self) :   
63        """Starts a transaction."""
64        self.database.query("BEGIN;")
65        self.tool.logdebug("Transaction begins...")
66       
67    def commitTransaction(self) :   
68        """Commits a transaction."""
69        self.database.query("COMMIT;")
70        self.tool.logdebug("Transaction committed.")
71       
72    def rollbackTransaction(self) :     
73        """Rollbacks a transaction."""
74        self.database.query("ROLLBACK;")
75        self.tool.logdebug("Transaction aborted.")
76       
77    def doRawSearch(self, query) :
78        """Does a raw search query."""
79        query = query.strip()   
80        if not query.endswith(';') :   
81            query += ';'
82        try :
83            self.tool.logdebug("QUERY : %s" % query)
84            result = self.database.query(query)
85        except PGError, msg :   
86            raise PyKotaStorageError, str(msg)
87        else :   
88            return result
89           
90    def doSearch(self, query) :       
91        """Does a search query."""
92        result = self.doRawSearch(query)
93        if (result is not None) and (result.ntuples() > 0) : 
94            return result.dictresult()
95       
96    def doModify(self, query) :
97        """Does a (possibly multiple) modify query."""
98        query = query.strip()   
99        if not query.endswith(';') :   
100            query += ';'
101        try :
102            self.tool.logdebug("QUERY : %s" % query)
103            result = self.database.query(query)
104        except PGError, msg :   
105            raise PyKotaStorageError, str(msg)
106        else :   
107            return result
108           
109    def doQuote(self, field) :
110        """Quotes a field for use as a string in SQL queries."""
111        if type(field) == type(0.0) : 
112            typ = "decimal"
113        elif type(field) == type(0) :   
114            typ = "int"
115        elif type(field) == type(0L) :   
116            typ = "int"
117        else :   
118            typ = "text"
119        return pg._quote(field, typ)
120       
121    def prepareRawResult(self, result) :
122        """Prepares a raw result by including the headers."""
123        if result.ntuples() > 0 :
124            entries = [result.listfields()]
125            entries.extend(result.getresult())
126            nbfields = len(entries[0])
127            for i in range(1, len(entries)) :
128                fields = list(entries[i])
129                for j in range(nbfields) :
130                    field = fields[j]
131                    if type(field) == StringType :
132                        fields[j] = self.databaseToUserCharset(field) 
133                entries[i] = tuple(fields)   
134            return entries
135       
Note: See TracBrowser for help on using the browser.