/usr/share/pyshared/dhm/sql/dict.py is in python-dhm 0.6-3build1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | # sqldict.py
#
# Copyright 2003 Wichert Akkerman <wichert@deephackmode.org>
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# Calculate shared library dependencies
"""Basic SQL dictionary interface
Often you want to treat a SQL table as a dictionary. This module implements
the SQLTable class which makes it easy to do that. It expects to deal with
tables with unqiue keys (combined keys are supported) which is used to index
the dictionary.
"""
__docformat__ = "epytext en"
import copy, UserDict
class SQLLookup(UserDict.UserDict):
"""SQL lookup table.
This class implements a trivial lookup table that uses a SQL table
as data source. It loads the content of the table during construction,
so only use this for situations where you do frequent lookups or the
table size is small.
It makes a few assumptions on the SQL table:
- it contains only two columns: a key and a value column
- duplicate key entries are not detected. It is highly
recommended to use a unique constraint on the key column.
@cvar table: SQL table which contains our data
@type table: string
"""
def __init__(self, dbc, table, **kwargs):
"""Constructor.
Initializing of SQLLookup is done using a Connection
class and specifying the table containing the data.
@param dbc: database connection
@type dbc: sqlwrap.Connection class
@param table: SQL table with data
@type table: string
"""
UserDict.UserDict.__init__(self)
self.table=table
self.dbc=dbc
self._Read()
def _Read(self):
res=self.dbc.query("SELECT * FROM %s;" % self.table);
for data in res:
(key,value)=data[0:2]
self.data[key]=value
class DictIterator:
def __init__(self, db):
(cmd,values)=db._genwhere()
self.cursor=db.dbc.execute("SELECT DISTINCT %s FROM %s %s;" %
(",".join(db.keycols), db.table, cmd),
values, "format")
def __del__(self):
self.cursor.close()
def __iter__(self):
return self
def next(self):
res=self.cursor.fetchone()
if res==None:
raise StopIteration
if len(res)==1:
return res[0]
else:
return tuple(res)
class SQLDict:
"""SQL dictionary
This class provides a dictionary interface to a SQL table. This is an
abstract class; to use it derive your own class and make a three simple
changes:
1. set the 'table' class variable to the name of the SQL table
containing the data
2. set the 'keycols' class variable to the list of the key columns
3. implement the __getitem__ method
@cvar table: SQL table which contains our data
@type table: string
@cvar keycols: Columns which make up the unique key
@type keycols: string
"""
table = None
keycols = []
def __init__(self, dbc, table=None):
"""Constructor.
@param dbc: database connection
@type dbc: sqlwrap.Connection class
@param table: SQL table with data
@type table: string
"""
if table:
self.table=table
self.dbc=dbc
def _GetKeys(self, args, kwargs={}):
"""Build a key dictionary
Build a dictionary containing the keys based on both
normal and keyword arguments.
"""
if isinstance(args[0], tuple):
args=args[0]
assert(len(args)<=len(self.keycols))
found={}
for i in range(len(args)):
found[self.keycols[i]]=args[i]
for (key,value) in kwargs.items():
if not key in self.keycols:
raise KeyError, "Illegal key"
found[key]=value
if len(found)!=len(self.keycols):
raise KeyError, "Not all keys supplied"
return found
def _genwhere(self, keys=None):
"""Generate data for a WHERE clause to filter for a keyset.
This function generates data which can be used to generate
a WHERE clause to uniquely identify this object in a table. It
returns a tuple containing a string with the SQL command and a
tuple with the data values. This can be fed to the execute
method for a database connection using the format paramstyle.
@return: (command,values) tuple
"""
if not keys:
return ("", (()))
data=keys.items()
keys=map(lambda x: x[0], data)
values=tuple(map(lambda x: x[1], data))
return ("WHERE " + (" AND ".join(map(lambda x: x+"=%s", keys))),
values)
def __getitem__(self, key):
raise NotImplementedError
def __setitem__(self, key, item):
raise NotImplementedError
def __len__(self):
(cmd,values)=self._genwhere()
return int(self.dbc.query(
"SELECT COUNT(*) FROM %s %s;" % (self.table, cmd),
values, "format")[0][0])
def __iter__(self):
return DictIterator(self)
def __contains__(self, key):
return self.has_key(key)
def has_key(self, *arg, **kwargs):
(cmd,values)=self._genwhere(self._GetKeys(arg, kwargs))
res=self.dbc.query(
"SELECT COUNT(*) FROM %s %s;" %
(self.table, cmd), values, "format")
return res[0][0]>0
def keys(self):
(cmd,values)=self._genwhere()
keys=self.dbc.query("SELECT DISTINCT %s FROM %s %s;" %
(",".join(self.keycols), self.table, cmd),
values, "format")
if len(self.keycols)>1:
return keys
else:
return map(lambda x: x[0], keys)
def values(self):
keys=self.keys()
return map(lambda x,s=self: s[x], keys)
def clear(self):
(cmd,values)=self._genwhere()
self.dbc.execute("DELETE FROM %s %s;" % (self.table, cmd),
values, "format")
def __delitem__(self, *arg, **kwargs):
(cmd,values)=self._genwhere(self._GetKeys(arg, kwargs))
self.dbc.execute("DELETE FROM %s %s;" %
(self.table, cmd), values, "format")
class SQLFilterDict(SQLDict):
"""SQL filtering dictionary
This class works exactly like SQLDict but adds the ability to
only work on a subset of rows in a SQL table
This class provides a dictionary interface to a SQL table. This is an
abstract class; to use it derive your own class and make a three simple
changes:
1. set the 'table' class variable to the name of the SQL table
containing the data
2. set the 'keycols' class variable to the list of the key columns
3. implement the __getitem__ method
@cvar table: SQL table which contains our data
@type table: string
@cvar keycols: Columns which make up the unique key
@type keycols: string
"""
def __init__(self, dbc, table=None, **kwargs):
SQLDict.__init__(self, dbc=dbc, table=table)
self.filter=copy.copy(kwargs)
def _genwhere(self, keys={}):
"""Generate data for a WHERE clause to filter for a keyset.
This function generates data which can be used to generate
a WHERE clause to uniquely identify this object in a table. It
returns a tuple containing a string with the SQL command and a
tuple with the data values. This can be fed to the execute
method for a database connection using the format paramstyle.
@return: (command,values) tuple
"""
if not (keys or self.filter):
return ("", (()))
columns=copy.copy(self.filter.keys())
values=copy.copy(self.filter.values())
columns.extend(keys.keys())
values.extend(keys.values())
return (("WHERE " + " AND ".join(map(lambda x: x+"=%s", columns))),
tuple(values))
|