Contact: fumanchu@aminus.org

Log in as guest/dejavu to create tickets

I think I've seen this ORM somewhere before...

root/trunk/storage/storepypgsql.py

Revision 108 (checked in by fumanchu, 7 years ago)

New "version" method for db SM's.

  • Property svn:eol-style set to native
Line 
1 # Use libpq directly to avoid all of the DB-API overhead.
2 from pyPgSQL import libpq
3 import datetime
4 import dejavu
5 from dejavu.storage import db
6
7
8 class AdapterToPgSQL(db.AdapterToSQL):
9    
10     like_escapes = [("%", r"\\%"), ("_", r"\\_")]
11
12
13 class PgSQLDecompiler(db.SQLDecompiler):
14    
15     def dejavu_icontainedby(self, op1, op2):
16         if isinstance(op1, db.ConstWrapper):
17             # Looking for text in a field. Use ILike (reverse terms).
18             return op2 + " ILIKE '%" + self.adapter.escape_like(op1) + "%'"
19         else:
20             # Looking for field in (a, b, c).
21             # Force all args to lowercase for case-insensitive comparison.
22             atoms = [self.adapter.coerce(x).lower() for x in op2.basevalue]
23             return "LOWER(%s) IN (%s)" % (op1, ", ".join(atoms))
24    
25     def dejavu_istartswith(self, x, y):
26         return x + " ILIKE '" + self.adapter.escape_like(y) + "%'"
27    
28     def dejavu_iendswith(self, x, y):
29         return x + " ILIKE '%" + self.adapter.escape_like(y) + "'"
30    
31     def dejavu_ieq(self, x, y):
32         # ILIKE with no wildcards should behave like ieq.
33         return x + " ILIKE '" + self.adapter.escape_like(y) + "'"
34    
35     def dejavu_year(self, x):
36         return "date_part('year', " + x + ")"
37
38
39
40 class StorageManagerPgSQL(db.StorageManagerDB):
41     """StoreManager to save and retrieve Units via pyPgSQL 1.35."""
42    
43     identifier_length = 63
44     close_connection_method = 'finish'
45     decompiler = PgSQLDecompiler
46     toAdapter = AdapterToPgSQL()
47    
48     def __init__(self, name, arena, allOptions={}):
49         db.StorageManagerDB.__init__(self, name, arena, allOptions)
50        
51         # connstring = (host=h port=p dbname=d user=u password=p options=o tty=t)
52         self.connstring = allOptions[u'Connect']
53         atoms = self.connstring.split(" ")
54         for atom in atoms:
55             k, v = atom.split("=", 1)
56             setattr(self, k, v)
57    
58     def _get_conn(self):
59         try:
60             return libpq.PQconnectdb(self.connstring)
61         except libpq.DatabaseError, x:
62             msg = x.args[0]
63             if msg.endswith('does not exist\n'):
64                 if self.CreateIfMissing:
65                     self.create_database()
66                     return libpq.PQconnectdb(self.connstring)
67             elif msg.startswith('could not connect'):
68                 raise db.OutOfConnectionsError
69             raise x
70    
71     def _template_conn(self):
72         atoms = self.connstring.split(" ")
73         tmplconn = ""
74         for atom in atoms:
75             k, v = atom.split("=", 1)
76             if k == 'dbname': v = 'template1'
77             tmplconn += "%s=%s " % (k, v)
78         return libpq.PQconnectdb(tmplconn)
79    
80     def create_database(self):
81         c = self._template_conn()
82         self.execute('CREATE DATABASE %s' % self.identifier(self.dbname), c)
83         c.finish()
84    
85     def drop_database(self):
86         c = self._template_conn()
87         self.execute("DROP DATABASE %s;" % self.identifier(self.dbname), c)
88         c.finish()
89    
90     def version(self):
91         c = self._template_conn()
92         v = c.version
93         c.finish()
94         return v
95    
96     def fetch(self, query, conn=None):
97         """fetch(query, conn=None) -> rowdata, columns."""
98         res = self.execute(query, conn)
99        
100         columns = []
101         if res.resultType != libpq.EMPTY_QUERY:
102             for index in xrange(res.nfields):
103                 columns.append((res.fname(index), res.ftype(index)))
104        
105         data = [[res.getvalue(row, col) for col in xrange(res.nfields)]
106                 for row in xrange(res.ntuples)]
107         res.clear()
108        
109         return data, columns
110
Note: See TracBrowser for help on using the browser.