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

Revision 2146, 5.4 kB (checked in by jerome, 19 years ago)

It seems that $Log$ is not implemented or doesn't work for some reason

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