# SQLObject.py
#
# Copyright 2001, 2002,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

"""SQL object helper

This module implements SQLObject, an convenience class that allows one to
use data stored in a SQL database as if it was a standard python mapping
type.
"""

__docformat__	= "epytext en"

import UserDict

class SQLObjectException(Exception):
	"""SQLObject exception class

	@ivar reason: reason for raising this exception
	@type reason: string
	"""
	def __init__(self, reason):
		"""Constructor.

		@param reason: reason for raising this exception
		@type reason:  string
		"""
		self.reason=reason

	def __str__(self):
		return self.reason


class SQLObject(UserDict.UserDict):
	"""SQL object

	A SQL object acts like a dictionary representing a row in a
	SQL table. It keeps track of changes made (and will not allow
	changes for columns that do not exist) and can efficiently
	update the data in the SQL database when requested.

	@cvar table: name of SQL table containing data for this object
	@type table: string
	@cvar keys:  list of keys uniquely identifying an object
	@type keys:  list of strings
	@cvar attrs: list of columns
	@type attrs: list of strings
	"""
	table	= ""
	keys	= [ ]
	attrs	= [ ]

	def __init__(self, dbc=None, **kwargs):
		"""Constructor

		Extra keyword parameters are used to set initial valus for
		columns/attributes.

		@param dbc: database connection
		@type  dbc: sqlwrap.Connection class
		"""
		UserDict.UserDict.__init__(self)

		self.changes=[]

		cnonkey=0
		ckey=0
		for (key,value) in kwargs.items():
			if key in self.keys:
				ckey+=1
			else:
				cnonkey+=1

			self[key]=value

		for a in self.attrs:
			if not self.has_key(a):
				self[a]=None

		if dbc:
			self.dbc=dbc

			if ckey==len(self.keys) and not cnonkey:
				self.retrieve(dbc)


	def __setitem__(self, key, item):
		if key in self.keys and self.data.has_key(key) and self.data[key]:
			raise SQLObjectException, "cannot change key"

		self.data[key]=item
		if not key in self.changes:
			self.changes.append(key)


	def clear(self):
		"""Clear all data in this object.

		This method clear all data stored in a class instance. This
		can be used to recycle an instance so the cost of creating
		a new instance can be avoided.
		"""
		UserDict.UserDict.clear(self)
		self.changes=[]

		
	def _genwhere(self):
		"""Generate data for a WHERE clause to identify this object.

		This method 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
		"""
		cmd=" AND ".join(map(lambda x: x+"=%s", self.keys))
		values=map(lambda x,data=self.data: data[x], self.keys)

		return (cmd,tuple(values))


	def retrieve(self, dbc=None):
		"""Retrieve object from the database.

		It is possible to retrieve the object from another database by
		specifying a different database connection.

		@param dbc: database connection to save 
		@type dbc:  sqlwrap.Connection class
		"""
		if not dbc:
			dbc=self.dbc

		for k in self.keys:
			if not self.data.has_key(k):
				raise SQLObjectException, "Not all keys set"

		(cmd,values)=self._genwhere()
		cursor=dbc.execute("SELECT * FROM %s WHERE %s;" % 
			(self.table, cmd), values, "format")

		res=cursor.fetchone()
		if not res:
			cursor.close()
			raise KeyError

		self.changes=[]
		for i in range(len(cursor.description)):
			self.data[cursor.description[i][0]]=res[i]
		cursor.close()


	def _sql_insert(self, dbc):
		attrs=[]
		vals=[]
		for a in self.attrs:
			if not (self.data.has_key(a) and 
					self.data[a]!=None):
				continue

			attrs.append(a)
			vals.append(self.data[a])

		dbc.execute("INSERT INTO %s (%s) VALUES (%s);" % 
			(self.table, ", ".join(attrs),
			 ",".join(["%s"]*len(vals))), vals, "format")


	def _sql_update(self, dbc):
		set=", ".join(map(lambda x: x+"=%s", self.changes))
		data=tuple(map(lambda x,data=self.data: data[x], self.changes))
		(cmd,values)=self._genwhere()

		dbc.execute("UPDATE %s SET %s WHERE %s;" % 
			(self.table, set, cmd), data+values, "format")


	def update(self, dbc=None):
		"""Commit changes to the database.

		If the key (or one of the keys) has been changed a new row will
		be inserted in the database. The old row will NOT be removed
		though, this has to be done manually.

		It is possible to store the object in another database by
		specifying a different database connection.

		@param dbc: database connection to save 
		@type dbc:  sqlwrap.Connection class
		"""
		if not dbc:
			dbc=self.dbc
			
		if not self.changes:
			return

		kchange=0
		for k in self.keys:
			if k in self.changes:
				kchange+=1

		if kchange or (dbc and dbc!=self.dbc):
			self._sql_insert(dbc)
		else:
			self._sql_update(dbc)

		self.changes=[]

