pgdb.py 9.69 KB
Newer Older
1 2 3 4 5
""" pgdb - DB-SIG compliant module for PygreSQL.

	(c) 1999, Pascal Andre <andre@via.ecp.fr>.
	See package documentation for further information on copyright.

6 7
	Inline documentation is sparse.  See DB-SIG 2.0 specification for
	usage information.
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

		basic usage:

		pgdb.connect(connect_string) -> connection
			connect_string = 'host:database:user:password:opt:tty'
			All parts are optional. You may also pass host through
			password as keyword arguments. To pass a port, pass it in
			the host keyword parameter:
				pgdb.connect(host='localhost:5432')

		connection.cursor() -> cursor

		connection.commit()

		connection.close()

		connection.rollback()

		cursor.execute(query[, params])
			execute a query, binding params (a dictionary) if it is
			passed. The binding syntax is the same as the % operator
			for dictionaries, and no quoting is done.

		cursor.executemany(query, list of params)
			execute a query many times, binding each param dictionary
			from the list.

		cursor.fetchone() -> [value, value, ...]

		cursor.fetchall() -> [[value, value, ...], ...]

		cursor.fetchmany([size]) -> [[value, value, ...], ...]
			returns size or cursor.arraysize number of rows from result
			set. Default cursor.arraysize is 1.

		cursor.description -> [(column_name, type_name, display_size,
			internal_size, precision, scale, null_ok), ...]

			Note that precision, scale and null_ok are not implemented.

		cursor.rowcount
			number of rows available in the result set. Available after
			a call to execute.

		cursor.close()

"""

import _pg
import string
import exceptions
import types
import time
D'Arcy J.M. Cain's avatar
D'Arcy J.M. Cain committed
61
import types
62

63 64 65 66
# Marc-Andre is changing where DateTime goes.  This handles it either way.
try: from mx import DateTime
except ImportError: import DateTime

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
### module constants

# compliant with DB SIG 2.0
apilevel = '2.0'

# module may be shared, but not connections
threadsafety = 1

# this module use extended python format codes
paramstyle = 'pyformat'

### exception hierarchy

class Warning(StandardError):
	pass

class Error(StandardError):
	pass

class InterfaceError(Error):
	pass

class DatabaseError(Error):
	pass

class DataError(DatabaseError):
	pass

class OperationalError(DatabaseError):
	pass

class IntegrityError(DatabaseError):
	pass

class InternalError(DatabaseError):
	pass

class ProgrammingError(DatabaseError):
	pass

class NotSupportedError(DatabaseError):
	pass

### internal type handling class
class pgdbTypeCache:

	def __init__(self, cnx):
		self.__source = cnx.source()
		self.__type_cache = {}

	def typecast(self, typ, value):
		# for NULL values, no typecast is necessary
		if value == None:
			return value

		if typ == STRING:
			pass
		elif typ == BINARY:
			pass
Bruce Momjian's avatar
Bruce Momjian committed
126 127
		elif typ == BOOL:
			value = (value[:1] in ['t','T'])
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
		elif typ == INTEGER:
			value = int(value)
		elif typ == LONG:
			value = long(value)
		elif typ == FLOAT:
			value = float(value)
		elif typ == MONEY:
			value = string.replace(value, "$", "")
			value = string.replace(value, ",", "")
			value = float(value)
		elif typ == DATETIME:
			# format may differ ... we'll give string
			pass
		elif typ == ROWID:
			value = long(value)
		return value

	def getdescr(self, oid):
		try:
			return self.__type_cache[oid]
		except:
			self.__source.execute(
				"SELECT typname, typprtlen, typlen "
				"FROM pg_type WHERE oid = %s" % oid
			)
			res = self.__source.fetch(1)[0]
			# column name is omitted from the return value. It will
			# have to be prepended by the caller.
			res = (
				res[0],
				string.atoi(res[1]), string.atoi(res[2]),
				None, None, None
			)
			self.__type_cache[oid] = res
			return res

### cursor object

class pgdbCursor:

	def __init__(self, src, cache):
		self.__cache = cache
		self.__source = src
		self.description = None
		self.rowcount = -1
		self.arraysize = 5

	def close(self):
		self.__source.close()
		self.description = None
		self.rowcount = -1

	def execute(self, operation, params = None):
D'Arcy J.M. Cain's avatar
D'Arcy J.M. Cain committed
181 182 183 184 185
		# "The parameters may also be specified as list of
		# tuples to e.g. insert multiple rows in a single
		# operation, but this kind of usage is depreciated:
		if params and type(params) == types.ListType and \
					type(params[0]) == types.TupleType:
186 187
			self.executemany(operation, params)
		else:
D'Arcy J.M. Cain's avatar
D'Arcy J.M. Cain committed
188
			# not a list of tuples
189 190 191 192 193 194 195 196 197 198 199 200
			self.executemany(operation, (params,))

	def executemany(self, operation, param_seq):
		self.description = None
		self.rowcount = -1

		# first try to execute all queries
		totrows = 0
		sql = "INIT"
		try:
			for params in param_seq:
				if params != None:
D'Arcy J.M. Cain's avatar
D'Arcy J.M. Cain committed
201
					sql = _quoteparams(operation, params)
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
				else:
					sql = operation
				rows = self.__source.execute(sql)
				if rows != None: # true is __source is NOT a DQL
					totrows = totrows + rows
		except _pg.error, msg:
			raise DatabaseError, "error '%s' in '%s'" % ( msg, sql )
		except:
			raise OperationalError, "internal error in '%s'" % sql

		# then initialize result raw count and description
		if self.__source.resulttype == _pg.RESULT_DQL:
			self.rowcount = self.__source.ntuples
			d = []
			for typ in self.__source.listinfo():
				# listinfo is a sequence of
				# (index, column_name, type_oid)
				# getdescr returns all items needed for a
				# description tuple except the column_name.
				desc = typ[1:2]+self.__cache.getdescr(typ[2])
				d.append(desc)
			self.description = d
		else:
			self.rowcount = totrows
			self.description = None

	def fetchone(self):
		res = self.fetchmany(1, 0)
		try:
			return res[0]
		except:
			return None

	def fetchall(self):
		return self.fetchmany(-1, 0)

	def fetchmany(self, size = None, keep = 1):
		if size == None:
			size = self.arraysize
		if keep == 1:
			self.arraysize = size
		res = self.__source.fetch(size)
		result = []
		for r in res:
			row = []
			for i in range(len(r)):
				row.append(self.__cache.typecast(
						self.description[i][1],
						r[i]
					)
				)
			result.append(row)
		return result

	def setinputsizes(self, sizes):
		pass

	def setoutputsize(self, size, col = 0):
		pass

D'Arcy J.M. Cain's avatar
D'Arcy J.M. Cain committed
262

Bruce Momjian's avatar
Bruce Momjian committed
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
def _quote(x):
	if type(x) == types.StringType:
		x = "'" + string.replace(
				string.replace(str(x), '\\', '\\\\'), "'", "''") + "'"

	elif type(x) in (types.IntType, types.LongType, types.FloatType):
		pass
	elif x is None:
		x = 'NULL'
	elif hasattr(x, '__pg_repr__'):
		x = x.__pg_repr__()
	else:
		raise InterfaceError, 'do not know how to handle type %s' % type(x)

	return x

def _quoteparams(s, params):
	if hasattr(params, 'has_key'):
		x = {}
		for k, v in params.items():
			x[k] = _quote(v)
		params = x
	else:
		params = tuple(map(_quote, params))

	return s % params
D'Arcy J.M. Cain's avatar
D'Arcy J.M. Cain committed
289

290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
### connection object

class pgdbCnx:

	def __init__(self, cnx):
		self.__cnx = cnx
		self.__cache = pgdbTypeCache(cnx)
		try:
			src = self.__cnx.source()
			src.execute("BEGIN")
		except:
			raise OperationalError, "invalid connection."

	def close(self):
		self.__cnx.close()

	def commit(self):
		try:
			src = self.__cnx.source()
			src.execute("COMMIT")
			src.execute("BEGIN")
		except:
			raise OperationalError, "can't commit."

	def rollback(self):
		try:
			src = self.__cnx.source()
			src.execute("ROLLBACK")
			src.execute("BEGIN")
		except:
			raise OperationalError, "can't rollback."

	def cursor(self):
		try:
			src = self.__cnx.source()
			return pgdbCursor(src, self.__cache)
		except:
			raise pgOperationalError, "invalid connection."

### module interface

# connects to a database
def connect(dsn = None, user = None, password = None, host = None, database = None):
	# first get params from DSN
	dbport = -1
	dbhost = ""
	dbbase = ""
	dbuser = ""
	dbpasswd = ""
	dbopt = ""
	dbtty = ""
	try:
		params = string.split(dsn, ":")
		dbhost = params[0]
		dbbase = params[1]
		dbuser = params[2]
		dbpasswd = params[3]
		dbopt = params[4]
		dbtty = params[5]
	except:
		pass

	# override if necessary
	if user != None:
		dbuser = user
	if password != None:
		dbpasswd = password
	if database != None:
		dbbase = database
	if host != None:
		try:
			params = string.split(host, ":")
			dbhost = params[0]
Bruce Momjian's avatar
Bruce Momjian committed
363
			dbport = int(params[1])
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
		except:
			pass

	# empty host is localhost
	if dbhost == "":
		dbhost = None
	if dbuser == "":
		dbuser = None

	# open the connection
	cnx = _pg.connect(host = dbhost, dbname = dbbase, port = dbport,
						opt = dbopt, tty = dbtty,
						user = dbuser, passwd = dbpasswd)
	return pgdbCnx(cnx)

### types handling

# PostgreSQL is object-oriented: types are dynamic. We must thus use type names
# as internal type codes.

class pgdbType:

	def __init__(self, *values):
		self.values=  values

	def __cmp__(self, other):
		if other in self.values:
			return 0
		if other < self.values:
			return 1
		else:
			return -1

STRING = pgdbType(
398
	'char', 'bpchar', 'name', 'text', 'varchar'
399 400 401 402 403 404 405
)

# BLOB support is pg specific
BINARY = pgdbType()
INTEGER = pgdbType('int2', 'int4', 'serial')
LONG = pgdbType('int8')
FLOAT = pgdbType('float4', 'float8', 'numeric')
406
BOOL = pgdbType('bool')
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
MONEY = pgdbType('money')

# this may be problematic as type are quite different ... I hope it won't hurt
DATETIME = pgdbType(
	'abstime', 'reltime', 'tinterval', 'date', 'time', 'timespan', 'timestamp'
)

# OIDs are used for everything (types, tables, BLOBs, rows, ...). This may cause
# confusion, but we are unable to find out what exactly is behind the OID (at
# least not easily enough). Should this be undefined as BLOBs ?
ROWID = pgdbType(
	'oid', 'oid8'
)

# mandatory type helpers
def Date(year, month, day):
	return DateTime.DateTime(year, month, day)

def Time(hour, minute, second):
	return DateTime.TimeDelta(hour, minute, second)

def Timestamp(year, month, day, hour, minute, second):
	return DateTime.DateTime(year, month, day, hour, minute, second)

def DateFromTicks(ticks):
	return apply(Date, time.localtime(ticks)[:3])

def TimeFromTicks(ticks):
	return apply(Time, time.localtime(ticks)[3:6])

def TimestampFromTicks(ticks):
	return apply(Timestamp, time.localtime(ticks)[:6])