rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
id = kw['id']
id = self._idType(kw['id'])
def __init__(self, **kw): # The get() classmethod/constructor uses a magic keyword # argument when it wants an empty object, fetched from the # database. So we have nothing more to do in that case: if kw.has_key('_SO_fetch_no_create'): return
setattr(self, name, value)
try: setattr(self, name, value) except AttributeError, e: raise AttributeError, '%s (with attribute %r)' % (e, name)
def __init__(self, **kw): # The get() classmethod/constructor uses a magic keyword # argument when it wants an empty object, fetched from the # database. So we have nothing more to do in that case: if kw.has_key('_SO_fetch_no_create'): return
id = self._connection.queryInsertID(self._table, self._idName,
id = self._connection.queryInsertID(self,
def _SO_finishCreate(self, id=None): # Here's where an INSERT is finalized. # These are all the column values that were supposed # to be set, but were delayed until now: setters = self._SO_createValues.items() # Here's their database names: names = [self._SO_columnDict[v[0]].dbName for v in setters] values = [v[1] for ...
return int(obj)
try: return int(obj) except ValueError: return obj
def getID(obj): if isinstance(obj, SQLObject): return obj.id elif type(obj) is type(1): return obj elif type(obj) is type(1L): return int(obj) elif type(obj) is type(""): return int(obj) elif obj is None: return None
conn = self.module.connect(self.dsn)
if self.use_dsn: conn = self.module.connect(self.dsn) else: conn = self.module.connect(**self.dsn_dict)
def makeConnection(self): try: conn = self.module.connect(self.dsn) except self.module.OperationalError, e: raise self.module.OperationalError("%s; used connection string %r" % (e, self.dsn)) if self.autoCommit: # psycopg2 does not have an autocommit method. if hasattr(conn, 'autocommit'): conn.autocommit(1) return con...
raise validators.Invalid("can not parse Decimal value '%s' in the DecimalCol '%s'" % (value, self.name), value, state)
raise validators.Invalid("can not parse Decimal value '%s' in the DecimalCol from '%s'" % (value, getattr(state, 'soObject', '(unknown)')), value, state)
def from_python(self, value, state): if value is None: return None if isinstance(value, float): value = str(value) if isinstance(value, (str, unicode)): connection = state.soObject._connection if hasattr(connection, "decimalSeparator"): value = value.replace(connection.decimalSeparator, ".") try: return Decimal(value) ...
q += "%s.%s, %s FROM %s WHERE " % \ (cls._table, cls._idName, ", ".join(["%s.%s" % (cls._table, col.dbName) for col in cls._SO_columns]), ", ".join(select.tables))
columns = ", ".join(["%s.%s" % (cls._table, col.dbName) for col in cls._SO_columns]) if columns: q += "%s.%s, %s FROM %s WHERE " % \ (cls._table, cls._idName, columns, ", ".join(select.tables)) else: q += "%s.%s FROM %s WHERE " % \ (cls._table, cls._idName, ", ".join(select.tables))
def queryForSelect(self, select): ops = select.ops cls = select.sourceClass if ops.get('distinct', False): q = 'SELECT DISTINCT ' else: q = 'SELECT ' if ops.get('lazyColumns', 0): q += "%s.%s FROM %s WHERE " % \ (cls._table, cls._idName, ", ".join(select.tables)) else: q += "%s.%s, %s FROM %s WHERE " % \ (cls._table, c...
return self._idType(value)
return cls._idType(value)
def coerceID(cls, value): if isinstance(value, cls): return value.id else: return self._idType(value)
registerConverter(type(TRUE), BoolConverter)
if type(TRUE) == InstanceType: registerConverter(BOOL, BoolConverter) else: registerConverter(type(TRUE), BoolConverter)
def BoolConverter(value, db): if db in ('postgres',): if value: return "'t'" else: return "'f'" else: if value: return '1' else: return '0'
def cmper(a, b, attr=orderBy): return cmp(getattr(b, attr), getattr(a, attr))
reverse = True
def cmper(a, b, attr=orderBy): return cmp(getattr(b, attr), getattr(a, attr))
def cmper(a, b, attr=orderBy): return cmp(getattr(a, attr), getattr(b, attr))
reverse = False def cmper(a, b, attr=orderBy, rev=reverse): a = getattr(a, attr) b = getattr(b, attr) if rev: a, b = b, a if a is None: if b is None: return 0 return -1 if b is None: return 1 return cmp(a, b)
def cmper(a, b, attr=orderBy): return cmp(getattr(a, attr), getattr(b, attr))
return tableCreateSQLs
return tableCreateSQLs or []
def createSQL(self, soClass): tableCreateSQLs = getattr(soClass.sqlmeta, 'createSQL', None) if tableCreateSQLs: assert isinstance(tableCreateSQLs,(str,list,dict,tuple)), ( '%s.sqlmeta.createSQL must be a str, list, dict or tuple.' % (soClass.__name__)) if isinstance(tableCreateSQLs, dict): tableCreateSQLs = tableCreate...
self._SO_createValues.update(kw)
def set(self, **kw): if not self.sqlmeta._creating: self.sqlmeta.send(events.RowUpdateSignal, self, kw) # set() is used to update multiple values at once, # potentially with one SQL statement if possible.
assert _cardInfo.has_key(ccType), "I can't validate that type of credit card"
assert self._cardInfo.has_key(ccType), "I can't validate that type of credit card"
def _validateReturn(self, fieldDict, state): ccType = string.lower(string.strip(fieldDict[self._ccTypeField])) number = string.strip(fieldDict[self._ccNumberField]) number = string.replace(number, ' ', '') number = string.replace(number, '-', '') try: long(number) except ValueError: return {self._ccNumberField: self.me...
if not _validateMod10(number):
if not self._validateMod10(number):
def _validateReturn(self, fieldDict, state): ccType = string.lower(string.strip(fieldDict[self._ccTypeField])) number = string.strip(fieldDict[self._ccNumberField]) number = string.replace(number, ' ', '') number = string.replace(number, '-', '') try: long(number) except ValueError: return {self._ccNumberField: self.me...
if "sspi" in kw and kw["sspi"]: self.make_conn_str = lambda keys: \ ["Provider=SQLOLEDB;Data Source=%s;Initial Catalog=%s;Integrated Security=SSPI;Persist Security Info=False" % ( keys.host, keys.db)]
if kw.get("sspi"): conn_str += "Integrated Security=SSPI;Persist Security Info=False" self.make_conn_str = lambda keys: [conn_str % (keys.host, keys.db)]
def __init__(self, db, user, password='', host='localhost', autoCommit=0, **kw): global sqlmodule if not sqlmodule: try: import adodbapi as sqlmodule self.dbconnection = sqlmodule.connect # ADO uses unicode only (AFAIK) self.usingUnicodeStrings = True # MSDE does not allow SQL server login if "sspi" in kw and kw["sspi"...
self.make_conn_str = lambda keys: \ ["Provider=SQLOLEDB;Data Source=%s;User Id=%s;Password=%s;Initial Catalog=%s" % ( keys.host, keys.user, keys.password, keys.db)] if "sspi" in kw: del kw["sspi"]
conn_str += "User Id=%s;Password=%s" self.make_conn_str = lambda keys: [conn_str % (keys.host, keys.db, keys.user, keys.password)] col.popKey(kw, "sspi") col.popKey(kw, "ncli")
def __init__(self, db, user, password='', host='localhost', autoCommit=0, **kw): global sqlmodule if not sqlmodule: try: import adodbapi as sqlmodule self.dbconnection = sqlmodule.connect # ADO uses unicode only (AFAIK) self.usingUnicodeStrings = True # MSDE does not allow SQL server login if "sspi" in kw and kw["sspi"...
declarative.setup_attributes(cls, new_attrs)
def __classinit__(cls, new_attrs):
raise TypeError, "%s.new() got an unexpected keyword argument %s" % (self.__class__.__name__, name)
raise TypeError, "%s() got an unexpected keyword argument %s" % (self.__class__.__name__, name)
def _create(self, id, **kw):
host=host or 'localhost', port=port or '', **args)
host=host or 'localhost', port=port or 0, **args)
def connectionFromURI(cls, uri): user, password, host, port, path, args = cls._parseURI(uri) return cls(db=path.strip('/'), user=user or '', passwd=password or '', host=host or 'localhost', port=port or '', **args)
delIndex = _sqlmeta_attr('delIndex', 2) getSchema = _sqlmeta_attr('getSchema', 2)
def __classinit__(cls, new_attrs):
if self.verbose > 1:
if self.options.verbose > 1:
def best_upgrade(self, current, dest, target_dbname): current_dir = os.path.join(self.base_dir(), current) if self.options.verbose > 1: print ('Looking in %s for upgraders' % self.shorten_filename(current_dir)) upgraders = [] for fn in os.listdir(current_dir): match = self.upgrade_regex.search(fn) if not match: if self...
self._conn = sqlite.connect(self.filename)
self._conn = sqlite.connect(self.filename, autocommit=autoCommit)
def __init__(self, filename, autoCommit=1, **kw): global sqlite if sqlite is None: import sqlite self.module = sqlite self.filename = filename # full path to sqlite-db-file if not autoCommit and not kw.has_key('pool'): # Pooling doesn't work with transactions... kw['pool'] = 0 # use only one connection for sqlite - su...
for column in newClass._columns:
for column in newClass._columns[:]:
def __new__(cls, className, bases, d):
if hasattr(val, 'childName'):
if 'childName' in cls.sqlmeta.columns:
def get(cls, id, connection=None, selectResults=None, childResults=None, childUpdate=False):
row = self.queryOne('SELECT gen_id(%s,1) FROM rdb$database'
c.execute('SELECT gen_id(%s,1) FROM rdb$database'
def _queryInsertID(self, conn, soInstance, id, names, values): """Firebird uses 'generators' to create new ids for a table. The users needs to create a generator named GEN_<tablename> for each table this method to work.""" table = soInstance.sqlmeta.table idName = soInstance.sqlmeta.idName sequenceName = getattr(soInst...
id = row[0]
id = c.fetchone()[0]
def _queryInsertID(self, conn, soInstance, id, names, values): """Firebird uses 'generators' to create new ids for a table. The users needs to create a generator named GEN_<tablename> for each table this method to work.""" table = soInstance.sqlmeta.table idName = soInstance.sqlmeta.idName sequenceName = getattr(soInst...
self.query(q)
c.execute(q)
def _queryInsertID(self, conn, soInstance, id, names, values): """Firebird uses 'generators' to create new ids for a table. The users needs to create a generator named GEN_<tablename> for each table this method to work.""" table = soInstance.sqlmeta.table idName = soInstance.sqlmeta.idName sequenceName = getattr(soInst...
if self.kw['use_unicode'] and colClass is col.StringCol:
if self.kw.get('use_unicode') and colClass is col.StringCol:
def columnsFromSchema(self, tableName, soClass): colData = self.queryAll("SHOW COLUMNS FROM %s" % tableName) results = [] for field, t, nullAllowed, key, default, extra in colData: if field == 'id': continue colClass, kw = self.guessClass(t) if self.kw['use_unicode'] and colClass is col.StringCol: colClass = col.Unicod...
sql = ';\n' + join_sql
sql += ';\n' + join_sql
def createTableSQL(cls, createJoinTables=True, createIndexes=True, connection=None): conn = connection or cls._connection sql, constraints = conn.createTableSQL(cls) if createJoinTables: join_sql = cls.createJoinTablesSQL(connection=conn) if join_sql: sql = ';\n' + join_sql if createIndexes: index_sql = cls.createIndex...
self.cache.clear()
if self.doCache: self.cache.clear()
def clear(self): self.cache.clear() self.expiredCache.clear()
results = self.otherClass.select(getattr(self.otherClass.q, self.soClass.sqlmeta.style.dbColumnToPythonAttr(self.joinColumn)) == inst.id)
if inst.sqlmeta._perConnection: conn = inst._connection else: conn = None results = self.otherClass.select(getattr(self.otherClass.q, self.soClass.sqlmeta.style.dbColumnToPythonAttr(self.joinColumn)) == inst.id, connection=conn)
def performJoin(self, inst): results = self.otherClass.select(getattr(self.otherClass.q, self.soClass.sqlmeta.style.dbColumnToPythonAttr(self.joinColumn)) == inst.id) if self.orderBy is NoDefault: self.orderBy = self.otherClass.sqlmeta.defaultOrder return results.orderBy(self.orderBy)
)
), connection=conn
def performJoin(self, inst): options={ 'otherTable' : self.otherClass.sqlmeta.table, 'otherID' : self.otherClass.sqlmeta.idName, 'interTable' : self.intermediateTable, 'table' : self.soClass.sqlmeta.table, 'ID' : self.soClass.sqlmeta.idName, 'joinCol' : self.joinColumn, 'otherCol' : self.otherColumn, 'idValue' : inst.i...
elif t.count('varying'):
elif t.count('varying') or t.count('varchar'):
def guessClass(self, t): if t.count('int'): return col.IntCol, {} elif t.count('varying'): if '(' in t: return col.StringCol, {'length': int(t[t.index('(')+1:-1])} else: # varchar without length in Postgres means any length return col.StringCol, {} elif t.startswith('character('): return col.StringCol, {'length': int(t...
return datetime.datetime(*stime[:7])
return datetime.datetime(*stime[:6])
def to_python(self, value, state): if value is None: return None if isinstance(value, (datetime.datetime, datetime.date, datetime.time, sqlbuilder.SQLExpression)): return value if mxdatetime_available: if isinstance(value, DateTimeType): # convert mxDateTime instance to datetime if (self.format.find("%H") >= 0) or (sel...
options={ 'otherTable' : self.otherClass.sqlmeta.table, 'otherID' : self.otherClass.sqlmeta.idName, 'interTable' : self.intermediateTable, 'table' : self.soClass.sqlmeta.table, 'ID' : self.soClass.sqlmeta.idName, 'joinCol' : self.joinColumn, 'otherCol' : self.otherColumn, 'idValue' : inst.id, } clause = '''\ %(otherTab...
results = self.otherClass.select(sqlbuilder.AND( OtherTableToJoin( self.otherClass.sqlmeta.table, self.otherClass.sqlmeta.idName, self.intermediateTable, self.otherColumn
def performJoin(self, inst): options={ 'otherTable' : self.otherClass.sqlmeta.table, 'otherID' : self.otherClass.sqlmeta.idName, 'interTable' : self.intermediateTable, 'table' : self.soClass.sqlmeta.table, 'ID' : self.soClass.sqlmeta.idName, 'joinCol' : self.joinColumn, 'otherCol' : self.otherColumn, 'idValue' : inst.i...
connection=conn ) return results
JoinToTable( self.soClass.sqlmeta.table, self.soClass.sqlmeta.idName, self.intermediateTable, self.joinColumn ), TableToId(self.soClass.sqlmeta.table, self.soClass.sqlmeta.idName, inst.id), ), clauseTables=(self.soClass.sqlmeta.table, self.otherClass.sqlmeta.table, self.intermediateTable)) if self.orderBy is NoDefault:...
def performJoin(self, inst): options={ 'otherTable' : self.otherClass.sqlmeta.table, 'otherID' : self.otherClass.sqlmeta.idName, 'interTable' : self.intermediateTable, 'table' : self.soClass.sqlmeta.table, 'ID' : self.soClass.sqlmeta.idName, 'joinCol' : self.joinColumn, 'otherCol' : self.otherColumn, 'idValue' : inst.i...
return getattr(self, select, attr)
return getattr(self.select, attr)
def __getattr__(self, attr): # @@: This passes through private variable access too... should it? # Also magic methods, like __str__ return getattr(self, select, attr)
print "OUT: %r; in: %r" % (sourceClass.sqlrepr(orderBy), sourceClass.sqlrepr(self.ops['orderBy']))
def __init__(self, sourceClass, clause, clauseTables=None, **ops): self.sourceClass = sourceClass if clause is None or isinstance(clause, str) and clause == 'all': clause = sqlbuilder.SQLTrueClause self.clause = clause tablesDict = sqlbuilder.tablesUsedDict(self.clause) tablesDict[sourceClass._table] = 1 if clauseTable...
self._joinMethodName = self.kw.pop('joinMethodName')
self._joinMethodName = popKey(self.kw, 'joinMethodName')
def __init__(self, otherClass=None, **kw): kw['otherClass'] = otherClass kw['joinDef'] = self self.kw = kw if self.kw.has_key('joinMethodName'): self._joinMethodName = self.kw.pop('joinMethodName') else: self._joinMethodName = None
self.decimalSeparator = cur.fetchone()[0][-3]
self.decimalSeparator = str(cur.fetchone()[0])[-3]
def makeConnection(self): con = self.dbconnection( *self.make_conn_str(self) ) cur = con.cursor() cur.execute('SET ANSI_NULLS ON') cur.execute("SELECT CAST('12345.21' AS DECIMAL(10, 2))") self.decimalSeparator = cur.fetchone()[0][-3] cur.close() return con
if isinstance(value, array.array):
if isinstance(value, array_type):
def StringLikeConverter(value, db): if isinstance(value, array.array): try: value = value.tounicode() except ValueError: value = value.tostring() if db in ('mysql', 'postgres'): for orig, repl in sqlStringReplace: value = value.replace(orig, repl) elif db in ('sqlite', 'firebird', 'sybase', 'maxdb'): value = value.rep...
registerConverter(array.array, StringLikeConverter)
registerConverter(array_type, StringLikeConverter)
def StringLikeConverter(value, db): if isinstance(value, array.array): try: value = value.tounicode() except ValueError: value = value.tostring() if db in ('mysql', 'postgres'): for orig, repl in sqlStringReplace: value = value.replace(orig, repl) elif db in ('sqlite', 'firebird', 'sybase', 'maxdb'): value = value.rep...
dsn_dict["password"] = password
dsn_dict["password"] = passwd
def __init__(self, dsn=None, host=None, port=None, db=None, user=None, passwd=None, usePygresql=False, **kw): global psycopg, pgdb self.usePygresql = usePygresql if usePygresql: if pgdb is None: import pgdb self.module = pgdb else: if psycopg is None: import psycopg self.module = psycopg
id = c.lastrowid
try: id = c.lastrowid except AttributeError: id = c.insert_id()
def _queryInsertID(self, conn, soInstance, id, names, values): table = soInstance.sqlmeta.table idName = soInstance.sqlmeta.idName c = conn.cursor() if id is not None: names = [idName] + names values = [id] + values q = self._insertSQL(table, names, values) if self.debug: self.printDebug(conn, q, 'QueryIns') self._exec...
_table = 'auto_test'
def setup_method(self, meth): conn = getConnection() dbName = conn.dbName creator = getattr(self, dbName + 'Create', None) if creator: conn.query(creator) def teardown_method(self, meth): conn = getConnection() dbName = conn.dbName dropper = getattr(self, dbName + 'Drop', None) if dropper: conn.query(dropper)
def test_dynamicJoin(self): if not supports('dynamicColumn'): return col = KeyCol('personID', foreignKey='Person') Phone.addColumn(col, changeSchema=True) join = MultipleJoin('Phone') Person.addJoin(join) for phone in Phone.select('all'): if phone.phone.startswith('555'): phone.person = Person.selectBy(name='tim')[0] e...
return val._childClasses[childName].get(id, selectResults=childResults)
return val._childClasses[childName].get(id, connection=connection, selectResults=childResults)
def get(cls, id, connection=None, selectResults=None, childResults=None, childUpdate=False):
inst._parent = inst._parentClass.get(id, childUpdate=True)
inst._parent = inst._parentClass.get(id, connection=connection, childUpdate=True)
def get(cls, id, connection=None, selectResults=None, childResults=None, childUpdate=False):
c.addColumn(columnDef, childUpdate=True)
c.addColumn(columnDef, connection=connection, childUpdate=True)
def addColumn(cls, columnDef, changeSchema=False, connection=None, childUpdate=False): #DSM: Try to add parent properties to the current class #DSM: Only do this once if possible at object creation and once for #DSM: each new dynamic column to refresh the current class if childUpdate or cls._parentClass: for col in cls...
return col.StringCol, {'length': int(t[t.index('(')+1:-1])}
if '(' in t: return col.StringCol, {'length': int(t[t.index('(')+1:-1])} else: return col.StringCol, {}
def guessClass(self, t): if t.count('int'): return col.IntCol, {} elif t.count('varying'): return col.StringCol, {'length': int(t[t.index('(')+1:-1])} elif t.startswith('character('): return col.StringCol, {'length': int(t[t.index('(')+1:-1]), 'varchar': False} elif t == 'text': return col.StringCol, {} elif t.startswi...
return self.makeConnection()
conn = self.makeConnection() self._connectionNumbers[id(conn)] = self._connectionCount self._connectionCount += 1 return conn
def getConnection(self): # SQLite can't share connections between threads, and so can't # pool connections. Since we are isolating threads here, we # don't have to worry about locking as much. if self._memory: return self.makeConnection() threadid = thread.get_ident() if (self._pool is not None and self._threadPool.ha...
amount = Currency()
amount = CurrencyCol()
def _set_position(self, value): self.employee.position = value
longitude = property(_get_longitude, set_longitude)
longitude = property(_get_longitude, _set_longitude)
def _set_longitude(self, value): self._so.longitude = value
return int(id)
return int(obj)
def getID(obj): try: return obj.id except AttributeError: return int(id)
opts['timeout'] = float(popKey(kw, 'timeout'))
if using_sqlite2: opts['timeout'] = float(popKey(kw, 'timeout')) else: opts['timeout'] = int(float(popKey(kw, 'timeout')) * 1000)
def __init__(self, filename, autoCommit=1, **kw): global sqlite global using_sqlite2 if sqlite is None: try: from pysqlite2 import dbapi2 as sqlite using_sqlite2 = True except ImportError: import sqlite using_sqlite2 = False self.module = sqlite self.filename = filename # full path to sqlite-db-file self._memory = fil...
for jdef in soClass._parentClass.sqlmeta.joins: join = jdef.withClass(soClass)
for join in soClass._parentClass.sqlmeta.joins:
for jdef in soClass._parentClass.sqlmeta.joins: join = jdef.withClass(soClass) jname = join.joinMethodName jarn = join.addRemoveName setattr(soClass, getterName(jname), eval('lambda self: self._parent.%s' % jname)) if hasattr(join, 'remove'): setattr(soClass, 'remove' + jarn, eval('lambda self,o: self._parent.remove%s...
self.dbconnection = sqlmodule.connect self.usingUnicodeStrings = True if kw.get("ncli"): conn_str = "Provider=SQLNCLI;" else: conn_str = "Provider=SQLOLEDB;" conn_str += "Data Source=%s;Initial Catalog=%s;" if kw.get("sspi"): conn_str += "Integrated Security=SSPI;Persist Security Info=False" self.make_conn_str = ...
except ImportError:
def __init__(self, db, user, password='', host='localhost', autoCommit=0, **kw): global sqlmodule if not sqlmodule: try: import adodbapi as sqlmodule self.dbconnection = sqlmodule.connect # ADO uses unicode only (AFAIK) self.usingUnicodeStrings = True
self.dbconnection = sqlmodule.connect sqlmodule.Binary = lambda st: str(st) self.usingUnicodeStrings = False self.make_conn_str = lambda keys: \ ["", keys.user, keys.password, keys.host, keys.db]
if sqlmodule.__name__ == 'adodbapi': import adodbapi as sqlmodule self.dbconnection = sqlmodule.connect self.usingUnicodeStrings = True if kw.get("ncli"): conn_str = "Provider=SQLNCLI;" else: conn_str = "Provider=SQLOLEDB;" conn_str += "Data Source=%s;Initial Catalog=%s;" if kw.get("sspi"): conn_str += "Integrate...
def __init__(self, db, user, password='', host='localhost', autoCommit=0, **kw): global sqlmodule if not sqlmodule: try: import adodbapi as sqlmodule self.dbconnection = sqlmodule.connect # ADO uses unicode only (AFAIK) self.usingUnicodeStrings = True
def _toPython(self, value, state=None): return self.attemptConvert(self, value, state, toPython) def _fromPython(self, value, state): return self.attemptConvert(self, value, state, fromPython)
def toPython(self, value, state=None): return self.attemptConvert(value, state, toPython) def fromPython(self, value, state): return self.attemptConvert(value, state, fromPython)
def _toPython(self, value, state=None): return self.attemptConvert(self, value, state, toPython)
user, host = host.rsplit('@', 1)
user = host[:host.rfind('@')] host = host[host.rfind('@')+1:]
def _parseURI(uri): schema, rest = uri.split(':', 1) assert rest.startswith('/'), "URIs must start with scheme:/ -- you did not include a / (in %r)" % rest if rest.startswith('/') and not rest.startswith('//'): host = None rest = rest[1:] elif rest.startswith('///'): host = None rest = rest[3:] else: rest = rest[2:] if...
results = self.otherClass.select(getattr(self.otherClass.q, pythonColumn) == inst.id)
results = self.otherClass.select( getattr(self.otherClass.q, pythonColumn) == inst.id, connection=conn )
def performJoin(self, inst): pythonColumn = self.soClass.sqlmeta.style.dbColumnToPythonAttr(self.joinColumn) results = self.otherClass.select(getattr(self.otherClass.q, pythonColumn) == inst.id) if results.count() == 0: if not self.makeDefault: return None else: kw = {pythonColumn[:-2]: inst} # skipping the ID (from fo...
results = self.otherClass.select('''\
clause = '''\
def performJoin(self, inst): options={ 'otherTable' : self.otherClass.sqlmeta.table, 'otherID' : self.otherClass.sqlmeta.idName, 'interTable' : self.intermediateTable, 'table' : self.soClass.sqlmeta.table, 'ID' : self.soClass.sqlmeta.idName, 'joinCol' : self.joinColumn, 'otherCol' : self.otherColumn, 'idValue' : inst.i...
%(table)s.%(ID)s = %(idValue)s''' % options, clauseTables=( options['table'], options['otherTable'], options['interTable'], ))
%(table)s.%(ID)s = %(idValue)s''' % options results = self.otherClass.select(sqlbuilder.SQLConstant(clause), clauseTables=( options['table'], options['otherTable'], options['interTable'], ) )
def performJoin(self, inst): options={ 'otherTable' : self.otherClass.sqlmeta.table, 'otherID' : self.otherClass.sqlmeta.idName, 'interTable' : self.intermediateTable, 'table' : self.soClass.sqlmeta.table, 'ID' : self.soClass.sqlmeta.idName, 'joinCol' : self.joinColumn, 'otherCol' : self.otherColumn, 'idValue' : inst.i...
if not autoCommit and not kw.has_key('pool'): kw['pool'] = 0
def __init__(self, dsn=None, host=None, db=None, user=None, passwd=None, autoCommit=1, usePygresql=False, **kw): global psycopg, pgdb if usePygresql: if pgdb is None: import pgdb self.pgmodule = pgdb else: if psycopg is None: import psycopg self.pgmodule = psycopg
def addColumn(cls, columnDef, changeSchema=False):
def addColumn(cls, columnDef, changeSchema=False, connection=None):
def addColumn(cls, columnDef, changeSchema=False): column = columnDef.withClass(cls) name = column.name assert name != 'id', "The 'id' column is implicit, and should not be defined as a column" cls._SO_columnDict[name] = column cls._SO_columns.append(column)
cls._connection.addColumn(cls._table, column)
conn = connection or cls._connection conn.addColumn(cls._table, column)
def addColumn(cls, columnDef, changeSchema=False): column = columnDef.withClass(cls) name = column.name assert name != 'id', "The 'id' column is implicit, and should not be defined as a column" cls._SO_columnDict[name] = column cls._SO_columns.append(column)
def addColumnsFromDatabase(cls): for columnDef in cls._connection.columnsFromSchema(cls._table, cls):
def addColumnsFromDatabase(cls, connection=None): conn = connection or cls._connection for columnDef in conn.columnsFromSchema(cls._table, cls):
def addColumnsFromDatabase(cls): for columnDef in cls._connection.columnsFromSchema(cls._table, cls): alreadyExists = False for c in cls._columns: if c.name == columnDef.name: alreadyExists = True break if not alreadyExists: cls.addColumn(columnDef)
def delColumn(cls, column, changeSchema=False):
def delColumn(cls, column, changeSchema=False, connection=None):
def delColumn(cls, column, changeSchema=False): if isinstance(column, str): column = cls._SO_columnDict[column] if isinstance(column, col.Col): for c in cls._SO_columns: if column is c.columnDef: column = c break cls._SO_columns.remove(column) cls._columns.remove(column.columnDef) name = column.name del cls._SO_columnD...
cls._connection.delColumn(cls._table, column)
conn = connection or cls._connection conn.delColumn(cls._table, column)
def delColumn(cls, column, changeSchema=False): if isinstance(column, str): column = cls._SO_columnDict[column] if isinstance(column, col.Col): for c in cls._SO_columns: if column is c.columnDef: column = c break cls._SO_columns.remove(column) cls._columns.remove(column.columnDef) name = column.name del cls._SO_columnD...
cls._connection._SO_columnClause(cls, kw), connection=connection)
conn._SO_columnClause(cls, kw), connection=conn)
def selectBy(cls, connection=None, **kw): return SelectResults(cls, cls._connection._SO_columnClause(cls, kw), connection=connection)
def dropTable(cls, ifExists=False, dropJoinTables=True, cascade=False): if ifExists and not cls._connection.tableExists(cls._table):
def dropTable(cls, ifExists=False, dropJoinTables=True, cascade=False, connection=None): conn = connection or conn._connection if ifExists and not conn.tableExists(cls._table):
def selectBy(cls, connection=None, **kw): return SelectResults(cls, cls._connection._SO_columnClause(cls, kw), connection=connection)
cls._connection.dropTable(cls._table, cascade)
conn.dropTable(cls._table, cascade)
def dropTable(cls, ifExists=False, dropJoinTables=True, cascade=False): if ifExists and not cls._connection.tableExists(cls._table): return cls._connection.dropTable(cls._table, cascade) if dropJoinTables: cls.dropJoinTables(ifExists=ifExists)
cls.dropJoinTables(ifExists=ifExists)
cls.dropJoinTables(ifExists=ifExists, connection=conn)
def dropTable(cls, ifExists=False, dropJoinTables=True, cascade=False): if ifExists and not cls._connection.tableExists(cls._table): return cls._connection.dropTable(cls._table, cascade) if dropJoinTables: cls.dropJoinTables(ifExists=ifExists)
def createTable(cls, ifNotExists=False, createJoinTables=True): if ifNotExists and cls._connection.tableExists(cls._table):
def createTable(cls, ifNotExists=False, createJoinTables=True, connection=None): conn = connection or cls._connection if ifNotExists and conn.tableExists(cls._table):
def createTable(cls, ifNotExists=False, createJoinTables=True): if ifNotExists and cls._connection.tableExists(cls._table): return cls._connection.createTable(cls) if createJoinTables: cls.createJoinTables(ifNotExists=ifNotExists)
cls._connection.createTable(cls)
conn.createTable(cls)
def createTable(cls, ifNotExists=False, createJoinTables=True): if ifNotExists and cls._connection.tableExists(cls._table): return cls._connection.createTable(cls) if createJoinTables: cls.createJoinTables(ifNotExists=ifNotExists)
cls.createJoinTables(ifNotExists=ifNotExists)
cls.createJoinTables(ifNotExists=ifNotExists, connection=conn)
def createTable(cls, ifNotExists=False, createJoinTables=True): if ifNotExists and cls._connection.tableExists(cls._table): return cls._connection.createTable(cls) if createJoinTables: cls.createJoinTables(ifNotExists=ifNotExists)
def createTableSQL(cls, createJoinTables=True): sql = cls._connection.createTableSQL(cls)
def createTableSQL(cls, createJoinTables=True, connection=None): conn = connection or cls._connection sql = conn.createTableSQL(cls)
def createTableSQL(cls, createJoinTables=True): sql = cls._connection.createTableSQL(cls) if createJoinTables: sql += '\n' + cls.createJoinTablesSQL() return sql
sql += '\n' + cls.createJoinTablesSQL()
sql += '\n' + cls.createJoinTablesSQL(connection=conn)
def createTableSQL(cls, createJoinTables=True): sql = cls._connection.createTableSQL(cls) if createJoinTables: sql += '\n' + cls.createJoinTablesSQL() return sql
def createJoinTables(cls, ifNotExists=False):
def createJoinTables(cls, ifNotExists=False, connection=None): conn = connection or cls._connection
def createJoinTables(cls, ifNotExists=False): for join in cls._getJoinsToCreate(): if ifNotExists and \ cls._connection.tableExists(join.intermediateTable): continue cls._connection._SO_createJoinTable(join)
cls._connection.tableExists(join.intermediateTable):
conn.tableExists(join.intermediateTable):
def createJoinTables(cls, ifNotExists=False): for join in cls._getJoinsToCreate(): if ifNotExists and \ cls._connection.tableExists(join.intermediateTable): continue cls._connection._SO_createJoinTable(join)
cls._connection._SO_createJoinTable(join)
conn._SO_createJoinTable(join)
def createJoinTables(cls, ifNotExists=False): for join in cls._getJoinsToCreate(): if ifNotExists and \ cls._connection.tableExists(join.intermediateTable): continue cls._connection._SO_createJoinTable(join)
def createJoinTablesSQL(cls):
def createJoinTablesSQL(cls, connection=None): conn = connection or cls._connection
def createJoinTablesSQL(cls): sql = [] for join in cls._getJoinsToCreate(): sql.append(cls._connection._SO_createJoinTableSQL(join)) return '\n'.join(sql)
sql.append(cls._connection._SO_createJoinTableSQL(join))
sql.append(conn._SO_createJoinTableSQL(join))
def createJoinTablesSQL(cls): sql = [] for join in cls._getJoinsToCreate(): sql.append(cls._connection._SO_createJoinTableSQL(join)) return '\n'.join(sql)
def dropJoinTables(cls, ifExists=False):
def dropJoinTables(cls, ifExists=False, connection=None): conn = connection or cls._connection
def dropJoinTables(cls, ifExists=False): for join in cls._SO_joinList: if not join: continue if not join.hasIntermediateTable(): continue if join.soClass.__name__ > join.otherClass.__name__: continue if ifExists and \ not cls._connection.tableExists(join.intermediateTable): continue cls._connection._SO_dropJoinTable(jo...
not cls._connection.tableExists(join.intermediateTable):
not conn.tableExists(join.intermediateTable):
def dropJoinTables(cls, ifExists=False): for join in cls._SO_joinList: if not join: continue if not join.hasIntermediateTable(): continue if join.soClass.__name__ > join.otherClass.__name__: continue if ifExists and \ not cls._connection.tableExists(join.intermediateTable): continue cls._connection._SO_dropJoinTable(jo...
cls._connection._SO_dropJoinTable(join)
conn._SO_dropJoinTable(join)
def dropJoinTables(cls, ifExists=False): for join in cls._SO_joinList: if not join: continue if not join.hasIntermediateTable(): continue if join.soClass.__name__ > join.otherClass.__name__: continue if ifExists and \ not cls._connection.tableExists(join.intermediateTable): continue cls._connection._SO_dropJoinTable(jo...
def clearTable(cls):
def clearTable(cls, connection=None):
def clearTable(cls): # 3-03 @@: Maybe this should check the cache... but it's # kind of crude anyway, so... cls._connection.clearTable(cls._table)
cls._connection.clearTable(cls._table)
conn = connection or cls._connection conn.clearTable(cls._table)
def clearTable(cls): # 3-03 @@: Maybe this should check the cache... but it's # kind of crude anyway, so... cls._connection.clearTable(cls._table)
def sqlrepr(cls, value): return cls._connection.sqlrepr(value)
def sqlrepr(cls, value, connection=None): return (connection or cls._connection).sqlrepr(value)
def sqlrepr(cls, value): return cls._connection.sqlrepr(value)
return MySQLdb.connect(host=self.host, port=self.port, db=self.db, user=self.user, passwd=self.password)
try: conn = self.module.connect(host=self.host, port=self.port, db=self.db, user=self.user, passwd=self.password) except self.module.OperationalError, e: raise self.module.OperationalError( "%s; used connection string: host=%s, port=%s, db=%s, user=%s, pwd=%s" % ( e, self.host, self.port, self.db, self.user, self.passw...
def makeConnection(self): return MySQLdb.connect(host=self.host, port=self.port, db=self.db, user=self.user, passwd=self.password)
if e.args[0] in (2006, 20013):
if e.args[0] == 2013:
def _executeRetry(self, conn, cursor, query): while 1: try: if self.need_unicode: # For MysqlDB 1.2.1 and later, we go # encoding->unicode->charset (in the mysql db) myquery = unicode(query, self.encoding) return cursor.execute(myquery) else: return cursor.execute(query) except MySQLdb.OperationalError, e: if e.args[0]...
_cacheValue = False
_cacheValues = False
def _get_phoneNumber(self): value = self._SO_get_phoneNumber() number = '(%s) %s-%s' % (value[0:3], value[3:6], value[6:10]) if len(value) > 10: number += ' ext.%s' % value[10:] return number
return '<%s %i %s>' \
return '<%s %r %s>' \
def __repr__(self): return '<%s %i %s>' \ % (self.__class__.__name__, self.id, ' '.join(['%s=%s' % (name, repr(value)) for name, value in self._reprItems()]))
else: for key, col in soClass.sqlmeta.columns.items(): if key in kw: data[col.dbName] = kw[key] elif col.foreignName in kw: obj = kw[col.foreignName] if obj is None: data[col.dbName] = None else: data[col.dbName] = obj.id
for key, col in soClass.sqlmeta.columns.items(): if key in kw: data[col.dbName] = kw[key] elif col.foreignName in kw: obj = kw[col.foreignName] if obj is None: data[col.dbName] = None else: data[col.dbName] = obj.id
def _SO_columnClause(self, soClass, kw): ops = {None: "IS"} data = {} if 'id' in kw: data[soClass.sqlmeta.idName] = kw['id'] else: for key, col in soClass.sqlmeta.columns.items(): if key in kw: data[col.dbName] = kw[key] elif col.foreignName in kw: obj = kw[col.foreignName] if obj is None: data[col.dbName] = None else:...
Called when an instance is updated through a call to ``.set()``. The arguments are ``(instance, kwargs)``. ``kwargs`` can be modified. This is run *before* the instance is updated; if you want to look at the current values, simply look at ``instance``.
Called when an instance is updated through a call to ``.set()`` (or a column attribute assignment). The arguments are ``(instance, kwargs)``. ``kwargs`` can be modified. This is run *before* the instance is updated; if you want to look at the current values, simply look at ``instance``.
def _makeSubclassConnectionsPost(new_class): for cls in new_class.__bases__: for weakReceiver, signal in subclassClones.get(cls, []): receiver = weakReceiver() if not receiver: continue listen(receiver, new_class, signal)
def __init__(self, tableName, alias=None):
def __init__(self, table, alias=None): if hasattr(table, "sqlmeta"): tableName = table.sqlmeta.table else: tableName = table table = None
def __init__(self, tableName, alias=None): Table.__init__(self, tableName) if alias is None: self._alias_lock.acquire() try: AliasTable._alias_counter += 1 alias = "%s_alias%d" % (tableName, AliasTable._alias_counter) finally: self._alias_lock.release() self.alias = alias
if hasattr(table, "sqlmeta"): table = table.sqlmeta.table
def __init__(self, table, alias=None): if hasattr(table, "sqlmeta"): table = table.sqlmeta.table self.q = AliasTable(table, alias)
return '\n'.join(sql)
return ';\n'.join(sql)
def createJoinTablesSQL(cls, connection=None): conn = connection or cls._connection sql = [] for join in cls._getJoinsToCreate(): if not getattr(join, 'createRelatedTable', True): # This join has requested not to be created continue sql.append(conn._SO_createJoinTableSQL(join)) return '\n'.join(sql)
return '\n'.join(sql)
return ';\n'.join(sql)
def createIndexesSQL(cls, connection=None): conn = connection or cls._connection sql = [] for index in cls.sqlmeta.indexes: if not index: continue sql.append(conn.createIndexSQL(cls, index)) return '\n'.join(sql)
things = self.items
things = self.items[:]
def __sqlrepr__(self, db): select = "SELECT %s" % ", ".join([sqlrepr(v, db) for v in self.items])