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"""00280029importthreading0030importweakref0031importsqlbuilder0032importdbconnection0033importcol0034importstyles0035importtypes0036importwarnings0037importjoins0038importindex0039importclassregistry0040importdeclarative0041importevents0042fromsresultsimportSelectResults0043fromutil.threadinglocalimportlocal00440045importsys0046if((sys.version_info[0]==2)and(sys.version_info[:3]<(2,6,0)))or((sys.version_info[0]==3)and(sys.version_info[:3]<(3,4,0))):0048raiseImportError("SQLObject requires Python 2.6, 2.7 or 3.4+")00490050"""0051This thread-local storage is needed for RowCreatedSignals. It gathers0052code-blocks to execute _after_ the whole hierachy of inherited SQLObjects0053is created. See SQLObject._create0054"""00550056NoDefault=sqlbuilder.NoDefault00570058classSQLObjectNotFound(LookupError):pass0059classSQLObjectIntegrityError(Exception):pass00600061defmakeProperties(obj):0062"""0063 This function takes a dictionary of methods and finds0064 methods named like:0065 * _get_attr0066 * _set_attr0067 * _del_attr0068 * _doc_attr0069 Except for _doc_attr, these should be methods. It0070 then creates properties from these methods, like0071 property(_get_attr, _set_attr, _del_attr, _doc_attr).0072 Missing methods are okay.0073 """00740075ifisinstance(obj,dict):0076defsetFunc(var,value):0077obj[var]=value0078d=obj0079else:0080defsetFunc(var,value):0081setattr(obj,var,value)0082d=obj.__dict__00830084props={}0085forvar,valueind.items():0086ifvar.startswith('_set_'):0087props.setdefault(var[5:],{})['set']=value0088elifvar.startswith('_get_'):0089props.setdefault(var[5:],{})['get']=value0090elifvar.startswith('_del_'):0091props.setdefault(var[5:],{})['del']=value0092elifvar.startswith('_doc_'):0093props.setdefault(var[5:],{})['doc']=value0094forvar,settersinprops.items():0095iflen(setters)==1and'doc'insetters:0096continue0097ifvarind:0098ifisinstance(d[var],(types.MethodType,types.FunctionType)):0099warnings.warn(0100"I tried to set the property %r, but it was "0101"already set, as a method (%r). Methods have "0102"significantly different semantics than properties, "0103"and this may be a sign of a bug in your code."0104%(var,d[var]))0105continue0106setFunc(var,0107property(setters.get('get'),setters.get('set'),0108setters.get('del'),setters.get('doc')))01090110defunmakeProperties(obj):0111ifisinstance(obj,dict):0112defdelFunc(obj,var):0113delobj[var]0114d=obj0115else:0116delFunc=delattr0117d=obj.__dict__01180119forvar,valueind.items():0120ifisinstance(value,property):0121forpropin[value.fget,value.fset,value.fdel]:0122ifpropandnotprop.__name__ind:0123delFunc(obj,var)0124break01250126deffindDependencies(name,registry=None):0127depends=[]0128forklassinclassregistry.registry(registry).allClasses():0129iffindDependantColumns(name,klass):0130depends.append(klass)0131else:0132forjoininklass.sqlmeta.joins:0133ifisinstance(join,joins.SORelatedJoin)andjoin.otherClassName==name:0134depends.append(klass)0135break0136returndepends01370138deffindDependantColumns(name,klass):0139depends=[]0140forcolinklass.sqlmeta.columnList:0141ifcol.foreignKey==nameandcol.cascadeisnotNone:0142depends.append(col)0143returndepends01440145def_collectAttributes(cls,new_attrs,look_for_class):0146"""Finds all attributes in `new_attrs` that are instances of0147 `look_for_class`. The ``.name`` attribute is set for any matching objects.0148 Returns them as a list.01490150 """0151result=[]0152forattr,valueinnew_attrs.items():0153ifisinstance(value,look_for_class):0154value.name=attr0155delattr(cls,attr)0156result.append(value)0157returnresult01580159classCreateNewSQLObject:0160"""0161 Dummy singleton to use in place of an ID, to signal we want0162 a new object.0163 """0164pass01650166classsqlmeta(object):01670168"""0169 This object is the object we use to keep track of all sorts of0170 information. Subclasses are made for each SQLObject subclass0171 (dynamically if necessary), and instances are created to go0172 alongside every SQLObject instance.0173 """01740175table=None0176idName=None0177idSequence=None0178# This function is used to coerce IDs into the proper format,0179# so you should replace it with str, or another function, if you0180# aren't using integer IDs0181idType=int0182style=None0183lazyUpdate=False0184defaultOrder=None0185cacheValues=True0186registry=None0187fromDatabase=False0188# Default is false, but we set it to true for the *instance*0189# when necessary: (bad clever? maybe)0190expired=False01910192# This is a mapping from column names to SOCol (or subclass)0193# instances:0194columns={}0195columnList=[]01960197# This is a mapping from column names to Col (or subclass)0198# instances; these objects don't have the logic that the SOCol0199# objects do, and are not attached to this class closely.0200columnDefinitions={}02010202# These are lists of the join and index objects:0203indexes=[]0204indexDefinitions=[]0205joins=[]0206joinDefinitions=[]02070208# These attributes shouldn't be shared with superclasses:0209_unshared_attributes=['table','columns','childName']02100211# These are internal bookkeeping attributes; the class-level0212# definition is a default for the instances, instances will0213# reset these values.02140215# When an object is being created, it has an instance0216# variable _creating, which is true. This way all the0217# setters can be captured until the object is complete,0218# and then the row is inserted into the database. Once0219# that happens, _creating is deleted from the instance,0220# and only the class variable (which is always false) is0221# left.0222_creating=False0223_obsolete=False0224# Sometimes an intance is attached to a connection, not0225# globally available. In that case, self.sqlmeta._perConnection0226# will be true. It's false by default:0227_perConnection=False02280229# Inheritance definitions:0230parentClass=None# A reference to the parent class0231childClasses={}# References to child classes, keyed by childName0232childName=None# Class name for inheritance child object creation02330234# Does the row require syncing?0235dirty=False02360237# Default encoding for UnicodeCol's0238dbEncoding=None02390240__metaclass__=declarative.DeclarativeMeta02410242def__classinit__(cls,new_attrs):0243forattrincls._unshared_attributes:0244ifattrnotinnew_attrs:0245setattr(cls,attr,None)0246declarative.setup_attributes(cls,new_attrs)02470248def__init__(self,instance):0249self.instance=weakref.proxy(instance)02500251@classmethod0252defsend(cls,signal,*args,**kw):0253events.send(signal,cls.soClass,*args,**kw)02540255@classmethod0256defsetClass(cls,soClass):0257cls.soClass=soClass0258ifnotcls.style:0259cls.style=styles.defaultStyle0260try:0261ifcls.soClass._connectionandcls.soClass._connection.style:0262cls.style=cls.soClass._connection.style0263exceptAttributeError:0264pass0265ifcls.tableisNone:0266cls.table=cls.style.pythonClassToDBTable(cls.soClass.__name__)0267ifcls.idNameisNone:0268cls.idName=cls.style.idForTable(cls.table)02690270# plainSetters are columns that haven't been overridden by the0271# user, so we can contact the database directly to set them.0272# Note that these can't set these in the SQLObject class0273# itself, because they specific to this subclass of SQLObject,0274# and cannot be shared among classes.0275cls._plainSetters={}0276cls._plainGetters={}0277cls._plainForeignSetters={}0278cls._plainForeignGetters={}0279cls._plainJoinGetters={}0280cls._plainJoinAdders={}0281cls._plainJoinRemovers={}02820283# This is a dictionary of columnName: columnObject0284# None of these objects can be shared with superclasses0285cls.columns={}0286cls.columnList=[]0287# These, however, can be shared:0288cls.columnDefinitions=cls.columnDefinitions.copy()0289cls.indexes=[]0290cls.indexDefinitions=cls.indexDefinitions[:]0291cls.joins=[]0292cls.joinDefinitions=cls.joinDefinitions[:]02930294############################################################0295## Adding special values, like columns and indexes0296############################################################02970298########################################0299## Column handling0300########################################03010302@classmethod0303defaddColumn(cls,columnDef,changeSchema=False,connection=None):0304post_funcs=[]0305cls.send(events.AddColumnSignal,cls.soClass,connection,0306columnDef.name,columnDef,changeSchema,post_funcs)0307sqlmeta=cls0308soClass=cls.soClass0309delcls0310column=columnDef.withClass(soClass)0311name=column.name0312assertname!='id',(0313"The 'id' column is implicit, and should not be defined as "0314"a column")0315assertnamenotinsqlmeta.columns,(0316"The class %s.%s already has a column %r (%r), you cannot "0317"add the column %r"0318%(soClass.__module__,soClass.__name__,name,0319sqlmeta.columnDefinitions[name],columnDef))0320# Collect columns from the parent classes to test0321# if the column is not in a parent class0322parent_columns=[]0323forbaseinsoClass.__bases__:0324ifhasattr(base,"sqlmeta"):0325parent_columns.extend(base.sqlmeta.columns.keys())0326ifhasattr(soClass,name):0327assert(nameinparent_columns)or(name=="childName"),(0328"The class %s.%s already has a variable or method %r, you cannot "0329"add the column %r"0330%(soClass.__module__,soClass.__name__,name,name))0331sqlmeta.columnDefinitions[name]=columnDef0332sqlmeta.columns[name]=column0333# A stable-ordered version of the list...0334sqlmeta.columnList.append(column)03350336###################################################0337# Create the getter function(s). We'll start by0338# creating functions like _SO_get_columnName,0339# then if there's no function named _get_columnName0340# we'll alias that to _SO_get_columnName. This0341# allows a sort of super call, even though there's0342# no superclass that defines the database access.0343ifsqlmeta.cacheValues:0344# We create a method here, which is just a function0345# that takes "self" as the first argument.0346getter=eval('lambda self: self._SO_loadValue(%s)'%repr(instanceName(name)))03470348else:0349# If we aren't caching values, we just call the0350# function _SO_getValue, which fetches from the0351# database.0352getter=eval('lambda self: self._SO_getValue(%s)'%repr(name))0353setattr(soClass,rawGetterName(name),getter)03540355# Here if the _get_columnName method isn't in the0356# definition, we add it with the default0357# _SO_get_columnName definition.0358ifnothasattr(soClass,getterName(name))or(name=='childName'):0359setattr(soClass,getterName(name),getter)0360sqlmeta._plainGetters[name]=103610362#################################################0363# Create the setter function(s)0364# Much like creating the getters, we will create0365# _SO_set_columnName methods, and then alias them0366# to _set_columnName if the user hasn't defined0367# those methods themself.03680369# @@: This is lame; immutable right now makes it unsettable,0370# making the table read-only0371ifnotcolumn.immutable:0372# We start by just using the _SO_setValue method0373setter=eval('lambda self, val: self._SO_setValue(%s, val, self.%s, self.%s)'%(repr(name),'_SO_from_python_%s'%name,'_SO_to_python_%s'%name))0374setattr(soClass,'_SO_from_python_%s'%name,column.from_python)0375setattr(soClass,'_SO_to_python_%s'%name,column.to_python)0376setattr(soClass,rawSetterName(name),setter)0377# Then do the aliasing0378ifnothasattr(soClass,setterName(name))or(name=='childName'):0379setattr(soClass,setterName(name),setter)0380# We keep track of setters that haven't been0381# overridden, because we can combine these0382# set columns into one SQL UPDATE query.0383sqlmeta._plainSetters[name]=103840385##################################################0386# Here we check if the column is a foreign key, in0387# which case we need to make another method that0388# fetches the key and constructs the sister0389# SQLObject instance.0390ifcolumn.foreignKey:03910392# We go through the standard _SO_get_columnName deal0393# we're giving the object, not the ID of the0394# object this time:0395origName=column.origName0396ifsqlmeta.cacheValues:0397# self._SO_class_className is a reference0398# to the class in question.0399getter=eval('lambda self: self._SO_foreignKey(self._SO_loadValue(%r), self._SO_class_%s, %s)'%(instanceName(name),column.foreignKey,column.refColumnandrepr(column.refColumn)))0400else:0401# Same non-caching version as above.0402getter=eval('lambda self: self._SO_foreignKey(self._SO_getValue(%s), self._SO_class_%s, %s)'%(repr(name),column.foreignKey,column.refColumnandrepr(column.refColumn)))0403setattr(soClass,rawGetterName(origName),getter)04040405# And we set the _get_columnName version0406ifnothasattr(soClass,getterName(origName)):0407setattr(soClass,getterName(origName),getter)0408sqlmeta._plainForeignGetters[origName]=104090410ifnotcolumn.immutable:0411# The setter just gets the ID of the object,0412# and then sets the real column.0413setter=eval('lambda self, val: setattr(self, %s, self._SO_getID(val, %s))'%(repr(name),column.refColumnandrepr(column.refColumn)))0414setattr(soClass,rawSetterName(origName),setter)0415ifnothasattr(soClass,setterName(origName)):0416setattr(soClass,setterName(origName),setter)0417sqlmeta._plainForeignSetters[origName]=104180419classregistry.registry(sqlmeta.registry).addClassCallback(0420column.foreignKey,0421lambdaforeign,me,attr:setattr(me,attr,foreign),0422soClass,'_SO_class_%s'%column.foreignKey)04230424ifcolumn.alternateMethodName:0425func=eval('lambda cls, val, connection=None: cls._SO_fetchAlternateID(%s, %s, val, connection=connection)'%(repr(column.name),repr(column.dbName)))0426setattr(soClass,column.alternateMethodName,classmethod(func))04270428ifchangeSchema:0429conn=connectionorsoClass._connection0430conn.addColumn(sqlmeta.table,column)04310432ifsoClass._SO_finishedClassCreation:0433makeProperties(soClass)04340435forfuncinpost_funcs:0436func(soClass,column)04370438@classmethod0439defaddColumnsFromDatabase(sqlmeta,connection=None):0440soClass=sqlmeta.soClass0441conn=connectionorsoClass._connection0442forcolumnDefinconn.columnsFromSchema(sqlmeta.table,soClass):0443ifcolumnDef.namenotinsqlmeta.columnDefinitions:0444ifisinstance(columnDef.name,unicode):0445columnDef.name=columnDef.name.encode('ascii')0446sqlmeta.addColumn(columnDef)04470448@classmethod0449defdelColumn(cls,column,changeSchema=False,connection=None):0450sqlmeta=cls0451soClass=sqlmeta.soClass0452ifisinstance(column,str):0453ifcolumninsqlmeta.columns:0454column=sqlmeta.columns[column]0455elifcolumn+'ID'insqlmeta.columns:0456column=sqlmeta.columns[column+'ID']0457else:0458raiseValueError('Unknown column '+column)0459ifisinstance(column,col.Col):0460forcinsqlmeta.columns.values():0461ifcolumnisc.columnDef:0462column=c0463break0464else:0465raiseIndexError(0466"Column with definition %r not found"%column)0467post_funcs=[]0468cls.send(events.DeleteColumnSignal,cls.soClass,connection,0469column.name,column,post_funcs)0470name=column.name0471delsqlmeta.columns[name]0472delsqlmeta.columnDefinitions[name]0473sqlmeta.columnList.remove(column)0474delattr(soClass,rawGetterName(name))0475ifnameinsqlmeta._plainGetters:0476delattr(soClass,getterName(name))0477delattr(soClass,rawSetterName(name))0478ifnameinsqlmeta._plainSetters:0479delattr(soClass,setterName(name))0480ifcolumn.foreignKey:0481delattr(soClass,rawGetterName(soClass.sqlmeta.style.instanceIDAttrToAttr(name)))0482ifnameinsqlmeta._plainForeignGetters:0483delattr(soClass,getterName(name))0484delattr(soClass,rawSetterName(soClass.sqlmeta.style.instanceIDAttrToAttr(name)))0485ifnameinsqlmeta._plainForeignSetters:0486delattr(soClass,setterName(name))0487ifcolumn.alternateMethodName:0488delattr(soClass,column.alternateMethodName)04890490ifchangeSchema:0491conn=connectionorsoClass._connection0492conn.delColumn(sqlmeta,column)04930494ifsoClass._SO_finishedClassCreation:0495unmakeProperties(soClass)0496makeProperties(soClass)04970498forfuncinpost_funcs:0499func(soClass,column)05000501########################################0502## Join handling0503########################################05040505@classmethod0506defaddJoin(cls,joinDef):0507sqlmeta=cls0508soClass=cls.soClass0509# The name of the method we'll create. If it's0510# automatically generated, it's generated by the0511# join class.0512join=joinDef.withClass(soClass)0513meth=join.joinMethodName05140515sqlmeta.joins.append(join)0516index=len(sqlmeta.joins)-10517ifjoinDefnotinsqlmeta.joinDefinitions:0518sqlmeta.joinDefinitions.append(joinDef)05190520# The function fetches the join by index, and0521# then lets the join object do the rest of the0522# work:0523func=eval('lambda self: self.sqlmeta.joins[%i].performJoin(self)'%index)05240525# And we do the standard _SO_get_... _get_... deal0526setattr(soClass,rawGetterName(meth),func)0527ifnothasattr(soClass,getterName(meth)):0528setattr(soClass,getterName(meth),func)0529sqlmeta._plainJoinGetters[meth]=105300531# Some joins allow you to remove objects from the0532# join.0533ifhasattr(join,'remove'):0534# Again, we let it do the remove, and we do the0535# standard naming trick.0536func=eval('lambda self, obj: self.sqlmeta.joins[%i].remove(self, obj)'%index)0537setattr(soClass,'_SO_remove'+join.addRemoveName,func)0538ifnothasattr(soClass,'remove'+join.addRemoveName):0539setattr(soClass,'remove'+join.addRemoveName,func)0540sqlmeta._plainJoinRemovers[meth]=105410542# Some joins allow you to add objects.0543ifhasattr(join,'add'):0544# And again...0545func=eval('lambda self, obj: self.sqlmeta.joins[%i].add(self, obj)'%index)0546setattr(soClass,'_SO_add'+join.addRemoveName,func)0547ifnothasattr(soClass,'add'+join.addRemoveName):0548setattr(soClass,'add'+join.addRemoveName,func)0549sqlmeta._plainJoinAdders[meth]=105500551ifsoClass._SO_finishedClassCreation:0552makeProperties(soClass)05530554@classmethod0555defdelJoin(sqlmeta,joinDef):0556soClass=sqlmeta.soClass0557forjoininsqlmeta.joins:0558# previously deleted joins will be None, so it must0559# be skipped or it'll error out on the next line.0560ifjoinisNone:0561continue0562ifjoinDefisjoin.joinDef:0563break0564else:0565raiseIndexError(0566"Join %r not found in class %r (from %r)"0567%(joinDef,soClass,sqlmeta.joins))0568meth=join.joinMethodName0569sqlmeta.joinDefinitions.remove(joinDef)0570foriinrange(len(sqlmeta.joins)):0571ifsqlmeta.joins[i]isjoin:0572# Have to leave None, because we refer to joins0573# by index.0574sqlmeta.joins[i]=None0575delattr(soClass,rawGetterName(meth))0576ifmethinsqlmeta._plainJoinGetters:0577delattr(soClass,getterName(meth))0578ifhasattr(join,'remove'):0579delattr(soClass,'_SO_remove'+join.addRemovePrefix)0580ifmethinsqlmeta._plainJoinRemovers:0581delattr(soClass,'remove'+join.addRemovePrefix)0582ifhasattr(join,'add'):0583delattr(soClass,'_SO_add'+join.addRemovePrefix)0584ifmethinsqlmeta._plainJoinAdders:0585delattr(soClass,'add'+join.addRemovePrefix)05860587ifsoClass._SO_finishedClassCreation:0588unmakeProperties(soClass)0589makeProperties(soClass)05900591########################################0592## Indexes0593########################################05940595@classmethod0596defaddIndex(cls,indexDef):0597cls.indexDefinitions.append(indexDef)0598index=indexDef.withClass(cls.soClass)0599cls.indexes.append(index)0600setattr(cls.soClass,index.name,index)06010602########################################0603## Utility methods0604########################################06050606@classmethod0607defgetColumns(sqlmeta):0608returnsqlmeta.columns.copy()06090610defasDict(self):0611"""0612 Return the object as a dictionary of columns to values.0613 """0614result={}0615forkeyinself.getColumns():0616result[key]=getattr(self.instance,key)0617result['id']=self.instance.id0618returnresult06190620@classmethod0621defexpireAll(sqlmeta,connection=None):0622"""0623 Expire all instances of this class.0624 """0625soClass=sqlmeta.soClass0626connection=connectionorsoClass._connection0627cache_set=connection.cache0628cache_set.weakrefAll(soClass)0629foritemincache_set.getAll(soClass):0630item.expire()063106320633sqlhub=dbconnection.ConnectionHub()063406350636# Turning it on gives earlier warning about things0637# that will be deprecated (having this off we won't flood people0638# with warnings right away).0639warnings_level=10640exception_level=None0641# Current levels:0642# 1) Actively deprecated0643# 2) Deprecated after 10644# 3) Deprecated after 206450646defdeprecated(message,level=1,stacklevel=2):0647ifexception_levelisnotNoneandexception_level<=level:0648raiseNotImplementedError(message)0649ifwarnings_levelisnotNoneandwarnings_level<=level:0650warnings.warn(message,DeprecationWarning,stacklevel=stacklevel)06510652#if sys.version_info[:3] < (2, 5, 0):0653# deprecated("Support for Python 2.4 has been declared obsolete and will be removed in the next release of SQLObject")06540655defsetDeprecationLevel(warning=1,exception=None):0656"""0657 Set the deprecation level for SQLObject. Low levels are more0658 actively being deprecated. Any warning at a level at or below0659 ``warning`` will give a warning. Any warning at a level at or0660 below ``exception`` will give an exception. You can use a higher0661 ``exception`` level for tests to help upgrade your code. ``None``0662 for either value means never warn or raise exceptions.06630664 The levels currently mean:06650666 1) Deprecated in current version. Will be removed in next version.06670668 2) Planned to deprecate in next version, remove later.06690670 3) Planned to deprecate sometime, remove sometime much later.06710672 As the SQLObject versions progress, the deprecation level of0673 specific features will go down, indicating the advancing nature of0674 the feature's doom. We'll try to keep features at 1 for a major0675 revision.06760677 As time continues there may be a level 0, which will give a useful0678 error message (better than ``AttributeError``) but where the0679 feature has been fully removed.0680 """0681globalwarnings_level,exception_level0682warnings_level=warning0683exception_level=exception068406850686class_sqlmeta_attr(object):06870688def__init__(self,name,deprecation_level):0689self.name=name0690self.deprecation_level=deprecation_level06910692def__get__(self,obj,type=None):0693ifself.deprecation_levelisnotNone:0694deprecated(0695'Use of this attribute should be replaced with '0696'.sqlmeta.%s'%self.name,level=self.deprecation_level)0697returngetattr((typeorobj).sqlmeta,self.name)069806990700_postponed_local=local()07010702# SQLObject is the superclass for all SQLObject classes, of0703# course. All the deeper magic is done in MetaSQLObject, and0704# only lesser magic is done here. All the actual work is done0705# here, though -- just automatic method generation (like0706# methods and properties for each column) is done in0707# MetaSQLObject.0708classSQLObject(object):07090710__metaclass__=declarative.DeclarativeMeta07110712_connection=sqlhub07130714sqlmeta=sqlmeta07150716#DSM: The _inheritable attribute controls wheter the class can by0717#DSM: inherited 'logically' with a foreignKey and a back reference.0718_inheritable=False# Is this class inheritable?0719_parent=None# A reference to the parent instance0720childName=None# Children name (to be able to get a subclass)07210722# The law of Demeter: the class should not call another classes by name0723SelectResultsClass=SelectResults07240725def__classinit__(cls,new_attrs):07260727# This is true if we're initializing the SQLObject class,0728# instead of a subclass:0729is_base=cls.__bases__==(object,)07300731cls._SO_setupSqlmeta(new_attrs,is_base)07320733implicitColumns=_collectAttributes(cls,new_attrs,col.Col)0734implicitJoins=_collectAttributes(cls,new_attrs,joins.Join)0735implicitIndexes=_collectAttributes(cls,new_attrs,index.DatabaseIndex)07360737ifnotis_base:0738cls._SO_cleanDeprecatedAttrs(new_attrs)07390740if'_connection'innew_attrs:0741connection=new_attrs['_connection']0742delcls._connection0743assert'connection'notinnew_attrs0744elif'connection'innew_attrs:0745connection=new_attrs['connection']0746delcls.connection0747else:0748connection=None07490750cls._SO_finishedClassCreation=False07510752######################################################0753# Set some attributes to their defaults, if necessary.0754# First we get the connection:0755ifnotconnectionandnotgetattr(cls,'_connection',None):0756mod=sys.modules[cls.__module__]0757# See if there's a __connection__ global in0758# the module, use it if there is.0759ifhasattr(mod,'__connection__'):0760connection=mod.__connection__07610762# Do not check hasattr(cls, '_connection') here - it is possible0763# SQLObject parent class has a connection attribute that came0764# from sqlhub, e.g.; check __dict__ only.0765ifconnectionand('_connection'notincls.__dict__):0766cls.setConnection(connection)07670768sqlmeta=cls.sqlmeta07690770# We have to check if there are columns in the inherited0771# _columns where the attribute has been set to None in this0772# class. If so, then we need to remove that column from0773# _columns.0774forkeyinsqlmeta.columnDefinitions.keys():0775if(keyinnew_attrs0776andnew_attrs[key]isNone):0777delsqlmeta.columnDefinitions[key]07780779forcolumninsqlmeta.columnDefinitions.values():0780sqlmeta.addColumn(column)07810782forcolumninimplicitColumns:0783sqlmeta.addColumn(column)07840785# Now the class is in an essentially OK-state, so we can0786# set up any magic attributes:0787declarative.setup_attributes(cls,new_attrs)07880789ifsqlmeta.fromDatabase:0790sqlmeta.addColumnsFromDatabase()07910792forjinimplicitJoins:0793sqlmeta.addJoin(j)0794foriinimplicitIndexes:0795sqlmeta.addIndex(i)07960797order_getter=lambdao:o.creationOrder0798sqlmeta.columnList.sort(key=order_getter)0799sqlmeta.indexes.sort(key=order_getter)0800sqlmeta.indexDefinitions.sort(key=order_getter)0801# Joins cannot be sorted because addJoin created accessors0802# that remember indexes.0803#sqlmeta.joins.sort(key=order_getter)0804sqlmeta.joinDefinitions.sort(key=order_getter)08050806# We don't setup the properties until we're finished with the0807# batch adding of all the columns...0808cls._notifyFinishClassCreation()0809cls._SO_finishedClassCreation=True0810makeProperties(cls)08110812# We use the magic "q" attribute for accessing lazy0813# SQL where-clause generation. See the sql module for0814# more.0815ifnotis_base:0816cls.q=sqlbuilder.SQLObjectTable(cls)0817cls.j=sqlbuilder.SQLObjectTableWithJoins(cls)08180819classregistry.registry(sqlmeta.registry).addClass(cls)08200821@classmethod0822def_SO_setupSqlmeta(cls,new_attrs,is_base):0823"""0824 This fixes up the sqlmeta attribute. It handles both the case0825 where no sqlmeta was given (in which we need to create another0826 subclass), or the sqlmeta given doesn't have the proper0827 inheritance. Lastly it calls sqlmeta.setClass, which handles0828 much of the setup.0829 """0830if('sqlmeta'notinnew_attrs0831andnotis_base):0832# We have to create our own subclass, usually.0833# type(className, bases_tuple, attr_dict) creates a new subclass.0834cls.sqlmeta=type('sqlmeta',(cls.sqlmeta,),{})0835ifnotissubclass(cls.sqlmeta,sqlmeta):0836# We allow no superclass and an object superclass, instead0837# of inheriting from sqlmeta; but in that case we replace0838# the class and just move over its attributes:0839assertcls.sqlmeta.__bases__in((),(object,)),(0840"If you do not inherit your sqlmeta class from "0841"sqlobject.sqlmeta, it must not inherit from any other "0842"class (your sqlmeta inherits from: %s)"0843%cls.sqlmeta.__bases__)0844forbaseincls.__bases__:0845superclass=getattr(base,'sqlmeta',None)0846ifsuperclass:0847break0848else:0849assert0,(0850"No sqlmeta class could be found in any superclass "0851"(while fixing up sqlmeta %r inheritance)"0852%cls.sqlmeta)0853values=dict(cls.sqlmeta.__dict__)0854forkeyinvalues.keys():0855ifkey.startswith('__')andkey.endswith('__'):0856# Magic values shouldn't be passed through:0857delvalues[key]0858cls.sqlmeta=type('sqlmeta',(superclass,),values)08590860ifnotis_base:# Do not pollute the base sqlmeta class0861cls.sqlmeta.setClass(cls)08620863@classmethod0864def_SO_cleanDeprecatedAttrs(cls,new_attrs):0865"""0866 This removes attributes on SQLObject subclasses that have0867 been deprecated; they are moved to the sqlmeta class, and0868 a deprecation warning is given.0869 """0870forattrin():0871ifattrinnew_attrs:0872deprecated("%r is deprecated and read-only; please do "0873"not use it in your classes until it is fully "0874"deprecated"%attr,level=1,stacklevel=5)08750876@classmethod0877defget(cls,id,connection=None,selectResults=None):08780879assertidisnotNone,'None is not a possible id for %s'%cls.__name__08800881id=cls.sqlmeta.idType(id)08820883ifconnectionisNone:0884cache=cls._connection.cache0885else:0886cache=connection.cache08870888# This whole sequence comes from Cache.CacheFactory's0889# behavior, where a None returned means a cache miss.0890val=cache.get(id,cls)0891ifvalisNone:0892try:0893val=cls(_SO_fetch_no_create=1)0894val._SO_validatorState=sqlbuilder.SQLObjectState(val)0895val._init(id,connection,selectResults)0896cache.put(id,cls,val)0897finally:0898cache.finishPut(cls)0899elifselectResultsandnotval.sqlmeta.dirty:0900val._SO_writeLock.acquire()0901try:0902val._SO_selectInit(selectResults)0903val.sqlmeta.expired=False0904finally:0905val._SO_writeLock.release()0906returnval09070908@classmethod0909def_notifyFinishClassCreation(cls):0910pass09110912def_init(self,id,connection=None,selectResults=None):0913assertidisnotNone0914# This function gets called only when the object is0915# created, unlike __init__ which would be called0916# anytime the object was returned from cache.0917self.id=id0918self._SO_writeLock=threading.Lock()09190920# If no connection was given, we'll inherit the class0921# instance variable which should have a _connection0922# attribute.0923if(connectionisnotNone)and(getattr(self,'_connection',None)isnotconnection):0925self._connection=connection0926# Sometimes we need to know if this instance is0927# global or tied to a particular connection.0928# This flag tells us that:0929self.sqlmeta._perConnection=True09300931ifnotselectResults:0932dbNames=[col.dbNameforcolinself.sqlmeta.columnList]0933selectResults=self._connection._SO_selectOne(self,dbNames)0934ifnotselectResults:0935raiseSQLObjectNotFound("The object %s by the ID %s does not exist"%(self.__class__.__name__,self.id))0936self._SO_selectInit(selectResults)0937self._SO_createValues={}0938self.sqlmeta.dirty=False09390940def_SO_loadValue(self,attrName):0941try:0942returngetattr(self,attrName)0943exceptAttributeError:0944try:0945self._SO_writeLock.acquire()0946try:0947# Maybe, just in the moment since we got the lock,0948# some other thread did a _SO_loadValue and we0949# have the attribute! Let's try and find out! We0950# can keep trying this all day and still beat the0951# performance on the database call (okay, we can0952# keep trying this for a few msecs at least)...0953result=getattr(self,attrName)0954exceptAttributeError:0955pass0956else:0957returnresult0958self.sqlmeta.expired=False0959dbNames=[col.dbNameforcolinself.sqlmeta.columnList]0960selectResults=self._connection._SO_selectOne(self,dbNames)0961ifnotselectResults:0962raiseSQLObjectNotFound("The object %s by the ID %s has been deleted"%(self.__class__.__name__,self.id))0963self._SO_selectInit(selectResults)0964result=getattr(self,attrName)0965returnresult0966finally:0967self._SO_writeLock.release()09680969defsync(self):0970ifself.sqlmeta.lazyUpdateandself._SO_createValues:0971self.syncUpdate()0972self._SO_writeLock.acquire()0973try:0974dbNames=[col.dbNameforcolinself.sqlmeta.columnList]0975selectResults=self._connection._SO_selectOne(self,dbNames)0976ifnotselectResults:0977raiseSQLObjectNotFound("The object %s by the ID %s has been deleted"%(self.__class__.__name__,self.id))0978self._SO_selectInit(selectResults)0979self.sqlmeta.expired=False0980finally:0981self._SO_writeLock.release()09820983defsyncUpdate(self):0984ifnotself._SO_createValues:0985return0986self._SO_writeLock.acquire()0987try:0988ifself.sqlmeta.columns:0989columns=self.sqlmeta.columns0990values=[(columns[v[0]].dbName,v[1])0991forvinsorted(0992self._SO_createValues.items(),0993key=lambdac:columns[c[0]].creationOrder)]0994self._connection._SO_update(self,values)0995self.sqlmeta.dirty=False0996self._SO_createValues={}0997finally:0998self._SO_writeLock.release()09991000post_funcs=[]1001self.sqlmeta.send(events.RowUpdatedSignal,self,post_funcs)1002forfuncinpost_funcs:1003func(self)10041005defexpire(self):1006ifself.sqlmeta.expired:1007return1008self._SO_writeLock.acquire()1009try:1010ifself.sqlmeta.expired:1011return1012forcolumninself.sqlmeta.columnList:1013delattr(self,instanceName(column.name))1014self.sqlmeta.expired=True1015self._connection.cache.expire(self.id,self.__class__)1016self._SO_createValues={}1017finally:1018self._SO_writeLock.release()10191020def_SO_setValue(self,name,value,from_python,to_python):1021# This is the place where we actually update the1022# database.10231024# If we are _creating, the object doesn't yet exist1025# in the database, and we can't insert it until all1026# the parts are set. So we just keep them in a1027# dictionary until later:1028d={name:value}1029ifnotself.sqlmeta._creatingandnotgetattr(self.sqlmeta,"row_update_sig_suppress",False):1030self.sqlmeta.send(events.RowUpdateSignal,self,d)1031iflen(d)!=1ornamenotind:1032# Already called RowUpdateSignal, don't call it again1033# inside .set()1034self.sqlmeta.row_update_sig_suppress=True1035self.set(**d)1036delself.sqlmeta.row_update_sig_suppress1037value=d[name]1038iffrom_python:1039dbValue=from_python(value,self._SO_validatorState)1040else:1041dbValue=value1042ifto_python:1043value=to_python(dbValue,self._SO_validatorState)1044ifself.sqlmeta._creatingorself.sqlmeta.lazyUpdate:1045self.sqlmeta.dirty=True1046self._SO_createValues[name]=dbValue1047setattr(self,instanceName(name),value)1048return10491050self._connection._SO_update(1051self,[(self.sqlmeta.columns[name].dbName,1052dbValue)])10531054ifself.sqlmeta.cacheValues:1055setattr(self,instanceName(name),value)10561057post_funcs=[]1058self.sqlmeta.send(events.RowUpdatedSignal,self,post_funcs)1059forfuncinpost_funcs:1060func(self)10611062defset(self,_suppress_set_sig=False,**kw):1063ifnotself.sqlmeta._creatingandnotgetattr(self.sqlmeta,"row_update_sig_suppress",False)andnot_suppress_set_sig:1064self.sqlmeta.send(events.RowUpdateSignal,self,kw)1065# set() is used to update multiple values at once,1066# potentially with one SQL statement if possible.10671068# Filter out items that don't map to column names.1069# Those will be set directly on the object using1070# setattr(obj, name, value).1071is_column=lambda_c:_cinself.sqlmeta._plainSetters1072f_is_column=lambdaitem:is_column(item[0])1073f_not_column=lambdaitem:notis_column(item[0])1074items=kw.items()1075extra=dict(filter(f_not_column,items))1076kw=dict(filter(f_is_column,items))10771078# _creating is special, see _SO_setValue1079ifself.sqlmeta._creatingorself.sqlmeta.lazyUpdate:1080forname,valueinkw.items():1081from_python=getattr(self,'_SO_from_python_%s'%name,None)1082iffrom_python:1083kw[name]=dbValue=from_python(value,self._SO_validatorState)1084else:1085dbValue=value1086to_python=getattr(self,'_SO_to_python_%s'%name,None)1087ifto_python:1088value=to_python(dbValue,self._SO_validatorState)1089setattr(self,instanceName(name),value)10901091self._SO_createValues.update(kw)10921093forname,valueinextra.items():1094try:1095getattr(self.__class__,name)1096exceptAttributeError:1097ifnamenotinself.sqlmeta.columns:1098raiseTypeError("%s.set() got an unexpected keyword argument %s"%(self.__class__.__name__,name))1099try:1100setattr(self,name,value)1101exceptAttributeErrorase:1102raiseAttributeError('%s (with attribute %r)'%(e,name))11031104self.sqlmeta.dirty=True1105return11061107self._SO_writeLock.acquire()11081109try:1110# We have to go through and see if the setters are1111# "plain", that is, if the user has changed their1112# definition in any way (put in something that1113# normalizes the value or checks for consistency,1114# for instance). If so then we have to use plain1115# old setattr() to change the value, since we can't1116# read the user's mind. We'll combine everything1117# else into a single UPDATE, if necessary.1118toUpdate={}1119forname,valueinkw.items():1120from_python=getattr(self,'_SO_from_python_%s'%name,None)1121iffrom_python:1122dbValue=from_python(value,self._SO_validatorState)1123else:1124dbValue=value1125to_python=getattr(self,'_SO_to_python_%s'%name,None)1126ifto_python:1127value=to_python(dbValue,self._SO_validatorState)1128ifself.sqlmeta.cacheValues:1129setattr(self,instanceName(name),value)1130toUpdate[name]=dbValue1131forname,valueinextra.items():1132try:1133getattr(self.__class__,name)1134exceptAttributeError:1135ifnamenotinself.sqlmeta.columns:1136raiseTypeError("%s.set() got an unexpected keyword argument %s"%(self.__class__.__name__,name))1137try:1138setattr(self,name,value)1139exceptAttributeErrorase:1140raiseAttributeError('%s (with attribute %r)'%(e,name))11411142iftoUpdate:1143toUpdate=toUpdate.items()1144toUpdate.sort(key=lambdac:self.sqlmeta.columns[c[0]].creationOrder)1145args=[(self.sqlmeta.columns[name].dbName,value)1146forname,valueintoUpdate]1147self._connection._SO_update(self,args)1148finally:1149self._SO_writeLock.release()11501151post_funcs=[]1152self.sqlmeta.send(events.RowUpdatedSignal,self,post_funcs)1153forfuncinpost_funcs:1154func(self)11551156def_SO_selectInit(self,row):1157forcol,colValueinzip(self.sqlmeta.columnList,row):1158ifcol.to_python:1159colValue=col.to_python(colValue,self._SO_validatorState)1160setattr(self,instanceName(col.name),colValue)11611162def_SO_getValue(self,name):1163# Retrieves a single value from the database. Simple.1164assertnotself.sqlmeta._obsolete,(1165"%s with id %s has become obsolete"%(self.__class__.__name__,self.id))1167# @@: do we really need this lock?1168#self._SO_writeLock.acquire()1169column=self.sqlmeta.columns[name]1170results=self._connection._SO_selectOne(self,[column.dbName])1171#self._SO_writeLock.release()1172assertresults!=None,"%s with id %s is not in the database"%(self.__class__.__name__,self.id)1174value=results[0]1175ifcolumn.to_python:1176value=column.to_python(value,self._SO_validatorState)1177returnvalue11781179def_SO_foreignKey(self,value,joinClass,idName=None):1180ifvalueisNone:1181returnNone1182ifself.sqlmeta._perConnection:1183connection=self._connection1184else:1185connection=None1186ifidNameisNone:# Get by id1187returnjoinClass.get(value,connection=connection)1188returnjoinClass.select(1189getattr(joinClass.q,idName)==value,connection=connection).getOne()11901191def__init__(self,**kw):1192# If we are the outmost constructor of a hiearchy of1193# InheritableSQLObjects (or simlpy _the_ constructor of a "normal"1194# SQLObject), we create a threadlocal list that collects the1195# RowCreatedSignals, and executes them if this very constructor is left1196try:1197_postponed_local.postponed_calls1198postponed_created=False1199exceptAttributeError:1200_postponed_local.postponed_calls=[]1201postponed_created=True12021203try:1204# We shadow the sqlmeta class with an instance of sqlmeta1205# that points to us (our sqlmeta buddy object; where the1206# sqlmeta class is our class's buddy class)1207self.sqlmeta=self.__class__.sqlmeta(self)1208# The get() classmethod/constructor uses a magic keyword1209# argument when it wants an empty object, fetched from the1210# database. So we have nothing more to do in that case:1211if'_SO_fetch_no_create'inkw:1212return12131214post_funcs=[]1215self.sqlmeta.send(events.RowCreateSignal,self,kw,post_funcs)12161217# Pass the connection object along if we were given one.1218if'connection'inkw:1219connection=kw.pop('connection')1220ifgetattr(self,'_connection',None)isnotconnection:1221self._connection=connection1222self.sqlmeta._perConnection=True12231224self._SO_writeLock=threading.Lock()12251226if'id'inkw:1227id=self.sqlmeta.idType(kw['id'])1228delkw['id']1229else:1230id=None12311232self._create(id,**kw)12331234forfuncinpost_funcs:1235func(self)1236finally:1237# if we are the creator of the tl-storage, we1238# have to exectute and under all circumstances1239# remove the tl-storage1240ifpostponed_created:1241try:1242forfuncin_postponed_local.postponed_calls:1243func()1244finally:1245del_postponed_local.postponed_calls12461247def_create(self,id,**kw):12481249self.sqlmeta._creating=True1250self._SO_createValues={}1251self._SO_validatorState=sqlbuilder.SQLObjectState(self)12521253# First we do a little fix-up on the keywords we were1254# passed:1255forcolumninself.sqlmeta.columnList:12561257# Then we check if the column wasn't passed in, and1258# if not we try to get the default.1259ifcolumn.namenotinkwandcolumn.foreignNamenotinkw:1260default=column.default12611262# If we don't get it, it's an error:1263# If we specified an SQL DEFAULT, then we should use that1264ifdefaultisNoDefault:1265ifcolumn.defaultSQLisNone:1266raiseTypeError("%s() did not get expected keyword argument '%s'"%(self.__class__.__name__,column.name))1267else:1268# There is defaultSQL for the column - do not put1269# the column to kw so that the backend creates the value1270continue12711272# Otherwise we put it in as though they did pass1273# that keyword:12741275kw[column.name]=default12761277self.set(**kw)12781279# Then we finalize the process:1280self._SO_finishCreate(id)12811282def_SO_finishCreate(self,id=None):1283# Here's where an INSERT is finalized.1284# These are all the column values that were supposed1285# to be set, but were delayed until now:1286setters=self._SO_createValues.items()1287setters.sort(key=lambdac:self.sqlmeta.columns[c[0]].creationOrder)1288# Here's their database names:1289names=[self.sqlmeta.columns[v[0]].dbNameforvinsetters]1290values=[v[1]forvinsetters]1291# Get rid of _SO_create*, we aren't creating anymore.1292# Doesn't have to be threadsafe because we're still in1293# new(), which doesn't need to be threadsafe.1294self.sqlmeta.dirty=False1295ifnotself.sqlmeta.lazyUpdate:1296delself._SO_createValues1297else:1298self._SO_createValues={}1299delself.sqlmeta._creating13001301# Do the insert -- most of the SQL in this case is left1302# up to DBConnection, since getting a new ID is1303# non-standard.1304id=self._connection.queryInsertID(self,1305id,names,values)1306cache=self._connection.cache1307cache.created(id,self.__class__,self)1308self._init(id)1309post_funcs=[]1310kw=dict([('class',self.__class__),('id',id)])1311def_send_RowCreatedSignal():1312self.sqlmeta.send(events.RowCreatedSignal,self,kw,post_funcs)1313forfuncinpost_funcs:1314func(self)1315_postponed_local.postponed_calls.append(_send_RowCreatedSignal)13161317def_SO_getID(self,obj,refColumn=None):1318returngetID(obj,refColumn)13191320@classmethod1321def_findAlternateID(cls,name,dbName,value,connection=None):1322ifisinstance(name,str):1323name=(name,)1324value=(value,)1325iflen(name)!=len(value):1326raiseValueError("'column' and 'value' tuples must be of the same size")1327new_value=[]1328forn,vinzip(name,value):1329from_python=getattr(cls,'_SO_from_python_'+n)1330iffrom_python:1331v=from_python(v,sqlbuilder.SQLObjectState(cls,connection=connection))1332new_value.append(v)1333condition=sqlbuilder.AND(*[getattr(cls.q,n)==vforn,vinzip(name,new_value)])1334return(connectionorcls._connection)._SO_selectOneAlt(1335cls,1336[cls.sqlmeta.idName]+1337[column.dbNameforcolumnincls.sqlmeta.columnList],1338condition),None13391340@classmethod1341def_SO_fetchAlternateID(cls,name,dbName,value,connection=None,idxName=None):1342result,obj=cls._findAlternateID(name,dbName,value,connection)1343ifnotresult:1344ifidxNameisNone:1345raiseSQLObjectNotFound("The %s by alternateID %s = %s does not exist"%(cls.__name__,name,repr(value)))1346else:1347names=[]1348foriinxrange(len(name)):1349names.append("%s = %s"%(name[i],repr(value[i])))1350names=', '.join(names)1351raiseSQLObjectNotFound("The %s by unique index %s(%s) does not exist"%(cls.__name__,idxName,names))1352ifobj:1353returnobj1354ifconnection:1355obj=cls.get(result[0],connection=connection,selectResults=result[1:])1356else:1357obj=cls.get(result[0],selectResults=result[1:])1358returnobj13591360@classmethod1361def_SO_depends(cls):1362returnfindDependencies(cls.__name__,cls.sqlmeta.registry)13631364@classmethod1365defselect(cls,clause=None,clauseTables=None,1366orderBy=NoDefault,limit=None,1367lazyColumns=False,reversed=False,1368distinct=False,connection=None,1369join=None,forUpdate=False):1370returncls.SelectResultsClass(cls,clause,1371clauseTables=clauseTables,1372orderBy=orderBy,1373limit=limit,1374lazyColumns=lazyColumns,1375reversed=reversed,1376distinct=distinct,1377connection=connection,1378join=join,forUpdate=forUpdate)13791380@classmethod1381defselectBy(cls,connection=None,**kw):1382conn=connectionorcls._connection1383returncls.SelectResultsClass(cls,1384conn._SO_columnClause(cls,kw),1385connection=conn)13861387@classmethod1388deftableExists(cls,connection=None):1389conn=connectionorcls._connection1390returnconn.tableExists(cls.sqlmeta.table)13911392@classmethod1393defdropTable(cls,ifExists=False,dropJoinTables=True,cascade=False,1394connection=None):1395conn=connectionorcls._connection1396ififExistsandnotcls.tableExists(connection=conn):1397return1398extra_sql=[]1399post_funcs=[]1400cls.sqlmeta.send(events.DropTableSignal,cls,connection,1401extra_sql,post_funcs)1402conn.dropTable(cls.sqlmeta.table,cascade)1403ifdropJoinTables:1404cls.dropJoinTables(ifExists=ifExists,connection=conn)1405forsqlinextra_sql:1406connection.query(sql)1407forfuncinpost_funcs:1408func(cls,conn)14091410@classmethod1411defcreateTable(cls,ifNotExists=False,createJoinTables=True,1412createIndexes=True,applyConstraints=True,1413connection=None):1414conn=connectionorcls._connection1415ififNotExistsandcls.tableExists(connection=conn):1416return1417extra_sql=[]1418post_funcs=[]1419cls.sqlmeta.send(events.CreateTableSignal,cls,connection,1420extra_sql,post_funcs)1421constraints=conn.createTable(cls)1422ifapplyConstraints:1423forconstraintinconstraints:1424conn.query(constraint)1425else:1426extra_sql.extend(constraints)1427ifcreateJoinTables:1428cls.createJoinTables(ifNotExists=ifNotExists,1429connection=conn)1430ifcreateIndexes:1431cls.createIndexes(ifNotExists=ifNotExists,1432connection=conn)1433forfuncinpost_funcs:1434func(cls,conn)1435returnextra_sql14361437@classmethod1438defcreateTableSQL(cls,createJoinTables=True,createIndexes=True,1439connection=None):1440conn=connectionorcls._connection1441sql,constraints=conn.createTableSQL(cls)1442ifcreateJoinTables:1443join_sql=cls.createJoinTablesSQL(connection=conn)1444ifjoin_sql:1445sql+=';\n'+join_sql1446ifcreateIndexes:1447index_sql=cls.createIndexesSQL(connection=conn)1448ifindex_sql:1449sql+=';\n'+index_sql1450returnsql,constraints14511452@classmethod1453defcreateJoinTables(cls,ifNotExists=False,connection=None):1454conn=connectionorcls._connection1455forjoinincls._getJoinsToCreate():1456if(ifNotExistsand1457conn.tableExists(join.intermediateTable)):1458continue1459conn._SO_createJoinTable(join)14601461@classmethod1462defcreateJoinTablesSQL(cls,connection=None):1463conn=connectionorcls._connection1464sql=[]1465forjoinincls._getJoinsToCreate():1466sql.append(conn._SO_createJoinTableSQL(join))1467return';\n'.join(sql)14681469@classmethod1470defcreateIndexes(cls,ifNotExists=False,connection=None):1471conn=connectionorcls._connection1472forindexincls.sqlmeta.indexes:1473ifnotindex:1474continue1475conn._SO_createIndex(cls,index)14761477@classmethod1478defcreateIndexesSQL(cls,connection=None):1479conn=connectionorcls._connection1480sql=[]1481forindexincls.sqlmeta.indexes:1482ifnotindex:1483continue1484sql.append(conn.createIndexSQL(cls,index))1485return';\n'.join(sql)14861487@classmethod1488def_getJoinsToCreate(cls):1489joins=[]1490forjoinincls.sqlmeta.joins:1491ifnotjoin:1492continue1493ifnotjoin.hasIntermediateTable()ornotgetattr(join,'createRelatedTable',True):1494continue1495ifjoin.soClass.__name__>join.otherClass.__name__:1496continue1497joins.append(join)1498returnjoins14991500@classmethod1501defdropJoinTables(cls,ifExists=False,connection=None):1502conn=connectionorcls._connection1503forjoinincls.sqlmeta.joins:1504ifnotjoin:1505continue1506ifnotjoin.hasIntermediateTable()ornotgetattr(join,'createRelatedTable',True):1507continue1508ifjoin.soClass.__name__>join.otherClass.__name__:1509continue1510ififExistsandnotconn.tableExists(join.intermediateTable):1512continue1513conn._SO_dropJoinTable(join)15141515@classmethod1516defclearTable(cls,connection=None,clearJoinTables=True):1517# 3-03 @@: Maybe this should check the cache... but it's1518# kind of crude anyway, so...1519conn=connectionorcls._connection1520conn.clearTable(cls.sqlmeta.table)1521ifclearJoinTables:1522forjoinincls._getJoinsToCreate():1523conn.clearTable(join.intermediateTable)15241525defdestroySelf(self):1526post_funcs=[]1527self.sqlmeta.send(events.RowDestroySignal,self,post_funcs)1528# Kills this object. Kills it dead!15291530klass=self.__class__15311532# Free related joins on the base class1533forjoininklass.sqlmeta.joins:1534ifisinstance(join,joins.SORelatedJoin):1535q="DELETE FROM %s WHERE %s=%d"%(join.intermediateTable,join.joinColumn,self.id)1536self._connection.query(q)15371538depends=[]1539depends=self._SO_depends()1540forkindepends:1541# Free related joins1542forjoinink.sqlmeta.joins:1543ifisinstance(join,joins.SORelatedJoin)andjoin.otherClassName==klass.__name__:1544q="DELETE FROM %s WHERE %s=%d"%(join.intermediateTable,join.otherColumn,self.id)1545self._connection.query(q)15461547cols=findDependantColumns(klass.__name__,k)15481549# Don't confuse the rest of the process1550iflen(cols)==0:1551continue15521553query=[]1554delete=setnull=restrict=False1555forcolincols:1556ifcol.cascade==False:1557# Found a restriction1558restrict=True1559query.append(getattr(k.q,col.name)==self.id)1560ifcol.cascade=='null':1561setnull=col.name1562elifcol.cascade:1563delete=True1564assertdeleteorsetnullorrestrict,(1565"Class %s depends on %s accoriding to "1566"findDependantColumns, but this seems inaccurate"1567%(k,klass))1568query=sqlbuilder.OR(*query)1569results=k.select(query,connection=self._connection)1570ifrestrict:1571ifresults.count():1572# Restrictions only apply if there are1573# matching records on the related table1574raiseSQLObjectIntegrityError(1575"Tried to delete %s::%s but "1576"table %s has a restriction against it"%1577(klass.__name__,self.id,k.__name__))1578else:1579forrowinresults:1580ifdelete:1581row.destroySelf()1582else:1583row.set(**{setnull:None})15841585self.sqlmeta._obsolete=True1586self._connection._SO_delete(self)1587self._connection.cache.expire(self.id,self.__class__)15881589forfuncinpost_funcs:1590func(self)15911592post_funcs=[]1593self.sqlmeta.send(events.RowDestroyedSignal,self,post_funcs)1594forfuncinpost_funcs:1595func(self)15961597@classmethod1598defdelete(cls,id,connection=None):1599obj=cls.get(id,connection=connection)1600obj.destroySelf()16011602@classmethod1603defdeleteMany(cls,where=NoDefault,connection=None):1604conn=connectionorcls._connection1605conn.query(conn.sqlrepr(sqlbuilder.Delete(cls.sqlmeta.table,where)))16061607@classmethod1608defdeleteBy(cls,connection=None,**kw):1609conn=connectionorcls._connection1610conn.query(conn.sqlrepr(sqlbuilder.Delete(cls.sqlmeta.table,1611conn._SO_columnClause(cls,kw))))16121613def__repr__(self):1614ifnothasattr(self,'id'):1615# Object initialization not finished. No attributes can be read.1616return'<%s (not initialized)>'%self.__class__.__name__1617return'<%s %r %s>'%(self.__class__.__name__,1619self.id,1620' '.join(['%s=%s'%(name,repr(value))forname,valueinself._reprItems()]))16211622def__sqlrepr__(self,db):1623returnstr(self.id)16241625@classmethod1626defsqlrepr(cls,value,connection=None):1627return(connectionorcls._connection).sqlrepr(value)16281629@classmethod1630defcoerceID(cls,value):1631ifisinstance(value,cls):1632returnvalue.id1633else:1634returncls.sqlmeta.idType(value)16351636def_reprItems(self):1637items=[]1638forcolinself.sqlmeta.columnList:1639value=getattr(self,col.name)1640r=repr(value)1641iflen(r)>20:1642value=r[:17]+"..."+r[-1]1643items.append((col.name,value))1644returnitems16451646@classmethod1647defsetConnection(cls,value):1648ifisinstance(value,basestring):1649value=dbconnection.connectionForURI(value)1650cls._connection=value16511652deftablesUsedImmediate(self):1653return[self.__class__.q]165416551656# Comparison16571658def__eq__(self,other):1659ifself.__class__isother.__class__:1660ifself.id==other.id:1661returnTrue1662returnFalse16631664def__ne__(self,other):1665returnnotself.__eq__(other)16661667def__lt__(self,other):1668returnNotImplemented16691670def__le__(self,other):1671returnNotImplemented16721673def__gt__(self,other):1674returnNotImplemented16751676def__ge__(self,other):1677returnNotImplemented167816791680# (De)serialization (pickle, etc.)16811682def__getstate__(self):1683ifself.sqlmeta._perConnection:1684frompickleimportPicklingError1685raisePicklingError('Cannot pickle an SQLObject instance that has a per-instance connection')1686ifself.sqlmeta.lazyUpdateandself._SO_createValues:1687self.syncUpdate()1688d=self.__dict__.copy()1689deld['sqlmeta']1690deld['_SO_validatorState']1691deld['_SO_writeLock']1692deld['_SO_createValues']1693returnd16941695def__setstate__(self,d):1696self.__init__(_SO_fetch_no_create=1)1697self._SO_validatorState=sqlbuilder.SQLObjectState(self)1698self._SO_writeLock=threading.Lock()1699self._SO_createValues={}1700self.__dict__.update(d)1701cls=self.__class__1702cache=self._connection.cache1703ifcache.tryGet(self.id,cls)isnotNone:1704raiseValueError(1705"Cannot unpickle %s row with id=%s - a different instance with the id already exists in the cache"%(cls.__name__,self.id))1706cache.created(self.id,cls,self)170717081709defsetterName(name):1710return'_set_%s'%name1711defrawSetterName(name):1712return'_SO_set_%s'%name1713defgetterName(name):1714return'_get_%s'%name1715defrawGetterName(name):1716return'_SO_get_%s'%name1717definstanceName(name):1718return'_SO_val_%s'%name171917201721########################################1722## Utility functions (for external consumption)1723########################################17241725defgetID(obj,refColumn=None):1726ifisinstance(obj,SQLObject):1727returngetattr(obj,refColumnor'id')1728elifisinstance(obj,int):1729returnobj1730elifisinstance(obj,long):1731returnint(obj)1732elifisinstance(obj,str):1733try:1734returnint(obj)1735exceptValueError:1736returnobj1737elifobjisNone:1738returnNone17391740defgetObject(obj,klass):1741ifisinstance(obj,int):1742returnklass(obj)1743elifisinstance(obj,long):1744returnklass(int(obj))1745elifisinstance(obj,str):1746returnklass(int(obj))1747elifobjisNone:1748returnNone1749else:1750returnobj17511752__all__=['NoDefault','SQLObject',1753'SQLObjectIntegrityError','SQLObjectNotFound',1754'getID','getObject','sqlhub','sqlmeta',1755]