root / pykota / trunk / pykota / storages / dbistorage.py @ 1327

Revision 1327, 5.3 kB (checked in by jalet, 20 years ago)

Preliminary work on Relationnal Database Independance via DB-API 2.0

  • 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.1  2004/02/02 22:44:15  jalet
25# Preliminary work on Relationnal Database Independance via DB-API 2.0
26#
27#
28#
29
30########################################################################
31##                                                                    ##
32## THIS FILE IS HIGHLY EXPERIMENTAL.                                  ##
33##                                                                    ##
34## IT WILL PROVIDE DATABASE INDEPENDANCE IN THE FUTURE.               ##
35##                                                                    ##
36## FOR NOW IT ONLY RECOGNIZES THE POSTGRESQL DBI MODULE.              ##
37##                                                                    ##
38## DON'T USE THIS UNTIL YOU ARE TOLD TO DO SO.                        ##
39##                                                                    ##
40##                                      THANKS !                      ##
41##                                                                    ##
42########################################################################
43
44from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
45from pykota.storages.sqlstorage import SQLStorage
46
47try :
48    import _pg
49    import pgdb
50except ImportError :   
51    import sys
52    # TODO : to translate or not to translate ?
53    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PygreSQL module installed correctly." % sys.version.split()[0]
54
55class Storage(BaseStorage, SQLStorage) :
56    def __init__(self, pykotatool, host, dbname, user, passwd) :
57        """Opens the Database Independant connection."""
58        BaseStorage.__init__(self, pykotatool)
59        try :
60            (host, port) = host.split(":")
61            port = int(port)
62        except ValueError :   
63            port = -1         # Use PostgreSQL's default tcp/ip port (5432).
64       
65        try :
66            self.database = pgdb.connect(host=host, database=dbname, user=user, password=passwd)
67            self.cursor = self.database.cursor()
68        except _pg.error, msg :
69            raise PyKotaStorageError, msg
70        else :   
71            self.closed = 0
72            self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
73           
74    def close(self) :   
75        """Closes the database connection."""
76        if not self.closed :
77            self.cursor.close()
78            self.database.close()
79            self.closed = 1
80            self.tool.logdebug("Database closed.")
81       
82    def beginTransaction(self) :   
83        """Starts a transaction."""
84        # No need for this since transactions begin automatically
85        # self.database.query("BEGIN;")
86        self.tool.logdebug("Transaction begins...")
87       
88    def commitTransaction(self) :   
89        """Commits a transaction."""
90        self.database.commit()
91        self.tool.logdebug("Transaction committed.")
92       
93    def rollbackTransaction(self) :     
94        """Rollbacks a transaction."""
95        self.database.rollback()
96        self.tool.logdebug("Transaction aborted.")
97       
98    def doSearch(self, query) :
99        """Does a search query."""
100        query = query.strip()   
101        if not query.endswith(';') :   
102            query += ';'
103        try :
104            self.tool.logdebug("QUERY : %s" % query)
105            self.cursor.execute(query)
106            result = self.cursor.fetchall()
107        except pgdb.DatabaseError, msg :   
108            raise PyKotaStorageError, msg
109        else :   
110            newresult = []
111            fieldsnames = [desc[0] for desc in self.cursor.description]
112            for record in result :
113                dico = {}
114                for fnumber in range(len(record)) :
115                    dico.update({fieldsnames[fnumber] : record[fnumber]})
116                newresult.append(dico)   
117            return newresult
118           
119    def doModify(self, query) :
120        """Does a (possibly multiple) modify query."""
121        query = query.strip()   
122        if not query.endswith(';') :   
123            query += ';'
124        try :
125            self.tool.logdebug("QUERY : %s" % query)
126            result = self.database.query(query)
127        except pg.error, msg :   
128            raise PyKotaStorageError, msg
129        else :   
130            return result
131           
132    def doQuote(self, field) :
133        """Quotes a field for use as a string in SQL queries."""
134        return pgdb._quote(field)
Note: See TracBrowser for help on using the browser.