forgetsql-0.5.1/0000755000175000001440000000000010023062130014167 5ustar wernerusers00000000000000forgetsql-0.5.1/bin/0000755000175000001440000000000010023062130014737 5ustar wernerusers00000000000000forgetsql-0.5.1/bin/forgetsql-generate0000755000175000001440000002147310023051474020503 0ustar wernerusers00000000000000#!/usr/bin/env python # $Id: forgetsql-generate,v 1.5 2004/03/08 11:04:28 stain Exp $ ## Distributed under LGPL ## (c) Stian Søiland 2002-2004 ## stian@soiland.no ## http://forgetsql.sourceforge.net/ # __version__ should really come from setup.py.. hmm __version__ = "0.5.1" import exceptions, time, re, types, pprint, sys import forgetSQL # backwards compatibility try: True,False except NameError: (True, False) = (1==1, 1==0) # Taken from http://www.python.org/doc/current/lib/built-in-funcs.html def my_import(name): mod = __import__(name) components = name.split('.') # Takes care of things like pyPgSQL.PgSQL for comp in components[1:]: mod = getattr(mod, comp) return mod def generateFromTables(tables, cursor, getLinks=1, code=0): """Generates python code (or class objects if code is false) based on SQL queries on the table names given in the list tables. code - if given - should be an dictionary containing these keys to be inserted into generated code: 'database': database name 'module': database module name 'connect': string to be inserted into module.connect() """ curs = cursor() forgetters = {} class _Wrapper(forgetSQL.Forgetter): pass _Wrapper.cursor = cursor for table in tables: # capitalize the table name to make it look like a class name = table.capitalize() # Define the class by instanciating the meta class to # the given name (requires Forgetter to be new style) forgetter = _Wrapper.__class__(name, (_Wrapper,), {}) # Register it forgetters[name] = forgetter forgetter._sqlTable = table forgetter._sqlLinks = {} forgetter._sqlFields = {} forgetter._shortView = () forgetter._descriptions = {} forgetter._userClasses = {} # Get columns curs.execute("SELECT * FROM %s LIMIT 1" % table) columns = [column[0] for column in curs.description] # convert to dictionary and register in forgetter for column in columns: forgetter._sqlFields[column] = column if getLinks: # Try to find links between tables (!) # Note the big O factor with this ... for (tableName, forgetter) in forgetters.items(): for (key, column) in forgetter._sqlFields.items(): # A column refering to another table would most likely # be called otherColumnID or just otherColumn. We'll # lowercase below when performing the test. possTable = re.sub(r'_?id$', '', column) # all tables (ie. one of the forgetters) are candidates foundLink = False for candidate in forgetters.keys(): if candidate.lower() == possTable.lower(): if possTable.lower() == tableName.lower(): # It's our own primary key! forgetter._sqlPrimary = (column,) break # Woooh! First - let's replace 'blapp_id' with 'blapp' # as the attribute name to indicate that it would # contain the Blapp instance, not just # some ID. del forgetter._sqlFields[key] forgetter._sqlFields[possTable] = column # And.. we'll need to know which class we refer to forgetter._userClasses[possTable] = candidate break # we've found our candidate if code: if code['module'] == "MySQLdb": code['class'] = 'forgetSQL.MysqlForgetter' else: code['class'] = 'forgetSQL.Forgetter' code['date'] = time.strftime('%Y-%m-%d') print ''' """Database wrappers %(database)s Autogenerated by forgetsql-generate %(date)s. """ import forgetSQL #import %(module)s class _Wrapper(%(class)s): """Just a simple wrapper class so that you may easily change stuff for all forgetters. Typically this involves subclassing MysqlForgetter instead.""" # Example database connection (might miss password) #_dbModule = %(module)s #_dbConnection = %(module)s.connect(%(connect)s) #def cursor(self): # return self._dbConnection.cursor() ''' % code items = forgetters.items() items.sort() for (name, forgetter) in items: print "class %s(_Wrapper):" % name for (key, value) in forgetter.__dict__.items(): if key.find('__') == 0: continue nice = pprint.pformat(value) # Get some indention nice = nice.replace('\n', '\n ' + ' '*len(key)) print ' %s = ' % key, nice print "" print ''' # Prepare them all. We need to send in our local # namespace. forgetSQL.prepareClasses(locals()) ''' else: forgetSQL.prepareClasses(forgetters) return forgetters def main(): try: # Should from optparse import OptionParser except ImportError: print >>sys.stderr, "optik 1.4.1 or Python 2.3 or later needed for command line usage" print >>sys.stderr, "Download optik from http://optik.sourceforge.net/" print >>sys.stderr, "or upgrade Python." sys.exit(1) usage = """usage: %prog [options] Generates Python code for using forgetSQL to access database tables. You need to include a line-seperated list of table names to either stdin or as a file using option --tables.""" parser = OptionParser(version="%prog " + __version__, usage=usage) parser.add_option("-t", "--tables", dest="tables", help="read list of tables from FILE instead of stdin", metavar="FILE") parser.add_option("-o", "--output", dest="output", help="write generated code to OUTPUT instead of stdout") parser.add_option("-m", "--dbmodule", dest="dbmodule", help="database module to use") parser.add_option("-H", "--host", dest="host", help="hostname of database server") parser.add_option("-d", "--database", dest="database", help="database to connect to") parser.add_option("-u", "--username", dest="username", help="database username") parser.add_option("-p", "--password", dest="password", help="database password") parser.add_option("-c", "--connect", dest="connect", help="database connect string (instead of host/database/user/password") (options, args) = parser.parse_args() if options.tables: try: file = open(options.tables) except IOError, e: print >>sys.stderr, "%s: %s" % (e.strerror, e.filename) sys.exit(2) else: file = sys.stdin if options.output: try: # Override print.. dirty. sys.stdout = open(output, "w") except IOError, e: print >>sys.stderr, "%s: %s" % (e.strerror, e.filename) sys.exit(3) if not options.dbmodule: print >>sys.stderr, "Missing required option --dbmodule" parser.print_help(file=sys.stderr) sys.exit(4) try: dbmodule = my_import(options.dbmodule) except ImportError: print >>sys.stderr, "Unknown database module", options.dbmodule sys.exit(5) if options.connect: connectstring = options.connect try: connection = dbmodule.connect(options.connect) except Exception, e: print >>sys.stderr, "Could not connect to database using", \ options.connect sys.exit(6) else: params = {} if options.database: params['database'] = options.database else: print >>sys.stderr, "Missing required option --database or --connect" sys.exit(7) if options.host: params['host'] = options.host if options.username: params['user'] = options.username if options.password: params['password'] = options.password connectstring = ", ".join(["%s=%r" % (key, value) for (key,value) in params.items() # filter out password for 'security reasons' if key != "password"]) try: connection = dbmodule.connect(**params) except Exception, e: print >>sys.stderr, "Could not connect to database using", \ connectstring print >>sys.stderr, e sys.exit(8) cursor = connection.cursor tables = file.read().split() if not tables: print >>sys.stderr, "No table names supplied" sys.exit(9) # collect useful strings for generated code code = {} code['connect'] = connectstring code['module'] = options.dbmodule code['database'] = options.database or '(unknown)' generateFromTables(tables, cursor, code=code) if __name__=='__main__': main() forgetsql-0.5.1/lib/0000755000175000001440000000000010023062130014735 5ustar wernerusers00000000000000forgetsql-0.5.1/lib/forgetSQL.py0000755000175000001440000007406110023062031017170 0ustar wernerusers00000000000000#!/usr/bin/env python __version__ = "0.5.1" ## Distributed under LGPL ## (c) Stian Søiland 2002-2003 ## stian@soiland.no ## http://forgetsql.sourceforge.net/ import exceptions, time, re, types, sys # from nav import database try: from mx import DateTime except: DateTime = None try: True,False except NameError: (True,False) = (1==1, 0==1) import weakref class NotFound(exceptions.Exception): pass class Forgetter(object): """SQL to object database wrapper. Given a welldefined database, by subclassing Forgetter and supplying some attributes, you may wrap your SQL tables into objects that are easier to program with. You must define all fields in the database table that you want to expose, and you may refine the names to suit your object oriented programming style. (ie. customerID -> customer) Objects will be created without loading from database, loading will occur when you try to read or write some of the attributes defined as a SQL field. If you change some attributes the object will be saved to the database by save() or garbage collection. (be aware that GC in Py >= 2.2 is not immediate) If you want to create new objects, just supply them with blank ID-fields, and _nextSequence() will be called to fetch a new ID used for insertion. The rule is one class pr. table, although it is possible to join several table into one class, as long as the identificator is unique. By defining _userClasses you can resolve links to other tables, a field in this table would be an id in another table, ie. another class. In practical use this means that behind attributes pointing to other classes (tables) you will find instances of that class. Short example usage of forgetterobjects: # Process all for user in User.getAllIterator(): # Access attributes print user.name print "Employed at:" # Access the Employed-class/table print user.employed.name, user.employed.address # fire him, setting employed reference to SQL NULL user.employed = None # Retrieve some ID shop = Shop(552) shop.name = 'Corrected name' shop.save() # Save now instead of waiting for garbage collactor # Include SQL where-statements in selections myIDs = User.getAllIDs(("name='soiland'", 'salary > 5')) Requirements: The attributes 'cursor' and '_dbModule' should be set from the outside. The cursor should be DB 2.0 complient, preferably with autocommit turned on. (Transactions are not within the scope of this module yet) Python 2.2 (iterators, methodclasses) """ # How long to keep objects in cache? _timeout = 60 # Will be 1 once prepare() is called _prepared = 0 # The default table containing our fields # _sqlTable = 'shop' _sqlTable = '' # A mapping between our fields and the database fields. # # You must include all fields needed here. You may specify # other names if you want to make the sql name more approriate # for object oriented programming. (Like calling a field 'location' # instead of 'location_id', because we wrap the location in a seperate # object and don't really care about the id) # # You may reference to other tables with a dot, all # other db fields will be related to _sqlTable. # If you reference other tables, don't forget to # modify _sqlLinks. # # _sqlFields = { # 'id': 'shop_id', # 'name': 'name', # 'location': 'location_id', # 'chain': 'shop_chain_id', # 'address': 'address.address_id', # } _sqlFields = {} # A list of attribute names (in the object, not database) # that are the primary key in the database. Normally # 'id' is sufficient. It is legal to have # multiple fields as primary key, but it won't work # properly with _userClasses and getChildren(). # # If your table is a link table or something, ALL fields # should be in _sqlPrimary. (all fields are needed to define # a unique row to be deleted/updated) _sqlPrimary = ('id',) # When using several tables, you should include a # 'link' statement, displaying which fields link the # two tables together. Note that these are sql names. # _sqlLinks = ( # ('shop_id', 'address.shop_id'), # ) _sqlLinks = () # The name of the sequence used by _nextSequence # - if None, a guess will be made based on _sqlTable # and _sqlPrimary. _sqlSequence = None # Order by this attribute by default, if specified # _orderBy = 'name' - this could also be a tupple _orderBy = None # _userClasses can be used to trigger creation of a field # with an instance of the class. The given database field # will be sent to the constructor as an objectID # (ie. as self.id in this object) (ie. the class does not # neccessary need to be a subclass of Forgetter) # # This means that the attribute will be an instance of that # class, not the ID. The object will not be loaded from the # database until you try to read any of it's attributes, # though. (to prevent unneccessary database overload and # recursions) # # Notice that _userClasses must be a name resolvable, ie. # from the same module as your other classes. # _userClasses = { # 'location': 'Location', # 'chain': 'Chain', # 'address': 'Address', # } _userClasses = {} # If you want userClasses to work properly with strings instead of # instances, you must also 'prepare' your classes to resolve the # names. This must be done from the same module you are defining the # classes: forgetSQL.prepareClasses(locals()) # A list of fields that are suitable for a textual # representation (typical a one liner). # # Fields will be joint together with spaces or # simular. # _shortView = ('name') _shortView = () # Description for the fields (ie. labels) # Note that these fields will be translated with the _ function. # If a field is undescribe, a capitalized version of the field name # will be presented. #_descriptions = { # 'name': 'Full name', # 'description': 'Description of thingie', #} _descriptions = {} def cursor(cls): try: import database return database.cursor() except: raise "cursor method undefined, no database connection could be made" cursor = classmethod(cursor) # a reference to the database module object used, ie. # MySQLdb, psycopg etc. # Use MyClass._dbModule = MySQLdb - not "MySQLdb" # _dbModule = None def __new__(cls, *args): if not hasattr(cls, '_cache'): cls._cache = {} try: # to implement 'goto' in Python.. UGH if not cls._cache.has_key(args): # unknown raise "NotFound" (ref, updated) = cls._cache[args] realObject = ref() if realObject is None: # No more real references to it, dead object raise "NotFound" age = time.time() - updated if age > cls._timeout: # Too old! raise "NotFound" updated = time.time() except "NotFound": # We'll need to create it realObject = object.__new__(cls, *args) ref = weakref.ref(realObject) updated = time.time() # store a weak reference cls._cache[args] = (ref, updated) return realObject def __init__(self, *id): """Initialize, possibly with a database id. A forgetter with multivalue primary key (ie. _sqlPrimary more than 1 in length), may be initalized by using several parameters to this constructor. Note that the object will not be loaded before you call load().""" self._values = {} self.reset() if not id: self._resetID() else: self._setID(id) def _setID(self, id): """Sets the ID, id can be either a list, following the _sqlPrimary, or some other type, that will be set as the singleton ID (requires 1-length sqlPrimary). """ if type(id) in (types.ListType, types.TupleType): try: for key in self._sqlPrimary: value = id[0] self.__dict__[key] = value id = id[1:] # rest, go revursive except IndexError: raise 'Not enough id fields, required: %s' % len(self._sqlPrimary) elif len(self._sqlPrimary) <= 1: # It's a simple value key = self._sqlPrimary[0] self.__dict__[key] = id else: raise 'Not enough id fields, required: %s' % len(self._sqlPrimary) self._new = False def _getID(self): """Gets the ID values as a tupple annotated by sqlPrimary""" id = [] for key in self._sqlPrimary: value = self.__dict__[key] if isinstance(value, Forgetter): # It's another object, we store only the ID if value._new: # It's a new object too, it must be saved! value.save() try: (value,) = value._getID() except: raise "Unsupported: Part %s of %s primary key is a reference to %s, with multiple-primary-key %s " % (key, self.__class__, value.__class__, value) id.append(value) return id def _resetID(self): """Resets all ID fields.""" # Dirty.. .=)) self._setID((None,) * len(self._sqlPrimary)) self._new = True def _validID(self): """Is all ID fields with values, ie. not None?""" return not None in self._getID() def __getattr__(self, key): """Will be called when an unknown key is to be retrieved, ie. most likely one of our database fields.""" if self._sqlFields.has_key(key): if not self._updated: self.load() return self._values[key] else: raise AttributeError, key def __setattr__(self, key, value): """Will be called whenever something needs to be set, so we store the value as a SQL-thingie unless the key is not listed in sqlFields.""" if key not in self._sqlPrimary and self._sqlFields.has_key(key): if not self._updated: self.load() self._values[key] = value self._changed = time.time() else: # It's a normal thingie self.__dict__[key] = value def __del__(self): """Saves the object on deletion. Be aware of this. If you want to undo some change, use reset() first. Be aware of Python 2.2's garbage collector, that might run in the background. This means that unless you call save() changes might not be done immediately in the database. Not calling save() also means that you cannot catch errors caused by wrong insertion/update (ie. wrong datatype for a field) """ try: self.save() except Exception, e: pass def _checkTable(cls, field): """Splits a field from _sqlFields into table, column. Registers the table in cls._tables, and returns a fully qualified table.column (default table: cls._sqlTable)""" # Get table part try: (table, field) = field.split('.') except ValueError: table = cls._sqlTable # clean away white space table = table.strip() field = field.strip() # register table cls._tables[table] = None # and return in proper shape return table + '.' + field _checkTable = classmethod(_checkTable) def reset(self): """Reset all fields, almost like creating a new object. Note: Forgets changes you have made not saved to database! (Remember: Others might reference the object already, expecting something else!) Override this method if you add properties not defined in _sqlFields""" self._resetID() self._new = None self._updated = None self._changed = None self._values = {} # initially create fields for field in self._sqlFields.keys(): self._values[field] = None def load(self, id=None): """Loads from database. Old values will be discarded.""" if id is not None: # We are asked to change our ID to something else self.reset() self._setID(id) if not self._new and self._validID(): self._loadDB() self._updated = time.time() def save(self): """Saves to database if anything has changed since last load""" if ( self._new or (self._validID() and self._changed) or (self._updated and self._changed > self._updated) ): # Don't save if we have not loaded existing data! self._saveDB() return True return False def delete(self): """Marks this object for deletion in the database. The object will then be reset and ready for use again with a new id.""" (sql, ) = self._prepareSQL("DELETE") curs = self.cursor() curs.execute(sql, self._getID()) curs.close() self.reset() def _prepareSQL(cls, operation="SELECT", where=None, selectfields=None, orderBy=None): """Returns a sql for the given operation. Possible operations: SELECT read data for this id SELECTALL read data for all ids INSERT insert data, create new id UPDATE update data for this id DELETE remove data for this id SQL will be built by data from _sqlFields, and will contain 0 or several %s for you to sprintf-format in later: SELECT --> len(cls._sqlPrimary) SELECTALL --> 0 %s INSERT --> len(cls._sqlFields) %s (including id) UPDATE --> len(cls._sqlFields) %s (including id) DELETE --> len(cls._sqlPrimary) (Note: INSERT and UPDATE will only change values in _sqlTable, so the actual number of fields for substitutions might be lower than len(cls._sqlFields) ) For INSERT you should use cls._nextSequence() to retrieve a new 'id' number. Note that if your sequences are not named tablename_primarykey_seq (ie. for table 'blapp' with primary key 'john_id', sequence name blapp_john_id_seq) you must give the sequence name as an optional argument to _nextSequence) Additional note: cls._nextSequence() MUST be overloaded for multi _sqlPrimary classes. Return a tupple. Return values will always be tuples: SELECT --> (sql, fields) SELECTALL -> sql, fields) INSERT -> (sql, fields) UPDATE -> (sql, fields) DELETE -> (sql,) -- for consistency fields will be object properties as a list, ie. the keys from cls._sqlFields. The purpose of this list is to give the programmer an idea of which order the keys are inserted in the SQL, giving help for retreiving (SELECT, SELECTALL) or inserting for %s (INSERT, DELETE). Why? Well, the keys are stored in a hash, and we cannot be sure about the order of hash.keys() from time to time, not even with the same instance. Optional where-parameter applies to SELECT, SELECTALL and DELETE. where should be a list or string of where clauses. """ # Normalize parameter for later comparissions operation = operation.upper() # Convert where to a list if it is a string if type(where) in (types.StringType, types.UnicodeType): where = (where,) if orderBy is None: orderBy = cls._orderBy if operation in ('SELECT', 'SELECTALL'): # Get the object fields and sql fields in the same # order to be able to reconstruct later. fields = [] sqlfields = [] for (field, sqlfield) in cls._sqlFields.items(): if selectfields is None or field in selectfields: fields.append(field) sqlfields.append(sqlfield) if not fields: # dirrrrrty! raise """ERROR: No fields defined, cannot create SQL. Maybe sqlPrimary is invalid? Fields asked: %s My fields: %s""" % (selectfields, cls._sqlFields) sql = "SELECT\n " sql += ', '.join(sqlfields) sql += "\nFROM\n " tables = cls._tables.keys() if not tables: raise "REALITY ERROR: No tables defined" sql += ', '.join(tables) tempWhere = ["%s=%s" % linkPair for linkPair in cls._sqlLinks] # this MUST be here. if operation <> 'SELECTALL': for key in cls._sqlPrimary: tempWhere.append(cls._sqlFields[key] + "=%s") if where: tempWhere += where if(tempWhere): # Make sure to use paranteses in case someone has used # ORs in the WHERE-list.. sql += "\nWHERE\n (" sql += ') AND\n ('.join(tempWhere) sql += ')' if operation == 'SELECTALL' and orderBy: sql += '\nORDER BY\n ' if type(orderBy) in (types.TupleType, types.ListType): orderBy = [cls._sqlFields[x] for x in orderBy] orderBy = ',\n '.join(orderBy) else: orderBy = cls._sqlFields[orderBy] sql += orderBy return (sql, fields) elif operation in ('INSERT', 'UPDATE'): if operation == 'UPDATE': sql = 'UPDATE %s SET\n ' % cls._sqlTable else: sql = 'INSERT INTO %s (\n ' % cls._sqlTable set = [] fields = [] sqlfields = [] for (field, sqlfield) in cls._sqlFields.items(): if operation == 'UPDATE' and field in cls._sqlPrimary: continue if sqlfield.find(cls._sqlTable + '.') == 0: # It's a local field, chop of the table part sqlfield = sqlfield[len(cls._sqlTable)+1:] fields.append(field) sqlfields.append(sqlfield) set.append(sqlfield + '=%s') if operation == 'UPDATE': sql += ',\n '.join(set) sql += '\nWHERE\n ' tempWhere = [] for key in cls._sqlPrimary: tempWhere.append(cls._sqlFields[key] + "=%s") fields.append(key) sql += ' AND\n '.join(tempWhere) else: sql += ',\n '.join(sqlfields) sql += ')\nVALUES (\n ' sql += ',\n '.join(('%s',) * len(sqlfields)) sql += ')' return (sql, fields) elif operation == 'DELETE': sql = 'DELETE FROM ' + cls._sqlTable + ' WHERE ' if where: sql += " AND\n ".join(where) else: for key in cls._sqlPrimary: tempWhere = [] for key in cls._sqlPrimary: tempWhere.append(cls._sqlFields[key] + "=%s") sql += ' AND\n '.join(tempWhere) return (sql, ) else: raise "Unknown operation", operation _prepareSQL = classmethod(_prepareSQL) def _nextSequence(cls, name=None): """Returns a new sequence number for insertion in self._sqlTable. Note that if your sequences are not named tablename_primarykey_seq (ie. for table 'blapp' with primary key 'john_id', sequence name blapp_john_id_seq) you must give the full sequence name as an optional argument to _nextSequence) """ if not name: name = cls._sqlSequence if not name: # Assume it's tablename_primarykey_seq if len(cls._sqlPrimary) <> 1: raise "Could not guess sequence name for multi-primary-key" primary = cls._sqlPrimary[0] name = '%s_%s_seq' % (cls._sqlTable, primary.replace('.','_')) # Don't have . as a tablename or column name! =) curs = cls.cursor() curs.execute("SELECT nextval('%s')" % name) value = curs.fetchone()[0] curs.close() return value _nextSequence = classmethod(_nextSequence) def _loadFromRow(self, result, fields, cursor): """Load from a database row, described by fields. fields should be the attribute names that will be set. Note that userclasses will be created (but not loaded). """ position = 0 for elem in fields: value = result[position] valueType = cursor.description[position][1] if hasattr(self._dbModule, 'BOOLEAN') and \ valueType == self._dbModule.BOOLEAN and \ (value is not True or value is not False): # convert to a python boolean value = value and True or False if value and self._userClasses.has_key(elem): userClass = self._userClasses[elem] # create an instance value = userClass(value) self._values[elem] = value position += 1 def _loadDB(self): """Connects to the database to load myself""" if not self._validID(): raise NotFound, self._getID() (sql, fields) = self._prepareSQL("SELECT") curs = self.cursor() curs.execute(sql, self._getID()) result = curs.fetchone() curs.close() if not result: raise NotFound, self._getID() self._loadFromRow(result, fields, curs) self._updated = time.time() def _saveDB(self): """Inserts or updates into the database. Note that every field will be updated, not just the changed one.""" # We're a "fresh" copy now self._updated = time.time() if self._new: operation = 'INSERT' if not self._validID(): self._setID(self._nextSequence()) # Note that we assign this ID to our self # BEFORE possibly saving any of our attribute # objects that might be new as well. This means # that they might have references to us, as long # as the database does not require our existence # yet. # # Since mysql does not have Sequences, this will # not work as smoothly there. See class # MysqlForgetter below. else: operation = 'UPDATE' (sql, fields) = self._prepareSQL(operation) values = [] for field in fields: value = getattr(self, field) # First some dirty datatype hacks if DateTime and type(value) == DateTime.DateTimeType: # stupid psycopg does not support it's own return type.. # lovely.. value = str(value) if DateTime and type(value) == DateTime.DateTimeDeltaType: # Format delta as days, hours, minutes seconds # NOTE: includes value.second directly to get the # whole floating number value = value.strftime("%d %H:%M:") + str(value.second) if value is True or value is False: # We must store booleans as 't' and 'f' ... value = value and 't' or 'f' if isinstance(value, Forgetter): # It's another object, we store only the ID if value._new: # It's a new object too, it must be saved! value.save() try: (value,) = value._getID() except: raise "Unsupported: Can't reference multiple-primary-key: %s" % value values.append(value) cursor = self.cursor() cursor.execute(sql, values) # cursor.commit() cursor.close() self._new = False def getAll(cls, where=None, orderBy=None): """Retrieves all the objects, possibly matching the where list of clauses, that will be AND-ed. This will not load everything out from the database, but will create a large amount of objects with only the ID inserted. The data will be loaded from the objects when needed by the regular load()-autocall.""" ids = cls.getAllIDs(where, orderBy=orderBy) # Instansiate a lot of them if len(cls._sqlPrimary) > 1: return [cls(*id) for id in ids] else: return [cls(id) for id in ids] getAll = classmethod(getAll) def getAllIterator(cls, where=None, buffer=100, useObject=None, orderBy=None): """Retrieves every object, possibly limitted by the where list of clauses that will be AND-ed). Since this an iterator is returned, only buffer rows are loaded from the database at once. This is useful if you need to process all objects. If useObject is given, this object is returned each time, but with new data. """ (sql, fields) = cls._prepareSQL("SELECTALL", where, orderBy=orderBy) curs = cls.cursor() fetchedAt = time.time() curs.execute(sql) # We might start eating memory at this point def getNext(rows=[]): forgetter = cls if not rows: rows += curs.fetchmany(buffer) if not rows: curs.close() return None row = rows[0] del rows[0] try: idPositions = [fields.index(key) for key in cls._sqlPrimary] except ValueError: raise "Bad sqlPrimary, should be a list or tupple: %s" % cls._sqlPrimary ids = [row[pos] for pos in idPositions] if useObject: result = useObject result.reset() result._setID(ids) else: result = forgetter(*ids) result._loadFromRow(row, fields, curs) result._updated = fetchedAt return result return iter(getNext, None) getAllIterator = classmethod(getAllIterator) def getAllIDs(cls, where=None, orderBy=None): """Retrives all the IDs, possibly matching the where clauses. Where should be some list of where clauses that will be joined with AND). Note that the result might be tuples if this table has a multivalue _sqlPrimary.""" (sql, fields) = cls._prepareSQL("SELECTALL", where, cls._sqlPrimary, orderBy=orderBy) curs = cls.cursor() curs.execute(sql) # We might start eating memory at this point rows = curs.fetchall() curs.close() result = [] idPositions = [fields.index(key) for key in cls._sqlPrimary] for row in rows: ids = [row[pos] for pos in idPositions] if len(idPositions) > 1: ids = tuple(ids) else: ids = ids[0] result.append((ids)) return result getAllIDs = classmethod(getAllIDs) def getAllText(cls, where=None, SEPERATOR=' ', orderBy=None): """Retrieves a list of of all possible instances of this class. The list is composed of tupples in the format (id, description) - where description is a string composed by the fields from cls._shortView, joint with SEPERATOR. """ (sql, fields) = cls._prepareSQL("SELECTALL", where, orderBy=orderBy) curs = cls.cursor() curs.execute(sql) # We might start eating memory at this point rows = curs.fetchall() curs.close() result = [] idPositions = [fields.index(key) for key in cls._sqlPrimary] shortPos = [fields.index(short) for short in cls._shortView] for row in rows: ids = [row[pos] for pos in idPositions] if len(idPositions) > 1: ids = tuple(ids) else: ids = ids[0] text = SEPERATOR.join([str(row[pos]) for pos in shortPos]) result.append((ids, text)) return result getAllText = classmethod(getAllText) def getChildren(self, forgetter, field=None, where=None, orderBy=None): """Returns the children that links to me. That means that I have to be listed in their _userClasses somehow. If field is specified, that field in my children is used as the pointer to me. Use this if you have multiple fields referring to my class.""" if type(where) in (types.StringType, types.UnicodeType): where = (where,) if not field: for (i_field, i_class) in forgetter._userClasses.items(): if isinstance(self, i_class): field = i_field break # first one found is ok :=) if not field: raise "No field found, check forgetter's _userClasses" sqlname = forgetter._sqlFields[field] myID = self._getID()[0] # assuming single-primary ! whereList = ["%s='%s'" % (sqlname, myID)] if where: whereList.extend(where) return forgetter.getAll(whereList, orderBy=orderBy) def __repr__(self): return self.__class__.__name__ + ' %s' % self._getID() def __str__(self): shortView = self._shortView or self._sqlPrimary short = [str(getattr(self, short)) for short in shortView] text = ', '.join(short) # return repr(self) + ': ' + text return text def __eq__(self, obj): """Simple comparsion of objects.""" return self.__class__.__name__ == obj.__class__.__name__ \ and self._getID() == obj._getID() class MysqlForgetter(Forgetter): """MYSQL-compatible Forgetter""" def _saveDB(self): """Overloaded - we dont have nextval() in mysql""" # We're a "fresh" copy now self._updated = time.time() if self._new: operation = 'INSERT' else: operation = 'UPDATE' (sql, fields) = self._prepareSQL(operation) values = [] for field in fields: value = getattr(self, field) if isinstance(value, Forgetter): # It's another object, we store only the ID if value._new: # It's a new object too, it must be saved! value.save() try: (value,) = value._getID() except: raise "Can't reference multiple-primary-key: %s" % value values.append(value) cursor = self.cursor() cursor.execute(sql, values) # cursor.commit() if not self._validID(): if not len(self._getID()) == 1: raise "Can't retrieve auto-inserted ID for multiple-primary-key" # Here's the mysql magic to get the new ID self._setID(cursor.insert_id()) cursor.close() self._new = False def prepareClasses(locals): """Fix _userClasses and some stuff in classes. Traverses locals, which is a locals() dictionary from the namespace where Forgetter subclasses have been defined, and resolves names in _userClasses to real class-references. Normally you would call forgettSQL.prepareClasses(locals()) after defining all classes in your local module. prepareClasses will only touch objects in the name space that is a subclassed of Forgetter.""" for (name, forgetter) in locals.items(): if not (type(forgetter) is types.TypeType and issubclass(forgetter, Forgetter)): # Only care about Forgetter objects continue # Resolve classes for (key, userclass) in forgetter._userClasses.items(): if type(userclass) is types.StringType: # resolve from locals resolved = locals[userclass] forgetter._userClasses[key] = resolved forgetter._tables = {} # Update all fields with proper names for (field, sqlfield) in forgetter._sqlFields.items(): forgetter._sqlFields[field] = forgetter._checkTable(sqlfield) newLinks = [] for linkpair in forgetter._sqlLinks: (link1, link2) = linkpair link1=forgetter._checkTable(link1) link2=forgetter._checkTable(link2) newLinks.append((link1, link2)) forgetter._sqlLinks = newLinks forgetter._prepared = 1 forgetsql-0.5.1/README0000644000175000001440000004756210023042142015066 0ustar wernerusers00000000000000================ forgetSQL readme ================ :Author: Stian Soiland :WWW: http://forgetsql.sourceforge.net/ :License: GNU Lesser General Public License (LGPL) See the file COPYING for details. :Status: unfinished :Abstract: forgetSQL is a Python module for accessing SQL databases by creating classes that maps SQL tables to objects, normally one class pr. SQL table. The idea is to forget everything about SQL and just worrying about normal classes and objects. .. contents:: Contents Installation ============ Installation of the forgetSQL module is pretty straight forward: python setup.py install This will install forgetSQL.py into site-packages/ of your Python distribution. Dependencies ------------ * Python 2.2.1 (True/False, new style classes, classmethods, iterators) * Some database module (tested: MySQLdb, psycopg) If using psycopg, mx.DateTime is needed to avoid a psycopg bug related to re-inserting dates. psycopg depends on mx.DateTime, so that shouldn't be a problem. What is forgetSQL? ================== Why forgetSQL? -------------- Let's start by showing an example using an imaginary database ``mydatabase``: This example is based on these SQL tables: account ~~~~~~~ =========== ================= ======= accountid fullname groupid =========== ================= ======= stain Stian Soiland 15 magnun Magnus Nordseth 15 stornes Sverre Stornes 17 mjaavatt Erlend Mjaavatten 15 =========== ================= ======= group ~~~~~ ======= ==== groupid name ======= ==== 15 unix 17 tie ======= ==== And should output something like:: Account details for Stian Søiland Group unix (15) Other members: Magnus Nordseth Erlend Mjaavatten In regular SQL programming, this could be done something like this:: cursor = dbconn.cursor() cursor.execute("SELECT fullname,groupid FROM account WHERE accountid=%s", ('stain',)) fullname,groupid = cursor.fetchone() print "Account details for", fullname cursor.execute("SELECT name FROM group WHERE groupid=%s" % groupid) (groupname,) = cursor.fetchone() print "Group %s (%s)" % (groupid, name) cursor.execute("""SELECT fullname FROM account JOIN group USING (groupid) WHERE group.groupid=%s AND NOT account.accountid=%s""", (groupid, accountid)) print "Other members:" for (membername,) in cursor.fetchall(): print membername Now, using forgetSQL:: from mydatabase import * account = Account("stain") # primary key print "Account details for", account.fullname group = account.group print "Group %s (%s)" % (group.name, group.groupid) print "Other members: " for member in group.getChildren(Account): # find Account with group as foreign key if member <> account: print member.fullname Notice the difference in size and complexity of these two examples. The first example is tightly bound against SQL. The programmer is forced to think about SQL instead of the real code. This programming style tends to move high-level details to SQL, even if it is not neccessary. In this example, when getting "other members", the detail of skipping the active user is done in SQL. This would hardly save any CPU time on modern computers, but has made the code more complex. Thinking in SQL makes your program very large, as everything can be solved by some specialized SQL. Trying to change your program or database structure at a later time would be a nightmare. Now, forgetSQL removes all those details for the every-day-SQL tasks. It will not be hyper-effective or give you points in the largest-join-ever-possible-contest, but it will help you focus on what you should be thinking of, making your program work. If you at a later point (when everything runs without failures) discovers that you need to optimize something with a mega-query in SQL, you could just replace that code with regular SQL operations. Of course, if you've been using test-driven development (like in http://c2.com/cgi/wiki?ExtremeProgramming ) your tests will show if the replaced code works. Another alternative could be to use views and stored procedure, and layer forgetSQL on top of those views and procedures. This has never been tested, though. =) What does forgetSQL do? ----------------------- For each table in your database, a class is created. Each instance created of these classes refer to a row in the given table. Each instance have attributes that refer to the fields in the database. Note that the instance is not created until you access that particular row. So accessing a column of a row is simply accessing the attribute ``row.column``. Now, if this column is a reference to another table, a foreign key, instead of an identifier you will in ``row.column`` find an instance from the other table, ie. from the other class. This is what happens in the example above, ``group = account.group`` retrieves this instance. Further attribute access within this instance is resolved from the matching row in the group table. If you want to change some value, you could just change the attribute value. In the example, if you want to change my name, simply run ``account.fullname = "Knut Carlsen"`` (my boss). You can retrieve every row in some table that refers to the current object. This is what happens in ``group.getChildren(Account)``, which will return a list of those Accounts that have a foreign key refering to ``group``. If you retrieve the objects several times, the constructor will return the same object the second time (unless some timeout has expired). This means that changes done to the object is immediately visible to all instances. This is to reflect normal behaviour in object oriented programming. >>> stain = Account("stain") >>> stain2 = Account("stain") >>> stain.fullname = "Knut Carlsen" >>> print stain2.fullname Knut Carlsen What does forgetSQL not do? --------------------------- forgetSQL is not a way to store objects in a database. It is a way to use databases as objects. You cannot store arbitrary objects in the database unless you use pickling. forgetSQL does not help you with database design, although you might choose a development style that uses regular classes and objects at first, and then design the database afterwards. You could then change your classes to use forgetSQL for data retrieval and storage, and later possibly replace forgetSQL classes with even more advanced objects. forgetSQL does not remove the need of heavy duty SQL. In some situations, SQL is simply the best solution. forgetSQL might involve many SQL operations for something that could be done in a single operations with a large magic query. If something does not scale up with forgetSQL, even if you refactored your code, you might try using SQL instead. This example would use excessive time in a table with a million rows:: for row in table.getAll(): row.backedUp = True row.save() This would involve creating one million object instances (each row), one million SELECTs (to get the other values that needs to be saved), and one million UPDATEs. By using ``getAllIterator`` you could reduce this to just one million UPDATEs (one SELECT, reusing the same object), but still it would be far much slower than ``UPDATE table SET backedUp=true``. forgetSQL does not support commits/rollback. This might be implemented later, but I'm still unsure of how to actually use this in programming. Any suggestions are welcome. Keeping in sync ~~~~~~~~~~~~~~~ forgetSQL does not ensure that objects in memory are in sync with what is stored in the database. The values in the object will be a snapshot of how the row were at the time you first tried to retrieve an attribute. If you change some value, and then save the object, the row is updated to your version, no matter what has happened in the database meanwhile. An object does not timeout while in memory, it does not refresh it's values unless you call ``_loadDB()`` manually, as automatically updating could confuse programmers. However, a timeout value is set, and if exceeded, *new* objects retrieved from database (ie. ``Account("stain")`` will be fresh. It is not easy to make a general way to ensure objects are updated. For instance, always checking it could be heavy. It could also confuse some programs if an object suddenly changes some of it's attributes without telling, this could fuck up any updates the program is attempting to do. On the other hand, saving a changed object as forgetSQL is now, will overwrite *all* attributes, not just the changed ones. Usage ===== forgetsql-generate ------------------ Before you can use forgetSQL, you will need to generate a module containg the classes representing database tables. Luckily, forgetSQL ships with a program that can do this for you by guessing. The program is called ``forgetsql-generate`` and should be installed by ``setup.py`` or the packaging system. You might need the devel-version of the forgetSQL package. Create a file ``tables.txt``, with a list of database tables, one per line. (This is needed since there is no consistent way to query a database about it's tables) Then generate the module representing your tables:: forgetsql-generate --dbmodule psycopg --username=johndoe --password=Jens1PuLe --database=genious --tables tables.txt --output Genious.py Alternative, you could pipe the table list to ``forgetsql-generate`` and avoid ``--tables`` -- and likewise drop ``--output`` and capture stdout from forgetsql-generate. The generated module is ready for use, except that you need should set database connecting details. One possible way is included in the generated code, commented out and without a password. It is recommended to set connection details from the outside instead, since the tables might be used by different parts of a system using different database passwords, connection details could be in a configuration file, you need persistent database connections, etc. The way to do this is to set Genious._Wrapper.cursor to a cursor method, and Genious._Wrapper._dbModule to the database module used:: import Genious import psycopg conn = psycopg.connect(user="blal", pass="sdlksdlk", database="blabla") Genious._Wrapper.cursor = conn.cursor() Genious._Wrapper._dbModule = psycopg This should be refactored to a more userfriendly interface. Normal use ---------- We'll call a class that is a representation of a database table a forgetter, because it inherits forgetSQL.Forgetter. This chapter will present normal usage of such forgetters by examples. Getting a row by giving primary key ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Example:: account = Account("stain") print account.fullname If the primary key is wrong (ie. the row does not exist) accessing ``account.fullname`` will raise ``forgetSQL.NotFound``. The object is actually not loaded from the database until a attribute is read. (delayed loading) One problem with that is that ``forgetSQL.NotFound`` will not be raised until the attribute is read. To test if the primary key is valid, force a load:: account = Account("stain") try: account.load() except forgetSQL.NotFound(): print "Cannot find stain" return Getting all rows in a table ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Example:: allAccounts = Account.getAll() for account in allAccounts: print account.accountid, account.fullname Note that ``getAll`` is a class method, so it is available even before creating some ``Account``. The returned list will be empty if nothing is found. Also note that if what you want to do is to iterate, using ``getAllIterator()`` would work well. This avoids creating all objects at once. To create a new row in a table ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Example:: account = Account() account.accountid = "jennyme" # primary key account.fullname = "Jenny Marie Ellingsaeter" account.save() If you have forgotten to set some required fields, save() will fail. If you don't set the primary key, forgetSQL will try to guess the sequence name (tablename_primarykey_seq) to retrieve a new one. This might or might not work. For MySQL some other magic is involved, but it should work. Change some attribute ~~~~~~~~~~~~~~~~~~~~~ Example:: account = Account("stain") account.fullname = "Stian Stornes" # got married to a beautiful man You can choose wether you want to call ``save()`` or not. If you don't call ``save()``, the object will be saved when the object reference disappaers (ie. del account, end of function, etc.) and collected by the garbage collector. Note that this might be delayed, and that any errors will be disgarded. If you are unsure if you have used the correct datatype or want to catch save-errors, use ``save()``:: group = Group(17) group.accountid = 'itil' # a string won't work in a integer field try: group.save() except Exception, e: print "Could not save group %s: %s" % (group, e) The exception raised will be database module specific, like ``psycopg.ProgrammingError``, possible containing some useful information. ``save()`` will return ``True`` if successful. Undoing an attribute change ~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you changed an attribute, and you don't want to save the change to the database (as this will happen when the garbage collector kicks in), you have two choices: * reset the instance to a blank state:: group.reset() This sets everything to None, including the primary key. If you have referenced the instance anywhere else, they will now experience a blank instance. * reload from database:: group.load() Note, ``load()`` will perform a new SELECT. Note that you don't have to ``reset()`` if you haven't changed any attributes, the instance will only save if anything has changed. Access foreign keys ~~~~~~~~~~~~~~~~~~~ Example:: account = Account("stain") print account.group.accountid print account.group.name An attribute which is a foreign key to some other table will be identified by forgetsql-generate if it's name is something like ``other_table_id``. If the generator could not identify foreign keys correctly, modify ``_userClasses`` in the generated Forgetter definition. (See `Specializing the forgetters`_). To access the real primary key, use account.group.accountid or account.group._getID(). Note that the latter will return a tupple (in case the primary key contained several columns).o You can set a foreign key attribute to a new object from the foreign class:: import random allGroups = Group.getAll() for account in Account.getAll(): # Set the group to one of the Group instances # in allGroups account.group = random.choice(allGroups) del account # Note that by reusing the account variable all of these # will be saved by the garbage collector or to just the foreign primary key:: account.group = 18 Note that this referencing magic makes JOIN unneccessary in many cases, but be aware that due to lazy loading (attributes are not loaded from database before they are accessed for the first time), in some cases this might result in many SELECT-calls. There are ways to avoid this, see `Wrapping SQL queries`_. Finding foreign keys ~~~~~~~~~~~~~~~~~~~~ You might want to walk in reverse, finding all accounts that have a given group as a foreign key:: group = Group(15) members = group.getChildren(Account) This is equivalent to SQL:: SELECT * FROM account WHERE groupid=15 Deleting an instance ~~~~~~~~~~~~~~~~~~~~ Note that although rows are represented as instances, they will not be deleted from the database by dereferencing. Simply removing a name binding only removes the representation. (and actually forces a ``save()`` if anything has changed). To remove a row from the database:: account = Account("stornes") account.delete() ``delete()`` might fail if your database claims reference integrity but does not cascade delete:: group = Group(17) group.delete() Advanced use ------------ WHERE-clasules ~~~~~~~~~~~~~~ You may specify a where-sentence to be inserted into the SELECT-call of ``getAll``-methods:: members = Account.getAll(where="groupid=17") Note that you must take care of proper escaping on your own by using this approach. Most database modules have some form of escape functions. In many cases, what you want to do with WHERE is probably the same as with ``getChildren()``:: group = Group(17) members = group.getChildren(Account) This will be as effective as generating a WHERE-clasule, since ``group.load()`` won't be run (no attributes accessed, only the primary key). The sentence is directly inserted, so you need to use the actual SQL column names, not the attribute names. You can use AND and OR as you like. If you have several clauses to be AND-ed together, forgetSQL can do this for you, as the where-parameter can be a list:: where = [] where.append("groupid=17") if something: where.append("fullname like 'Stian%'") Account.getAll(where=where) Sorting ~~~~~~~ If you have specified ``_orderBy`` (see `Specializing the forgetters`_), the results of ``getAll*`` and ``getChildren`` will be ordered by those attributes. If you want to specify ordering manually, you can supply a keyword argument to getAll:: all = Account.getAll(orderBy="fullname") The value of ``orderBy`` could be either a string (representing the object attribute to be sorted) or a tupple of strings (order by A, then B, etc.). Note that you can only order by attributes defined in the given table. If you want some other fancy sorting, sort the list after retrieval using regular ``list.sort()``:: all = Account.getAll() all.sort(lambda a,b: cmp(a.split()[-1], b.split()[-1])) # order by last name! :=) More getAll ~~~~~~~~~~~ There are specialized ``getAll`` methods for different situations. If you just want the IDs in a table:: >>> all = Account.getAllIDs() ['stornes', 'stain', 'magnun', 'mjaavatt'] The regular ``getAll()`` actually runs ``getAllIDs()``, and returns a list of instances based on those IDs. The real data is not loaded until attribute access. In some cases, this might be OK, for instance if you want to call getChildren and really don't care about the attribute values. If you are going to iterate through the list, a common case, use instead:: for account in Account.getAllIterator(): print account.fullname This will return an iterator, not a list, returning ``Account`` objects. For each iteration, a new instance is returned, with all fields loaded. Internally in the iterator, a buffer of results from SELECT * is contained. In Python, object creation is a bit expensive, so you might reuse the same object for each iteration by creating it first and specifying it as the keyword argument ``useObject``:: for account in Account.getAllIterator(useObject=Account()): print account.fullname Note that changes made to account in this case will be flushed unless you manually call ``save()``. Do not pass this instance on, as it's content will change for each iteration. Finally, ``getAllText()`` will use ``_shortView`` (See `Specializing the forgetters`_) and return tupples of (id, text). This is useful for a dropdown-list of selectors. Specializing the forgetters --------------------------- .. About specifying and correcting _sqlFields, etc. Sorry, this section is currently unfinished. Wrapping SQL queries -------------------- .. About joins, views, functions. Sorry, this section is currently unfinished. Framework suggestion -------------------- .. My suggestions for how you should wrap up things nicely, .. How to deal with database connections and extensions. Sorry, this section is currently unfinished. forgetsql-0.5.1/TODO0000444000175000001440000000277210022474122014674 0ustar wernerusers00000000000000TODO for forgetSQL ================== * rollback/commits how to do it in programs using forgetSQL? how to do it internally? * objects should timeout as well, but what should happen? raise TimeOutException ? Try a passive reload, and only raise exception if something has changed in the database? * generator should take parameters for database connection details * generator should try to fetch table lists from mysql/postgresql if possible * generated framework (_Wrapper and it's like) needs to be refactored - to make it easier to set database cursor and module. Could the set-module be avoided? Framework should include the suggestion of specializing in a subclassing module - to allow regeneration. * getAll* should try to use the _cache - but what about getAllIterator and the useObject? Maybe the getAll-things should be changed, when using getAll but not loading datas be appropriate? What about loading data immediately to _values, but skip instanciating _userClasses until __getattr__ ? * Include attributes in dir() -- how to do this? Skip the _values dictionary? There is another method almost like __getattr__ that I don't remember, it is called for EVERY attribute access, not just the non-existing ones. Use this? * Only fields changed should be stored in an UPDATE * connection details should be made easier to set * documentation, documentation, documentation! More examples, please! -- README added, but needs more work forgetsql-0.5.1/BUGS0000644000175000001440000000055410023040246014662 0ustar wernerusers00000000000000Known bugs for forgetSQL ======================== See also http://www.sourceforge.net/project/forgetsql for the Bug database. * getAll* and getChildren does not neccessarily use the cached version. * empty/wrong _sqlPrimary for tables with no obvious primary key - should select ALL fields as primary keys to avoid stupid error messages. forgetsql-0.5.1/COPYING0000444000175000001440000006365010022474122015241 0ustar wernerusers00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. ^L Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. ^L GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. ^L Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. ^L 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. ^L 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. ^L 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. ^L 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS ^L How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! forgetsql-0.5.1/setup.py0000755000175000001440000000145410023061643015720 0ustar wernerusers00000000000000#!/usr/bin/env python from distutils.core import setup # Whyyyyyyy oh whyyy doesn't distutils do this !?? # (if you forget this - root with umask 0077 # will install non-readable libraries) import os if os.geteuid() == 0: os.umask(0022) setup(name="forgetSQL", version="0.5.1", author="Stian Soiland", author_email="stian@soiland.no", url="http://forgetsql.sourceforge.net/", license="LGPL", description= """forgetSQL is a Python module for accessing SQL databases by creating classes that maps SQL tables to objects, normally one class pr. SQL table. The idea is to forget everything about SQL and just worrying about normal classes and objects.""", py_modules=['forgetSQL'], scripts = ['bin/forgetsql-generate'], package_dir = {'': 'lib'}, ) forgetsql-0.5.1/PKG-INFO0000644000175000001440000000070410023062130015265 0ustar wernerusers00000000000000Metadata-Version: 1.0 Name: forgetSQL Version: 0.5.1 Summary: forgetSQL is a Python module for accessing SQL databases by creating classes that maps SQL tables to objects, normally one class pr. SQL table. The idea is to forget everything about SQL and just worrying about normal classes and objects. Home-page: http://forgetsql.sourceforge.net/ Author: Stian Soiland Author-email: stian@soiland.no License: LGPL Description: UNKNOWN Platform: UNKNOWN