0001"""0002SQLObject0003---------00040005:author: Ian Bicking <ianb@colorstudy.com>00060007SQLObject is a object-relational mapper. See SQLObject.html or0008SQLObject.txt for more.00090010With the help by Oleg Broytman and many other contributors.0011See Authors.txt.00120013This program is free software; you can redistribute it and/or modify0014it under the terms of the GNU Lesser General Public License as0015published by the Free Software Foundation; either version 2.1 of the0016License, or (at your option) any later version.00170018This program is distributed in the hope that it will be useful,0019but WITHOUT ANY WARRANTY; without even the implied warranty of0020MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the0021GNU General Public License for more details.00220023You should have received a copy of the GNU Lesser General Public0024License along with this program; if not, write to the Free Software0025Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301,0026USA.0027"""0028importsys0029importthreading0030importweakref0031importtypes0032importwarnings0033from.importsqlbuilder0034from.importdbconnection0035from.importcol0036from.importstyles0037from.importjoins0038from.importindex0039from.importclassregistry0040from.importdeclarative0041from.importevents0042from.sresultsimportSelectResults0043from.util.threadinglocalimportlocal0044fromsqlobject.compatimportPY2,with_metaclass,string_type,unicode_type00450046if((sys.version_info[0]==2)and(sys.version_info[:2]<(2,6)))or((sys.version_info[0]==3)and(sys.version_info[:2]<(3,4))):0048raiseImportError("SQLObject requires Python 2.6, 2.7 or 3.4+")00490050ifnotPY2:0051# alias for python 3 compatability0052long=int00530054"""0055This thread-local storage is needed for RowCreatedSignals. It gathers0056code-blocks to execute _after_ the whole hierachy of inherited SQLObjects0057is created. See SQLObject._create0058"""00590060NoDefault=sqlbuilder.NoDefault006100620063classSQLObjectNotFound(LookupError):0064pass006500660067classSQLObjectIntegrityError(Exception):0068pass006900700071defmakeProperties(obj):0072"""0073 This function takes a dictionary of methods and finds0074 methods named like:0075 * _get_attr0076 * _set_attr0077 * _del_attr0078 * _doc_attr0079 Except for _doc_attr, these should be methods. It0080 then creates properties from these methods, like0081 property(_get_attr, _set_attr, _del_attr, _doc_attr).0082 Missing methods are okay.0083 """00840085ifisinstance(obj,dict):0086defsetFunc(var,value):0087obj[var]=value0088d=obj0089else:0090defsetFunc(var,value):0091setattr(obj,var,value)0092d=obj.__dict__00930094props={}0095forvar,valueind.items():0096ifvar.startswith('_set_'):0097props.setdefault(var[5:],{})['set']=value0098elifvar.startswith('_get_'):0099props.setdefault(var[5:],{})['get']=value0100elifvar.startswith('_del_'):0101props.setdefault(var[5:],{})['del']=value0102elifvar.startswith('_doc_'):0103props.setdefault(var[5:],{})['doc']=value0104forvar,settersinprops.items():0105iflen(setters)==1and'doc'insetters:0106continue0107ifvarind:0108ifisinstance(d[var],(types.MethodType,types.FunctionType)):0109warnings.warn(0110"I tried to set the property %r, but it was "0111"already set, as a method (%r). Methods have "0112"significantly different semantics than properties, "0113"and this may be a sign of a bug in your code."0114%(var,d[var]))0115continue0116setFunc(var,0117property(setters.get('get'),setters.get('set'),0118setters.get('del'),setters.get('doc')))011901200121defunmakeProperties(obj):0122ifisinstance(obj,dict):0123defdelFunc(obj,var):0124delobj[var]0125d=obj0126else:0127delFunc=delattr0128d=obj.__dict__01290130forvar,valueinlist(d.items()):0131ifisinstance(value,property):0132forpropin[value.fget,value.fset,value.fdel]:0133ifpropandprop.__name__notind:0134delFunc(obj,var)0135break013601370138deffindDependencies(name,registry=None):0139depends=[]0140forklassinclassregistry.registry(registry).allClasses():0141iffindDependantColumns(name,klass):0142depends.append(klass)0143else:0144forjoininklass.sqlmeta.joins:0145ifisinstance(join,joins.SORelatedJoin)andjoin.otherClassName==name:0147depends.append(klass)0148break0149returndepends015001510152deffindDependantColumns(name,klass):0153depends=[]0154for_colinklass.sqlmeta.columnList:0155if_col.foreignKey==nameand_col.cascadeisnotNone:0156depends.append(_col)0157returndepends015801590160def_collectAttributes(cls,new_attrs,look_for_class):0161"""Finds all attributes in `new_attrs` that are instances of0162 `look_for_class`. The ``.name`` attribute is set for any matching objects.0163 Returns them as a list.01640165 """0166result=[]0167forattr,valueinnew_attrs.items():0168ifisinstance(value,look_for_class):0169value.name=attr0170delattr(cls,attr)0171result.append(value)0172returnresult017301740175classCreateNewSQLObject:0176"""0177 Dummy singleton to use in place of an ID, to signal we want0178 a new object.0179 """0180pass018101820183classsqlmeta(with_metaclass(declarative.DeclarativeMeta,object)):0184"""0185 This object is the object we use to keep track of all sorts of0186 information. Subclasses are made for each SQLObject subclass0187 (dynamically if necessary), and instances are created to go0188 alongside every SQLObject instance.0189 """01900191table=None0192idName=None0193idSequence=None0194# This function is used to coerce IDs into the proper format,0195# so you should replace it with str, or another function, if you0196# aren't using integer IDs0197idType=int0198style=None0199lazyUpdate=False0200defaultOrder=None0201cacheValues=True0202registry=None0203fromDatabase=False0204# Default is false, but we set it to true for the *instance*0205# when necessary: (bad clever? maybe)0206expired=False02070208# This is a mapping from column names to SOCol (or subclass)0209# instances:0210columns={}0211columnList=[]02120213# This is a mapping from column names to Col (or subclass)0214# instances; these objects don't have the logic that the SOCol0215# objects do, and are not attached to this class closely.0216columnDefinitions={}02170218# These are lists of the join and index objects:0219indexes=[]0220indexDefinitions=[]0221joins=[]0222joinDefinitions=[]02230224# These attributes shouldn't be shared with superclasses:0225_unshared_attributes=['table','columns','childName']02260227# These are internal bookkeeping attributes; the class-level0228# definition is a default for the instances, instances will0229# reset these values.02300231# When an object is being created, it has an instance0232# variable _creating, which is true. This way all the0233# setters can be captured until the object is complete,0234# and then the row is inserted into the database. Once0235# that happens, _creating is deleted from the instance,0236# and only the class variable (which is always false) is0237# left.0238_creating=False0239_obsolete=False0240# Sometimes an intance is attached to a connection, not0241# globally available. In that case, self.sqlmeta._perConnection0242# will be true. It's false by default:0243_perConnection=False02440245# Inheritance definitions:0246parentClass=None# A reference to the parent class0247childClasses={}# References to child classes, keyed by childName0248childName=None# Class name for inheritance child object creation02490250# Does the row require syncing?0251dirty=False02520253# Default encoding for UnicodeCol's0254dbEncoding=None02550256def__classinit__(cls,new_attrs):0257forattrincls._unshared_attributes:0258ifattrnotinnew_attrs:0259setattr(cls,attr,None)0260declarative.setup_attributes(cls,new_attrs)02610262def__init__(self,instance):0263self.instance=weakref.proxy(instance)02640265@classmethod0266defsend(cls,signal,*args,**kw):0267events.send(signal,cls.soClass,*args,**kw)02680269@classmethod0270defsetClass(cls,soClass):0271cls.soClass=soClass0272ifnotcls.style:0273cls.style=styles.defaultStyle0274try:0275ifcls.soClass._connectionandcls.soClass._connection.style:0276cls.style=cls.soClass._connection.style0277exceptAttributeError:0278pass0279ifcls.tableisNone:0280cls.table=cls.style.pythonClassToDBTable(cls.soClass.__name__)0281ifcls.idNameisNone:0282cls.idName=cls.style.idForTable(cls.table)02830284# plainSetters are columns that haven't been overridden by the0285# user, so we can contact the database directly to set them.0286# Note that these can't set these in the SQLObject class0287# itself, because they specific to this subclass of SQLObject,0288# and cannot be shared among classes.0289cls._plainSetters={}0290cls._plainGetters={}0291cls._plainForeignSetters={}0292cls._plainForeignGetters={}0293cls._plainJoinGetters={}0294cls._plainJoinAdders={}0295cls._plainJoinRemovers={}02960297# This is a dictionary of columnName: columnObject0298# None of these objects can be shared with superclasses0299cls.columns={}0300cls.columnList=[]0301# These, however, can be shared:0302cls.columnDefinitions=cls.columnDefinitions.copy()0303cls.indexes=[]0304cls.indexDefinitions=cls.indexDefinitions[:]0305cls.joins=[]0306cls.joinDefinitions=cls.joinDefinitions[:]03070308############################################################0309# Adding special values, like columns and indexes0310############################################################03110312########################################0313# Column handling0314########################################03150316@classmethod0317defaddColumn(cls,columnDef,changeSchema=False,connection=None):0318post_funcs=[]0319cls.send(events.AddColumnSignal,cls.soClass,connection,0320columnDef.name,columnDef,changeSchema,post_funcs)0321sqlmeta=cls0322soClass=cls.soClass0323delcls0324column=columnDef.withClass(soClass)0325name=column.name0326assertname!='id',(0327"The 'id' column is implicit, and should not be defined as "0328"a column")0329assertnamenotinsqlmeta.columns,(0330"The class %s.%s already has a column %r (%r), you cannot "0331"add the column %r"0332%(soClass.__module__,soClass.__name__,name,0333sqlmeta.columnDefinitions[name],columnDef))0334# Collect columns from the parent classes to test0335# if the column is not in a parent class0336parent_columns=[]0337forbaseinsoClass.__bases__:0338ifhasattr(base,"sqlmeta"):0339parent_columns.extend(base.sqlmeta.columns.keys())0340ifhasattr(soClass,name):0341assert(nameinparent_columns)or(name=="childName"),(0342"The class %s.%s already has a variable or method %r, "0343"you cannot add the column %r"%(0344soClass.__module__,soClass.__name__,name,name))0345sqlmeta.columnDefinitions[name]=columnDef0346sqlmeta.columns[name]=column0347# A stable-ordered version of the list...0348sqlmeta.columnList.append(column)03490350###################################################0351# Create the getter function(s). We'll start by0352# creating functions like _SO_get_columnName,0353# then if there's no function named _get_columnName0354# we'll alias that to _SO_get_columnName. This0355# allows a sort of super call, even though there's0356# no superclass that defines the database access.0357ifsqlmeta.cacheValues:0358# We create a method here, which is just a function0359# that takes "self" as the first argument.0360getter=eval(0361'lambda self: self._SO_loadValue(%s)'%0362repr(instanceName(name)))03630364else:0365# If we aren't caching values, we just call the0366# function _SO_getValue, which fetches from the0367# database.0368getter=eval('lambda self: self._SO_getValue(%s)'%repr(name))0369setattr(soClass,rawGetterName(name),getter)03700371# Here if the _get_columnName method isn't in the0372# definition, we add it with the default0373# _SO_get_columnName definition.0374ifnothasattr(soClass,getterName(name))or(name=='childName'):0375setattr(soClass,getterName(name),getter)0376sqlmeta._plainGetters[name]=103770378#################################################0379# Create the setter function(s)0380# Much like creating the getters, we will create0381# _SO_set_columnName methods, and then alias them0382# to _set_columnName if the user hasn't defined0383# those methods themself.03840385# @@: This is lame; immutable right now makes it unsettable,0386# making the table read-only0387ifnotcolumn.immutable:0388# We start by just using the _SO_setValue method0389setter=eval(0390'lambda self, val: self._SO_setValue'0391'(%s, val, self.%s, self.%s)'%(0392repr(name),0393'_SO_from_python_%s'%name,'_SO_to_python_%s'%name))0394setattr(soClass,'_SO_from_python_%s'%name,column.from_python)0395setattr(soClass,'_SO_to_python_%s'%name,column.to_python)0396setattr(soClass,rawSetterName(name),setter)0397# Then do the aliasing0398ifnothasattr(soClass,setterName(name))or(name=='childName'):0399setattr(soClass,setterName(name),setter)0400# We keep track of setters that haven't been0401# overridden, because we can combine these0402# set columns into one SQL UPDATE query.0403sqlmeta._plainSetters[name]=104040405##################################################0406# Here we check if the column is a foreign key, in0407# which case we need to make another method that0408# fetches the key and constructs the sister0409# SQLObject instance.0410ifcolumn.foreignKey:04110412# We go through the standard _SO_get_columnName deal0413# we're giving the object, not the ID of the0414# object this time:0415origName=column.origName0416ifsqlmeta.cacheValues:0417# self._SO_class_className is a reference0418# to the class in question.0419getter=eval(0420'lambda self: self._SO_foreignKey'0421'(self._SO_loadValue(%r), self._SO_class_%s, %s)'%0422(instanceName(name),column.foreignKey,0423column.refColumnandrepr(column.refColumn)))0424else:0425# Same non-caching version as above.0426getter=eval(0427'lambda self: self._SO_foreignKey'0428'(self._SO_getValue(%s), self._SO_class_%s, %s)'%0429(repr(name),column.foreignKey,0430column.refColumnandrepr(column.refColumn)))0431setattr(soClass,rawGetterName(origName),getter)04320433# And we set the _get_columnName version0434ifnothasattr(soClass,getterName(origName)):0435setattr(soClass,getterName(origName),getter)0436sqlmeta._plainForeignGetters[origName]=104370438ifnotcolumn.immutable:0439# The setter just gets the ID of the object,0440# and then sets the real column.0441setter=eval(0442'lambda self, val: '0443'setattr(self, %s, self._SO_getID(val, %s))'%0444(repr(name),column.refColumnandrepr(column.refColumn)))0445setattr(soClass,rawSetterName(origName),setter)0446ifnothasattr(soClass,setterName(origName)):0447setattr(soClass,setterName(origName),setter)0448sqlmeta._plainForeignSetters[origName]=104490450classregistry.registry(sqlmeta.registry).addClassCallback(0451column.foreignKey,0452lambdaforeign,me,attr:setattr(me,attr,foreign),0453soClass,'_SO_class_%s'%column.foreignKey)04540455ifcolumn.alternateMethodName:0456func=eval(0457'lambda cls, val, connection=None: '0458'cls._SO_fetchAlternateID(%s, %s, val, connection=connection)'0459%(repr(column.name),repr(column.dbName)))0460setattr(soClass,column.alternateMethodName,classmethod(func))04610462ifchangeSchema:0463conn=connectionorsoClass._connection0464conn.addColumn(sqlmeta.table,column)04650466ifsoClass._SO_finishedClassCreation:0467makeProperties(soClass)04680469forfuncinpost_funcs:0470func(soClass,column)04710472@classmethod0473defaddColumnsFromDatabase(sqlmeta,connection=None):0474soClass=sqlmeta.soClass0475conn=connectionorsoClass._connection0476forcolumnDefinconn.columnsFromSchema(sqlmeta.table,soClass):0477ifcolumnDef.namenotinsqlmeta.columnDefinitions:0478ifisinstance(columnDef.name,unicode_type)andPY2:0479columnDef.name=columnDef.name.encode('ascii')0480sqlmeta.addColumn(columnDef)04810482@classmethod0483defdelColumn(cls,column,changeSchema=False,connection=None):0484sqlmeta=cls0485soClass=sqlmeta.soClass0486ifisinstance(column,str):0487ifcolumninsqlmeta.columns:0488column=sqlmeta.columns[column]0489elifcolumn+'ID'insqlmeta.columns:0490column=sqlmeta.columns[column+'ID']0491else:0492raiseValueError('Unknown column '+column)0493ifisinstance(column,col.Col):0494forcinsqlmeta.columns.values():0495ifcolumnisc.columnDef:0496column=c0497break0498else:0499raiseIndexError(0500"Column with definition %r not found"%column)0501post_funcs=[]0502cls.send(events.DeleteColumnSignal,cls.soClass,connection,0503column.name,column,post_funcs)0504name=column.name0505delsqlmeta.columns[name]0506delsqlmeta.columnDefinitions[name]0507sqlmeta.columnList.remove(column)0508delattr(soClass,rawGetterName(name))0509ifnameinsqlmeta._plainGetters:0510delattr(soClass,getterName(name))0511delattr(soClass,rawSetterName(name))0512ifnameinsqlmeta._plainSetters:0513delattr(soClass,setterName(name))0514ifcolumn.foreignKey:0515delattr(soClass,0516rawGetterName(soClass.sqlmeta.style.0517instanceIDAttrToAttr(name)))0518ifnameinsqlmeta._plainForeignGetters:0519delattr(soClass,getterName(name))0520delattr(soClass,0521rawSetterName(soClass.sqlmeta.style.0522instanceIDAttrToAttr(name)))0523ifnameinsqlmeta._plainForeignSetters:0524delattr(soClass,setterName(name))0525ifcolumn.alternateMethodName:0526delattr(soClass,column.alternateMethodName)05270528ifchangeSchema:0529conn=connectionorsoClass._connection0530conn.delColumn(sqlmeta,column)05310532ifsoClass._SO_finishedClassCreation:0533unmakeProperties(soClass)0534makeProperties(soClass)05350536forfuncinpost_funcs:0537func(soClass,column)05380539########################################0540# Join handling0541########################################05420543@classmethod0544defaddJoin(cls,joinDef):0545sqlmeta=cls0546soClass=cls.soClass0547# The name of the method we'll create. If it's0548# automatically generated, it's generated by the0549# join class.0550join=joinDef.withClass(soClass)0551meth=join.joinMethodName05520553sqlmeta.joins.append(join)0554index=len(sqlmeta.joins)-10555ifjoinDefnotinsqlmeta.joinDefinitions:0556sqlmeta.joinDefinitions.append(joinDef)05570558# The function fetches the join by index, and0559# then lets the join object do the rest of the0560# work:0561func=eval(0562'lambda self: self.sqlmeta.joins[%i].performJoin(self)'%index)05630564# And we do the standard _SO_get_... _get_... deal0565setattr(soClass,rawGetterName(meth),func)0566ifnothasattr(soClass,getterName(meth)):0567setattr(soClass,getterName(meth),func)0568sqlmeta._plainJoinGetters[meth]=105690570# Some joins allow you to remove objects from the0571# join.0572ifhasattr(join,'remove'):0573# Again, we let it do the remove, and we do the0574# standard naming trick.0575func=eval(0576'lambda self, obj: self.sqlmeta.joins[%i].remove(self, obj)'%0577index)0578setattr(soClass,'_SO_remove'+join.addRemoveName,func)0579ifnothasattr(soClass,'remove'+join.addRemoveName):0580setattr(soClass,'remove'+join.addRemoveName,func)0581sqlmeta._plainJoinRemovers[meth]=105820583# Some joins allow you to add objects.0584ifhasattr(join,'add'):0585# And again...0586func=eval(0587'lambda self, obj: self.sqlmeta.joins[%i].add(self, obj)'%0588index)0589setattr(soClass,'_SO_add'+join.addRemoveName,func)0590ifnothasattr(soClass,'add'+join.addRemoveName):0591setattr(soClass,'add'+join.addRemoveName,func)0592sqlmeta._plainJoinAdders[meth]=105930594ifsoClass._SO_finishedClassCreation:0595makeProperties(soClass)05960597@classmethod0598defdelJoin(sqlmeta,joinDef):0599soClass=sqlmeta.soClass0600forjoininsqlmeta.joins:0601# previously deleted joins will be None, so it must0602# be skipped or it'll error out on the next line.0603ifjoinisNone:0604continue0605ifjoinDefisjoin.joinDef:0606break0607else:0608raiseIndexError(0609"Join %r not found in class %r (from %r)"0610%(joinDef,soClass,sqlmeta.joins))0611meth=join.joinMethodName0612sqlmeta.joinDefinitions.remove(joinDef)0613foriinrange(len(sqlmeta.joins)):0614ifsqlmeta.joins[i]isjoin:0615# Have to leave None, because we refer to joins0616# by index.0617sqlmeta.joins[i]=None0618delattr(soClass,rawGetterName(meth))0619ifmethinsqlmeta._plainJoinGetters:0620delattr(soClass,getterName(meth))0621ifhasattr(join,'remove'):0622delattr(soClass,'_SO_remove'+join.addRemovePrefix)0623ifmethinsqlmeta._plainJoinRemovers:0624delattr(soClass,'remove'+join.addRemovePrefix)0625ifhasattr(join,'add'):0626delattr(soClass,'_SO_add'+join.addRemovePrefix)0627ifmethinsqlmeta._plainJoinAdders:0628delattr(soClass,'add'+join.addRemovePrefix)06290630ifsoClass._SO_finishedClassCreation:0631unmakeProperties(soClass)0632makeProperties(soClass)06330634########################################0635# Indexes0636########################################06370638@classmethod0639defaddIndex(cls,indexDef):0640cls.indexDefinitions.append(indexDef)0641index=indexDef.withClass(cls.soClass)0642cls.indexes.append(index)0643setattr(cls.soClass,index.name,index)06440645########################################0646# Utility methods0647########################################06480649@classmethod0650defgetColumns(sqlmeta):0651returnsqlmeta.columns.copy()06520653defasDict(self):0654"""0655 Return the object as a dictionary of columns to values.0656 """0657result={}0658forkeyinself.getColumns():0659result[key]=getattr(self.instance,key)0660result['id']=self.instance.id0661returnresult06620663@classmethod0664defexpireAll(sqlmeta,connection=None):0665"""0666 Expire all instances of this class.0667 """0668soClass=sqlmeta.soClass0669connection=connectionorsoClass._connection0670cache_set=connection.cache0671cache_set.weakrefAll(soClass)0672foritemincache_set.getAll(soClass):0673item.expire()067406750676sqlhub=dbconnection.ConnectionHub()067706780679# Turning it on gives earlier warning about things0680# that will be deprecated (having this off we won't flood people0681# with warnings right away).0682warnings_level=10683exception_level=None0684# Current levels:0685# 1) Actively deprecated0686# 2) Deprecated after 10687# 3) Deprecated after 2068806890690defdeprecated(message,level=1,stacklevel=2):0691ifexception_levelisnotNoneandexception_level<=level:0692raiseNotImplementedError(message)0693ifwarnings_levelisnotNoneandwarnings_level<=level:0694warnings.warn(message,DeprecationWarning,stacklevel=stacklevel)06950696# if sys.version_info[:2] < (2, 6):0697# deprecated("Support for Python 2.5 has been declared obsolete "0698# "and will be removed in the next release of SQLObject")069907000701defsetDeprecationLevel(warning=1,exception=None):0702"""0703 Set the deprecation level for SQLObject. Low levels are more0704 actively being deprecated. Any warning at a level at or below0705 ``warning`` will give a warning. Any warning at a level at or0706 below ``exception`` will give an exception. You can use a higher0707 ``exception`` level for tests to help upgrade your code. ``None``0708 for either value means never warn or raise exceptions.07090710 The levels currently mean:07110712 1) Deprecated in current version. Will be removed in next version.07130714 2) Planned to deprecate in next version, remove later.07150716 3) Planned to deprecate sometime, remove sometime much later.07170718 As the SQLObject versions progress, the deprecation level of0719 specific features will go down, indicating the advancing nature of0720 the feature's doom. We'll try to keep features at 1 for a major0721 revision.07220723 As time continues there may be a level 0, which will give a useful0724 error message (better than ``AttributeError``) but where the0725 feature has been fully removed.0726 """0727globalwarnings_level,exception_level0728warnings_level=warning0729exception_level=exception073007310732class_sqlmeta_attr(object):07330734def__init__(self,name,deprecation_level):0735self.name=name0736self.deprecation_level=deprecation_level07370738def__get__(self,obj,type=None):0739ifself.deprecation_levelisnotNone:0740deprecated(0741'Use of this attribute should be replaced with '0742'.sqlmeta.%s'%self.name,level=self.deprecation_level)0743returngetattr((typeorobj).sqlmeta,self.name)074407450746_postponed_local=local()074707480749# SQLObject is the superclass for all SQLObject classes, of0750# course. All the deeper magic is done in MetaSQLObject, and0751# only lesser magic is done here. All the actual work is done0752# here, though -- just automatic method generation (like0753# methods and properties for each column) is done in0754# MetaSQLObject.075507560757classSQLObject(with_metaclass(declarative.DeclarativeMeta,object)):07580759_connection=sqlhub07600761sqlmeta=sqlmeta07620763# DSM: The _inheritable attribute controls wheter the class can by0764# DSM: inherited 'logically' with a foreignKey and a back reference.0765_inheritable=False# Is this class inheritable?0766_parent=None# A reference to the parent instance0767childName=None# Children name (to be able to get a subclass)07680769# The law of Demeter: the class should not call another classes by name0770SelectResultsClass=SelectResults07710772def__classinit__(cls,new_attrs):07730774# This is true if we're initializing the SQLObject class,0775# instead of a subclass:0776is_base=cls.__bases__==(object,)07770778cls._SO_setupSqlmeta(new_attrs,is_base)07790780implicitColumns=_collectAttributes(cls,new_attrs,col.Col)0781implicitJoins=_collectAttributes(cls,new_attrs,joins.Join)0782implicitIndexes=_collectAttributes(cls,new_attrs,0783index.DatabaseIndex)07840785ifnotis_base:0786cls._SO_cleanDeprecatedAttrs(new_attrs)07870788if'_connection'innew_attrs:0789connection=new_attrs['_connection']0790delcls._connection0791assert'connection'notinnew_attrs0792elif'connection'innew_attrs:0793connection=new_attrs['connection']0794delcls.connection0795else:0796connection=None07970798cls._SO_finishedClassCreation=False07990800######################################################0801# Set some attributes to their defaults, if necessary.0802# First we get the connection:0803ifnotconnectionandnotgetattr(cls,'_connection',None):0804mod=sys.modules[cls.__module__]0805# See if there's a __connection__ global in0806# the module, use it if there is.0807ifhasattr(mod,'__connection__'):0808connection=mod.__connection__08090810# Do not check hasattr(cls, '_connection') here - it is possible0811# SQLObject parent class has a connection attribute that came0812# from sqlhub, e.g.; check __dict__ only.0813ifconnectionand('_connection'notincls.__dict__):0814cls.setConnection(connection)08150816sqlmeta=cls.sqlmeta08170818# We have to check if there are columns in the inherited0819# _columns where the attribute has been set to None in this0820# class. If so, then we need to remove that column from0821# _columns.0822forkeyinsqlmeta.columnDefinitions.keys():0823if(keyinnew_attrsandnew_attrs[key]isNone):0824delsqlmeta.columnDefinitions[key]08250826forcolumninsqlmeta.columnDefinitions.values():0827sqlmeta.addColumn(column)08280829forcolumninimplicitColumns:0830sqlmeta.addColumn(column)08310832# Now the class is in an essentially OK-state, so we can0833# set up any magic attributes:0834declarative.setup_attributes(cls,new_attrs)08350836ifsqlmeta.fromDatabase:0837sqlmeta.addColumnsFromDatabase()08380839forjinimplicitJoins:0840sqlmeta.addJoin(j)0841foriinimplicitIndexes:0842sqlmeta.addIndex(i)08430844deforder_getter(o):0845returno.creationOrder0846sqlmeta.columnList.sort(key=order_getter)0847sqlmeta.indexes.sort(key=order_getter)0848sqlmeta.indexDefinitions.sort(key=order_getter)0849# Joins cannot be sorted because addJoin created accessors0850# that remember indexes.0851# sqlmeta.joins.sort(key=order_getter)0852sqlmeta.joinDefinitions.sort(key=order_getter)08530854# We don't setup the properties until we're finished with the0855# batch adding of all the columns...0856cls._notifyFinishClassCreation()0857cls._SO_finishedClassCreation=True0858makeProperties(cls)08590860# We use the magic "q" attribute for accessing lazy0861# SQL where-clause generation. See the sql module for0862# more.0863ifnotis_base:0864cls.q=sqlbuilder.SQLObjectTable(cls)0865cls.j=sqlbuilder.SQLObjectTableWithJoins(cls)08660867classregistry.registry(sqlmeta.registry).addClass(cls)08680869@classmethod0870def_SO_setupSqlmeta(cls,new_attrs,is_base):0871"""0872 This fixes up the sqlmeta attribute. It handles both the case0873 where no sqlmeta was given (in which we need to create another0874 subclass), or the sqlmeta given doesn't have the proper0875 inheritance. Lastly it calls sqlmeta.setClass, which handles0876 much of the setup.0877 """0878if('sqlmeta'notinnew_attrsandnotis_base):0879# We have to create our own subclass, usually.0880# type(className, bases_tuple, attr_dict) creates a new subclass.0881cls.sqlmeta=type('sqlmeta',(cls.sqlmeta,),{})0882ifnotissubclass(cls.sqlmeta,sqlmeta):0883# We allow no superclass and an object superclass, instead0884# of inheriting from sqlmeta; but in that case we replace0885# the class and just move over its attributes:0886assertcls.sqlmeta.__bases__in((),(object,)),(0887"If you do not inherit your sqlmeta class from "0888"sqlobject.sqlmeta, it must not inherit from any other "0889"class (your sqlmeta inherits from: %s)"0890%cls.sqlmeta.__bases__)0891forbaseincls.__bases__:0892superclass=getattr(base,'sqlmeta',None)0893ifsuperclass:0894break0895else:0896assert0,(0897"No sqlmeta class could be found in any superclass "0898"(while fixing up sqlmeta %r inheritance)"0899%cls.sqlmeta)0900values=dict(cls.sqlmeta.__dict__)0901forkeyinlist(values.keys()):0902ifkey.startswith('__')andkey.endswith('__'):0903# Magic values shouldn't be passed through:0904delvalues[key]0905cls.sqlmeta=type('sqlmeta',(superclass,),values)09060907ifnotis_base:# Do not pollute the base sqlmeta class0908cls.sqlmeta.setClass(cls)09090910@classmethod0911def_SO_cleanDeprecatedAttrs(cls,new_attrs):0912"""0913 This removes attributes on SQLObject subclasses that have0914 been deprecated; they are moved to the sqlmeta class, and0915 a deprecation warning is given.0916 """0917forattrin():0918ifattrinnew_attrs:0919deprecated("%r is deprecated and read-only; please do "0920"not use it in your classes until it is fully "0921"deprecated"%attr,level=1,stacklevel=5)09220923@classmethod0924defget(cls,id,connection=None,selectResults=None):09250926assertidisnotNone,'None is not a possible id for %s'%cls.__name__09280929id=cls.sqlmeta.idType(id)09300931ifconnectionisNone:0932cache=cls._connection.cache0933else:0934cache=connection.cache09350936# This whole sequence comes from Cache.CacheFactory's0937# behavior, where a None returned means a cache miss.0938val=cache.get(id,cls)0939ifvalisNone:0940try:0941val=cls(_SO_fetch_no_create=1)0942val._SO_validatorState=sqlbuilder.SQLObjectState(val)0943val._init(id,connection,selectResults)0944cache.put(id,cls,val)0945finally:0946cache.finishPut(cls)0947elifselectResultsandnotval.sqlmeta.dirty:0948val._SO_writeLock.acquire()0949try:0950val._SO_selectInit(selectResults)0951val.sqlmeta.expired=False0952finally:0953val._SO_writeLock.release()0954returnval09550956@classmethod0957def_notifyFinishClassCreation(cls):0958pass09590960def_init(self,id,connection=None,selectResults=None):0961assertidisnotNone0962# This function gets called only when the object is0963# created, unlike __init__ which would be called0964# anytime the object was returned from cache.0965self.id=id0966self._SO_writeLock=threading.Lock()09670968# If no connection was given, we'll inherit the class0969# instance variable which should have a _connection0970# attribute.0971if(connectionisnotNone)and(getattr(self,'_connection',None)isnotconnection):0973self._connection=connection0974# Sometimes we need to know if this instance is0975# global or tied to a particular connection.0976# This flag tells us that:0977self.sqlmeta._perConnection=True09780979ifnotselectResults:0980dbNames=[col.dbNameforcolinself.sqlmeta.columnList]0981selectResults=self._connection._SO_selectOne(self,dbNames)0982ifnotselectResults:0983raiseSQLObjectNotFound(0984"The object %s by the ID %s does not exist"%(0985self.__class__.__name__,self.id))0986self._SO_selectInit(selectResults)0987self._SO_createValues={}0988self.sqlmeta.dirty=False09890990def_SO_loadValue(self,attrName):0991try:0992returngetattr(self,attrName)0993exceptAttributeError:0994try:0995self._SO_writeLock.acquire()0996try:0997# Maybe, just in the moment since we got the lock,0998# some other thread did a _SO_loadValue and we0999# have the attribute! Let's try and find out! We1000# can keep trying this all day and still beat the1001# performance on the database call (okay, we can1002# keep trying this for a few msecs at least)...1003result=getattr(self,attrName)1004exceptAttributeError:1005pass1006else:1007returnresult1008self.sqlmeta.expired=False1009dbNames=[col.dbNameforcolinself.sqlmeta.columnList]1010selectResults=self._connection._SO_selectOne(self,dbNames)1011ifnotselectResults:1012raiseSQLObjectNotFound(1013"The object %s by the ID %s has been deleted"%(1014self.__class__.__name__,self.id))1015self._SO_selectInit(selectResults)1016result=getattr(self,attrName)1017returnresult1018finally:1019self._SO_writeLock.release()10201021defsync(self):1022ifself.sqlmeta.lazyUpdateandself._SO_createValues:1023self.syncUpdate()1024self._SO_writeLock.acquire()1025try:1026dbNames=[col.dbNameforcolinself.sqlmeta.columnList]1027selectResults=self._connection._SO_selectOne(self,dbNames)1028ifnotselectResults:1029raiseSQLObjectNotFound(1030"The object %s by the ID %s has been deleted"%(1031self.__class__.__name__,self.id))1032self._SO_selectInit(selectResults)1033self.sqlmeta.expired=False1034finally:1035self._SO_writeLock.release()10361037defsyncUpdate(self):1038ifnotself._SO_createValues:1039return1040self._SO_writeLock.acquire()1041try:1042ifself.sqlmeta.columns:1043columns=self.sqlmeta.columns1044values=[(columns[v[0]].dbName,v[1])1045forvinsorted(1046self._SO_createValues.items(),1047key=lambdac:columns[c[0]].creationOrder)]1048self._connection._SO_update(self,values)1049self.sqlmeta.dirty=False1050self._SO_createValues={}1051finally:1052self._SO_writeLock.release()10531054post_funcs=[]1055self.sqlmeta.send(events.RowUpdatedSignal,self,post_funcs)1056forfuncinpost_funcs:1057func(self)10581059defexpire(self):1060ifself.sqlmeta.expired:1061return1062self._SO_writeLock.acquire()1063try:1064ifself.sqlmeta.expired:1065return1066forcolumninself.sqlmeta.columnList:1067delattr(self,instanceName(column.name))1068self.sqlmeta.expired=True1069self._connection.cache.expire(self.id,self.__class__)1070self._SO_createValues={}1071finally:1072self._SO_writeLock.release()10731074def_SO_setValue(self,name,value,from_python,to_python):1075# This is the place where we actually update the1076# database.10771078# If we are _creating, the object doesn't yet exist1079# in the database, and we can't insert it until all1080# the parts are set. So we just keep them in a1081# dictionary until later:1082d={name:value}1083ifnotself.sqlmeta._creatingandnotgetattr(self.sqlmeta,"row_update_sig_suppress",False):1085self.sqlmeta.send(events.RowUpdateSignal,self,d)1086iflen(d)!=1ornamenotind:1087# Already called RowUpdateSignal, don't call it again1088# inside .set()1089self.sqlmeta.row_update_sig_suppress=True1090self.set(**d)1091delself.sqlmeta.row_update_sig_suppress1092value=d[name]1093iffrom_python:1094dbValue=from_python(value,self._SO_validatorState)1095else:1096dbValue=value1097ifto_python:1098value=to_python(dbValue,self._SO_validatorState)1099ifself.sqlmeta._creatingorself.sqlmeta.lazyUpdate:1100self.sqlmeta.dirty=True1101self._SO_createValues[name]=dbValue1102setattr(self,instanceName(name),value)1103return11041105self._connection._SO_update(1106self,[(self.sqlmeta.columns[name].dbName,1107dbValue)])11081109ifself.sqlmeta.cacheValues:1110setattr(self,instanceName(name),value)11111112post_funcs=[]1113self.sqlmeta.send(events.RowUpdatedSignal,self,post_funcs)1114forfuncinpost_funcs:1115func(self)11161117defset(self,_suppress_set_sig=False,**kw):1118ifnotself.sqlmeta._creatingandnotgetattr(self.sqlmeta,"row_update_sig_suppress",False)andnot_suppress_set_sig:1121self.sqlmeta.send(events.RowUpdateSignal,self,kw)1122# set() is used to update multiple values at once,1123# potentially with one SQL statement if possible.11241125# Filter out items that don't map to column names.1126# Those will be set directly on the object using1127# setattr(obj, name, value).1128defis_column(_c):1129return_cinself.sqlmeta._plainSetters11301131deff_is_column(item):1132returnis_column(item[0])11331134deff_not_column(item):1135returnnotis_column(item[0])1136items=kw.items()1137extra=dict(filter(f_not_column,items))1138kw=dict(filter(f_is_column,items))11391140# _creating is special, see _SO_setValue1141ifself.sqlmeta._creatingorself.sqlmeta.lazyUpdate:1142forname,valueinkw.items():1143from_python=getattr(self,'_SO_from_python_%s'%name,None)1144iffrom_python:1145kw[name]=dbValue=from_python(value,1146self._SO_validatorState)1147else:1148dbValue=value1149to_python=getattr(self,'_SO_to_python_%s'%name,None)1150ifto_python:1151value=to_python(dbValue,self._SO_validatorState)1152setattr(self,instanceName(name),value)11531154self._SO_createValues.update(kw)11551156forname,valueinextra.items():1157try:1158getattr(self.__class__,name)1159exceptAttributeError:1160ifnamenotinself.sqlmeta.columns:1161raiseTypeError(1162"%s.set() got an unexpected keyword argument "1163"%s"%(self.__class__.__name__,name))1164try:1165setattr(self,name,value)1166exceptAttributeErrorase:1167raiseAttributeError('%s (with attribute %r)'%(e,name))11681169self.sqlmeta.dirty=True1170return11711172self._SO_writeLock.acquire()11731174try:1175# We have to go through and see if the setters are1176# "plain", that is, if the user has changed their1177# definition in any way (put in something that1178# normalizes the value or checks for consistency,1179# for instance). If so then we have to use plain1180# old setattr() to change the value, since we can't1181# read the user's mind. We'll combine everything1182# else into a single UPDATE, if necessary.1183toUpdate={}1184forname,valueinkw.items():1185from_python=getattr(self,'_SO_from_python_%s'%name,None)1186iffrom_python:1187dbValue=from_python(value,self._SO_validatorState)1188else:1189dbValue=value1190to_python=getattr(self,'_SO_to_python_%s'%name,None)1191ifto_python:1192value=to_python(dbValue,self._SO_validatorState)1193ifself.sqlmeta.cacheValues:1194setattr(self,instanceName(name),value)1195toUpdate[name]=dbValue1196forname,valueinextra.items():1197try:1198getattr(self.__class__,name)1199exceptAttributeError:1200ifnamenotinself.sqlmeta.columns:1201raiseTypeError(1202"%s.set() got an unexpected keyword argument "1203"%s"%(self.__class__.__name__,name))1204try:1205setattr(self,name,value)1206exceptAttributeErrorase:1207raiseAttributeError('%s (with attribute %r)'%(e,name))12081209iftoUpdate:1210toUpdate=sorted(1211toUpdate.items(),1212key=lambdac:self.sqlmeta.columns[c[0]].creationOrder)1213args=[(self.sqlmeta.columns[name].dbName,value)1214forname,valueintoUpdate]1215self._connection._SO_update(self,args)1216finally:1217self._SO_writeLock.release()12181219post_funcs=[]1220self.sqlmeta.send(events.RowUpdatedSignal,self,post_funcs)1221forfuncinpost_funcs:1222func(self)12231224def_SO_selectInit(self,row):1225for_col,colValueinzip(self.sqlmeta.columnList,row):1226if_col.to_python:1227colValue=_col.to_python(colValue,self._SO_validatorState)1228setattr(self,instanceName(_col.name),colValue)12291230def_SO_getValue(self,name):1231# Retrieves a single value from the database. Simple.1232assertnotself.sqlmeta._obsolete,(1233"%s with id %s has become obsolete"1234%(self.__class__.__name__,self.id))1235# @@: do we really need this lock?1236# self._SO_writeLock.acquire()1237column=self.sqlmeta.columns[name]1238results=self._connection._SO_selectOne(self,[column.dbName])1239# self._SO_writeLock.release()1240assertresultsisnotNone,"%s with id %s is not in the database"%(1241self.__class__.__name__,self.id)1242value=results[0]1243ifcolumn.to_python:1244value=column.to_python(value,self._SO_validatorState)1245returnvalue12461247def_SO_foreignKey(self,value,joinClass,idName=None):1248ifvalueisNone:1249returnNone1250ifself.sqlmeta._perConnection:1251connection=self._connection1252else:1253connection=None1254ifidNameisNone:# Get by id1255returnjoinClass.get(value,connection=connection)1256returnjoinClass.select(1257getattr(joinClass.q,idName)==value,1258connection=connection).getOne()12591260def__init__(self,**kw):1261# If we are the outmost constructor of a hiearchy of1262# InheritableSQLObjects (or simlpy _the_ constructor of a "normal"1263# SQLObject), we create a threadlocal list that collects the1264# RowCreatedSignals, and executes them if this very constructor is left1265try:1266_postponed_local.postponed_calls1267postponed_created=False1268exceptAttributeError:1269_postponed_local.postponed_calls=[]1270postponed_created=True12711272try:1273# We shadow the sqlmeta class with an instance of sqlmeta1274# that points to us (our sqlmeta buddy object; where the1275# sqlmeta class is our class's buddy class)1276self.sqlmeta=self.__class__.sqlmeta(self)1277# The get() classmethod/constructor uses a magic keyword1278# argument when it wants an empty object, fetched from the1279# database. So we have nothing more to do in that case:1280if'_SO_fetch_no_create'inkw:1281return12821283post_funcs=[]1284self.sqlmeta.send(events.RowCreateSignal,self,kw,post_funcs)12851286# Pass the connection object along if we were given one.1287if'connection'inkw:1288connection=kw.pop('connection')1289ifgetattr(self,'_connection',None)isnotconnection:1290self._connection=connection1291self.sqlmeta._perConnection=True12921293self._SO_writeLock=threading.Lock()12941295if'id'inkw:1296id=self.sqlmeta.idType(kw['id'])1297delkw['id']1298else:1299id=None13001301self._create(id,**kw)13021303forfuncinpost_funcs:1304func(self)1305finally:1306# if we are the creator of the tl-storage, we1307# have to exectute and under all circumstances1308# remove the tl-storage1309ifpostponed_created:1310try:1311forfuncin_postponed_local.postponed_calls:1312func()1313finally:1314del_postponed_local.postponed_calls13151316def_create(self,id,**kw):13171318self.sqlmeta._creating=True1319self._SO_createValues={}1320self._SO_validatorState=sqlbuilder.SQLObjectState(self)13211322# First we do a little fix-up on the keywords we were1323# passed:1324forcolumninself.sqlmeta.columnList:13251326# Then we check if the column wasn't passed in, and1327# if not we try to get the default.1328ifcolumn.namenotinkwandcolumn.foreignNamenotinkw:1329default=column.default13301331# If we don't get it, it's an error:1332# If we specified an SQL DEFAULT, then we should use that1333ifdefaultisNoDefault:1334ifcolumn.defaultSQLisNone:1335raiseTypeError(1336"%s() did not get expected keyword argument "1337"'%s'"%(self.__class__.__name__,column.name))1338else:1339# There is defaultSQL for the column -1340# do not put the column to kw1341# so that the backend creates the value.1342continue13431344# Otherwise we put it in as though they did pass1345# that keyword:13461347kw[column.name]=default13481349self.set(**kw)13501351# Then we finalize the process:1352self._SO_finishCreate(id)13531354def_SO_finishCreate(self,id=None):1355# Here's where an INSERT is finalized.1356# These are all the column values that were supposed1357# to be set, but were delayed until now:1358setters=self._SO_createValues.items()1359setters=sorted(1360setters,key=lambdac:self.sqlmeta.columns[c[0]].creationOrder)1361# Here's their database names:1362names=[self.sqlmeta.columns[v[0]].dbNameforvinsetters]1363values=[v[1]forvinsetters]1364# Get rid of _SO_create*, we aren't creating anymore.1365# Doesn't have to be threadsafe because we're still in1366# new(), which doesn't need to be threadsafe.1367self.sqlmeta.dirty=False1368ifnotself.sqlmeta.lazyUpdate:1369delself._SO_createValues1370else:1371self._SO_createValues={}1372delself.sqlmeta._creating13731374# Do the insert -- most of the SQL in this case is left1375# up to DBConnection, since getting a new ID is1376# non-standard.1377id=self._connection.queryInsertID(self,1378id,names,values)1379cache=self._connection.cache1380cache.created(id,self.__class__,self)1381self._init(id)1382post_funcs=[]1383kw=dict([('class',self.__class__),('id',id)])13841385def_send_RowCreatedSignal():1386self.sqlmeta.send(events.RowCreatedSignal,self,kw,post_funcs)1387forfuncinpost_funcs:1388func(self)1389_postponed_local.postponed_calls.append(_send_RowCreatedSignal)13901391def_SO_getID(self,obj,refColumn=None):1392returngetID(obj,refColumn)13931394@classmethod1395def_findAlternateID(cls,name,dbName,value,connection=None):1396ifisinstance(name,str):1397name=(name,)1398value=(value,)1399iflen(name)!=len(value):1400raiseValueError(1401"'column' and 'value' tuples must be of the same size")1402new_value=[]1403forn,vinzip(name,value):1404from_python=getattr(cls,'_SO_from_python_'+n)1405iffrom_python:1406v=from_python(1407v,sqlbuilder.SQLObjectState(cls,connection=connection))1408new_value.append(v)1409condition=sqlbuilder.AND(1410*[getattr(cls.q,_n)==_vfor_n,_vinzip(name,new_value)])1411return(connectionorcls._connection)._SO_selectOneAlt(1412cls,1413[cls.sqlmeta.idName]+1414[column.dbNameforcolumnincls.sqlmeta.columnList],1415condition),None14161417@classmethod1418def_SO_fetchAlternateID(cls,name,dbName,value,connection=None,1419idxName=None):1420result,obj=cls._findAlternateID(name,dbName,value,connection)1421ifnotresult:1422ifidxNameisNone:1423raiseSQLObjectNotFound(1424"The %s by alternateID %s = %s does not exist"%(1425cls.__name__,name,repr(value)))1426else:1427names=[]1428foriinrange(len(name)):1429names.append("%s = %s"%(name[i],repr(value[i])))1430names=', '.join(names)1431raiseSQLObjectNotFound(1432"The %s by unique index %s(%s) does not exist"%(1433cls.__name__,idxName,names))1434ifobj:1435returnobj1436ifconnection:1437obj=cls.get(result[0],connection=connection,1438selectResults=result[1:])1439else:1440obj=cls.get(result[0],selectResults=result[1:])1441returnobj14421443@classmethod1444def_SO_depends(cls):1445returnfindDependencies(cls.__name__,cls.sqlmeta.registry)14461447@classmethod1448defselect(cls,clause=None,clauseTables=None,1449orderBy=NoDefault,limit=None,1450lazyColumns=False,reversed=False,1451distinct=False,connection=None,1452join=None,forUpdate=False):1453returncls.SelectResultsClass(cls,clause,1454clauseTables=clauseTables,1455orderBy=orderBy,1456limit=limit,1457lazyColumns=lazyColumns,1458reversed=reversed,1459distinct=distinct,1460connection=connection,1461join=join,forUpdate=forUpdate)14621463@classmethod1464defselectBy(cls,connection=None,**kw):1465conn=connectionorcls._connection1466returncls.SelectResultsClass(cls,1467conn._SO_columnClause(cls,kw),1468connection=conn)14691470@classmethod1471deftableExists(cls,connection=None):1472conn=connectionorcls._connection1473returnconn.tableExists(cls.sqlmeta.table)14741475@classmethod1476defdropTable(cls,ifExists=False,dropJoinTables=True,cascade=False,1477connection=None):1478conn=connectionorcls._connection1479ififExistsandnotcls.tableExists(connection=conn):1480return1481extra_sql=[]1482post_funcs=[]1483cls.sqlmeta.send(events.DropTableSignal,cls,connection,1484extra_sql,post_funcs)1485conn.dropTable(cls.sqlmeta.table,cascade)1486ifdropJoinTables:1487cls.dropJoinTables(ifExists=ifExists,connection=conn)1488forsqlinextra_sql:1489connection.query(sql)1490forfuncinpost_funcs:1491func(cls,conn)14921493@classmethod1494defcreateTable(cls,ifNotExists=False,createJoinTables=True,1495createIndexes=True,applyConstraints=True,1496connection=None):1497conn=connectionorcls._connection1498ififNotExistsandcls.tableExists(connection=conn):1499return1500extra_sql=[]1501post_funcs=[]1502cls.sqlmeta.send(events.CreateTableSignal,cls,connection,1503extra_sql,post_funcs)1504constraints=conn.createTable(cls)1505ifapplyConstraints:1506forconstraintinconstraints:1507conn.query(constraint)1508else:1509extra_sql.extend(constraints)1510ifcreateJoinTables:1511cls.createJoinTables(ifNotExists=ifNotExists,1512connection=conn)1513ifcreateIndexes:1514cls.createIndexes(ifNotExists=ifNotExists,1515connection=conn)1516forfuncinpost_funcs:1517func(cls,conn)1518returnextra_sql15191520@classmethod1521defcreateTableSQL(cls,createJoinTables=True,createIndexes=True,1522connection=None):1523conn=connectionorcls._connection1524sql,constraints=conn.createTableSQL(cls)1525ifcreateJoinTables:1526join_sql=cls.createJoinTablesSQL(connection=conn)1527ifjoin_sql:1528sql+=';\n'+join_sql1529ifcreateIndexes:1530index_sql=cls.createIndexesSQL(connection=conn)1531ifindex_sql:1532sql+=';\n'+index_sql1533returnsql,constraints15341535@classmethod1536defcreateJoinTables(cls,ifNotExists=False,connection=None):1537conn=connectionorcls._connection1538forjoinincls._getJoinsToCreate():1539if(ifNotExistsand1540conn.tableExists(join.intermediateTable)):1541continue1542conn._SO_createJoinTable(join)15431544@classmethod1545defcreateJoinTablesSQL(cls,connection=None):1546conn=connectionorcls._connection1547sql=[]1548forjoinincls._getJoinsToCreate():1549sql.append(conn._SO_createJoinTableSQL(join))1550return';\n'.join(sql)15511552@classmethod1553defcreateIndexes(cls,ifNotExists=False,connection=None):1554conn=connectionorcls._connection1555for_indexincls.sqlmeta.indexes:1556ifnot_index:1557continue1558conn._SO_createIndex(cls,_index)15591560@classmethod1561defcreateIndexesSQL(cls,connection=None):1562conn=connectionorcls._connection1563sql=[]1564for_indexincls.sqlmeta.indexes:1565ifnot_index:1566continue1567sql.append(conn.createIndexSQL(cls,_index))1568return';\n'.join(sql)15691570@classmethod1571def_getJoinsToCreate(cls):1572joins=[]1573forjoinincls.sqlmeta.joins:1574ifnotjoin:1575continue1576ifnotjoin.hasIntermediateTable()ornotgetattr(join,'createRelatedTable',True):1578continue1579ifjoin.soClass.__name__>join.otherClass.__name__:1580continue1581joins.append(join)1582returnjoins15831584@classmethod1585defdropJoinTables(cls,ifExists=False,connection=None):1586conn=connectionorcls._connection1587forjoinincls.sqlmeta.joins:1588ifnotjoin:1589continue1590ifnotjoin.hasIntermediateTable()ornotgetattr(join,'createRelatedTable',True):1592continue1593ifjoin.soClass.__name__>join.otherClass.__name__:1594continue1595ififExistsandnotconn.tableExists(join.intermediateTable):1597continue1598conn._SO_dropJoinTable(join)15991600@classmethod1601defclearTable(cls,connection=None,clearJoinTables=True):1602# 3-03 @@: Maybe this should check the cache... but it's1603# kind of crude anyway, so...1604conn=connectionorcls._connection1605conn.clearTable(cls.sqlmeta.table)1606ifclearJoinTables:1607forjoinincls._getJoinsToCreate():1608conn.clearTable(join.intermediateTable)16091610defdestroySelf(self):1611post_funcs=[]1612self.sqlmeta.send(events.RowDestroySignal,self,post_funcs)1613# Kills this object. Kills it dead!16141615klass=self.__class__16161617# Free related joins on the base class1618forjoininklass.sqlmeta.joins:1619ifisinstance(join,joins.SORelatedJoin):1620q="DELETE FROM %s WHERE %s=%d"%(join.intermediateTable,1621join.joinColumn,self.id)1622self._connection.query(q)16231624depends=[]1625depends=self._SO_depends()1626forkindepends:1627# Free related joins1628forjoinink.sqlmeta.joins:1629ifisinstance(join,joins.SORelatedJoin)andjoin.otherClassName==klass.__name__:1631q="DELETE FROM %s WHERE %s=%d"%(join.intermediateTable,1632join.otherColumn,1633self.id)1634self._connection.query(q)16351636cols=findDependantColumns(klass.__name__,k)16371638# Don't confuse the rest of the process1639iflen(cols)==0:1640continue16411642query=[]1643delete=setnull=restrict=False1644for_colincols:1645if_col.cascadeisFalse:1646# Found a restriction1647restrict=True1648query.append(getattr(k.q,_col.name)==self.id)1649if_col.cascade=='null':1650setnull=_col.name1651elif_col.cascade:1652delete=True1653assertdeleteorsetnullorrestrict,(1654"Class %s depends on %s accoriding to "1655"findDependantColumns, but this seems inaccurate"1656%(k,klass))1657query=sqlbuilder.OR(*query)1658results=k.select(query,connection=self._connection)1659ifrestrict:1660ifresults.count():1661# Restrictions only apply if there are1662# matching records on the related table1663raiseSQLObjectIntegrityError(1664"Tried to delete %s::%s but "1665"table %s has a restriction against it"%1666(klass.__name__,self.id,k.__name__))1667else:1668forrowinresults:1669ifdelete:1670row.destroySelf()1671else:1672row.set(**{setnull:None})16731674self.sqlmeta._obsolete=True1675self._connection._SO_delete(self)1676self._connection.cache.expire(self.id,self.__class__)16771678forfuncinpost_funcs:1679func(self)16801681post_funcs=[]1682self.sqlmeta.send(events.RowDestroyedSignal,self,post_funcs)1683forfuncinpost_funcs:1684func(self)16851686@classmethod1687defdelete(cls,id,connection=None):1688obj=cls.get(id,connection=connection)1689obj.destroySelf()16901691@classmethod1692defdeleteMany(cls,where=NoDefault,connection=None):1693conn=connectionorcls._connection1694conn.query(conn.sqlrepr(sqlbuilder.Delete(cls.sqlmeta.table,where)))16951696@classmethod1697defdeleteBy(cls,connection=None,**kw):1698conn=connectionorcls._connection1699conn.query(conn.sqlrepr(sqlbuilder.Delete(1700cls.sqlmeta.table,conn._SO_columnClause(cls,kw))))17011702def__repr__(self):1703ifnothasattr(self,'id'):1704# Object initialization not finished. No attributes can be read.1705return'<%s (not initialized)>'%self.__class__.__name__1706return'<%s %r %s>'%(self.__class__.__name__,1708self.id,1709' '.join(1710['%s=%s'%(name,repr(value))1711forname,valueinself._reprItems()]))17121713def__sqlrepr__(self,db):1714returnstr(self.id)17151716@classmethod1717defsqlrepr(cls,value,connection=None):1718return(connectionorcls._connection).sqlrepr(value)17191720@classmethod1721defcoerceID(cls,value):1722ifisinstance(value,cls):1723returnvalue.id1724else:1725returncls.sqlmeta.idType(value)17261727def_reprItems(self):1728items=[]1729for_colinself.sqlmeta.columnList:1730value=getattr(self,_col.name)1731r=repr(value)1732iflen(r)>20:1733value=r[:17]+"..."+r[-1]1734items.append((_col.name,value))1735returnitems17361737@classmethod1738defsetConnection(cls,value):1739ifisinstance(value,string_type):1740value=dbconnection.connectionForURI(value)1741cls._connection=value17421743deftablesUsedImmediate(self):1744return[self.__class__.q]17451746# Comparison17471748def__eq__(self,other):1749ifself.__class__isother.__class__:1750ifself.id==other.id:1751returnTrue1752returnFalse17531754def__ne__(self,other):1755returnnotself.__eq__(other)17561757def__lt__(self,other):1758returnNotImplemented17591760def__le__(self,other):1761returnNotImplemented17621763def__gt__(self,other):1764returnNotImplemented17651766def__ge__(self,other):1767returnNotImplemented17681769# (De)serialization (pickle, etc.)17701771def__getstate__(self):1772ifself.sqlmeta._perConnection:1773frompickleimportPicklingError1774raisePicklingError(1775'Cannot pickle an SQLObject instance '1776'that has a per-instance connection')1777ifself.sqlmeta.lazyUpdateandself._SO_createValues:1778self.syncUpdate()1779d=self.__dict__.copy()1780deld['sqlmeta']1781deld['_SO_validatorState']1782deld['_SO_writeLock']1783deld['_SO_createValues']1784returnd17851786def__setstate__(self,d):1787self.__init__(_SO_fetch_no_create=1)1788self._SO_validatorState=sqlbuilder.SQLObjectState(self)1789self._SO_writeLock=threading.Lock()1790self._SO_createValues={}1791self.__dict__.update(d)1792cls=self.__class__1793cache=self._connection.cache1794ifcache.tryGet(self.id,cls)isnotNone:1795raiseValueError(1796"Cannot unpickle %s row with id=%s - "1797"a different instance with the id already exists "1798"in the cache"%(cls.__name__,self.id))1799cache.created(self.id,cls,self)180018011802defsetterName(name):1803return'_set_%s'%name180418051806defrawSetterName(name):1807return'_SO_set_%s'%name180818091810defgetterName(name):1811return'_get_%s'%name181218131814defrawGetterName(name):1815return'_SO_get_%s'%name181618171818definstanceName(name):1819return'_SO_val_%s'%name182018211822########################################1823# Utility functions (for external consumption)1824########################################18251826defgetID(obj,refColumn=None):1827ifisinstance(obj,SQLObject):1828returngetattr(obj,refColumnor'id')1829elifisinstance(obj,int):1830returnobj1831elifisinstance(obj,long):1832returnint(obj)1833elifisinstance(obj,str):1834try:1835returnint(obj)1836exceptValueError:1837returnobj1838elifobjisNone:1839returnNone184018411842defgetObject(obj,klass):1843ifisinstance(obj,int):1844returnklass(obj)1845elifisinstance(obj,long):1846returnklass(int(obj))1847elifisinstance(obj,str):1848returnklass(int(obj))1849elifobjisNone:1850returnNone1851else:1852returnobj18531854__all__=[1855'NoDefault','SQLObject','SQLObjectIntegrityError','SQLObjectNotFound',1856'getID','getObject','sqlhub','sqlmeta',1857]