Saturday, April 23, 2005

Static can be better...

Its not often that I wish Python was a statically typed language.-----------------------------------------------------------------
I have been playing with making my python - database interfaces a little more, well interesting.Specifically Tim at work showed me apachedb. It takes a database defintion and creates from that definition a setof java class files that represent each table, so you can (presumably - i have not used it) suck in data, create an object then "save" it to database and so on.
Aha I thought lets give this a go in python.
So firstly I start with making an object directly from a recordset::
class _recordset: def __init__(self, dict): for key in dict.keys(): self.__dict__[key] = dict[key]
def getRSasobj(cursor, SQL): ''' for a given cursor, and SQL, return RS as an object
improvements: somehow cast the items as they should be in ''' cursor.execute(SQL) desc = cursor.description rs = cursor.fetchall() #we now have the data as a tuple, and the col headings as a tuple names = [] [names.append(col[0]) for col in cursor.description] objlist = [] for row in rs: #zip the columnnames and the row data, then pass into a dictionary. #Now pass dictionary to mk a simple rs object, and append to list of objects objlist.append( _recordset( dict( zip( names, row) ) ) ) return objlist
The above just makes an instance of _recordset holding whatever data was in the returned row. (I guess it should be _row then).For example I can get x = getRSasobj(c,"Select Id, name from tblfoo;") and then see x[0].name
Ok its not brilliant but it works and when I refactor it it may be usable elsewhere
However i now want to try this apachedb thing.
SO first off - the plan
the plan--------(This is very mysql specific but hey!)
- get all tables in dbase "show tables"- get the table def for each table "DESCRIBE tbltask;"- Create a class module that holds the defintion Here is where I am coming unstuck.
I can create a class module fairly easily ( "class generic_%s:" % tablename ) but when I come to defining the attributes in a class (lets say the self.id and self.name) I hit the static problem. In Java (and i bet in apachedb) one would just declare (pseudocode - I canot rememebr the Java) ::
declare ID as INT or Datetime or Varchar(32) or whatever
But how od i do this in python?I am going to have to build seperate checks in ...similar to:: self.ID = parameter_ID if type(self.ID) != 'int': raise MyErrorClass
This seems overwrought...

0 Comments:

Post a Comment

<< Home