desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
''
def addServiceChannel(self, service):
self.service = service
''
def doDataReceived(self, conn, commandID, data):
defer_tool = self.service.callTarget(commandID, conn, data) return defer_tool
'@param response: str 分垃匏客户端获取的结果'
def produceResult(self, command, response):
return self.dataprotocl.pack(command, response)
''
def loseConnection(self, connID):
self.connmanager.loseConnection(connID)
'@param topicID: int 消息的䞻题id号 @param msg: 消息的类容protobuf结构类型 @param sendList: 掚向的目标列衚(客户端id 列衚)'
def pushObject(self, topicID, msg, sendList):
self.connmanager.pushObject(topicID, msg, sendList)
''
def __init__(self):
self.configpath = None self.mainpath = None self.root = None self.webroot = None
''
def config(self, configpath, mainpath):
self.configpath = configpath self.mainpath = mainpath
''
def masterapp(self):
config = json.load(open(self.configpath, 'r')) GlobalObject().json_config = config mastercnf = config.get('master') rootport = mastercnf.get('rootport') webport = mastercnf.get('webport') masterlog = mastercnf.get('log') self.root = PBRoot() rootservice = services.Service('rootservice') self.root.addServiceChannel(rootservice) self.webroot = vhost.NameVirtualHost() self.webroot.addHost('0.0.0.0', './') GlobalObject().root = self.root GlobalObject().webroot = self.webroot if masterlog: log.addObserver(loogoo(masterlog)) log.startLogging(sys.stdout) import webapp import rootapp reactor.listenTCP(webport, DelaySite(self.webroot)) reactor.listenTCP(rootport, BilateralFactory(self.root))
''
def start(self):
sys_args = sys.argv if ((len(sys_args) > 2) and (sys_args[1] == 'single')): server_name = sys_args[2] if (server_name == 'master'): mode = MASTER_SERVER_MODE else: mode = SINGLE_SERVER_MODE else: mode = MULTI_SERVER_MODE server_name = '' if (mode == MULTI_SERVER_MODE): self.masterapp() config = json.load(open(self.configpath, 'r')) sersconf = config.get('servers') for sername in sersconf.keys(): cmds = ('python %s %s %s' % (self.mainpath, sername, self.configpath)) subprocess.Popen(cmds, shell=True) reactor.run() elif (mode == SINGLE_SERVER_MODE): config = json.load(open(self.configpath, 'r')) sername = server_name cmds = ('python %s %s %s' % (self.mainpath, sername, self.configpath)) subprocess.Popen(cmds, shell=True) else: self.masterapp() reactor.run()
''
def render(self, request):
for child in GlobalObject().root.childsmanager._childs.values(): d = child.callbackChild('serverStop') d.addCallback(ErrorBack) reactor.callLater(0.5, reactor.stop) return 'stop'
''
def render(self, request):
for child in GlobalObject().root.childsmanager._childs.values(): d = child.callbackChild('sreload') d.addCallback(ErrorBack) return 'reload'
'@param port: int 远皋分垃服的端口号 @param rootaddr: 根节点服务噚地址'
def __init__(self, name):
self._name = name self._factory = pb.PBClientFactory() self._reference = ProxyReference() self._addr = None
''
def setName(self, name):
self._name = name
''
def getName(self):
return self._name
''
def connect(self, addr):
self._addr = addr reactor.connectTCP(addr[0], addr[1], self._factory) self.takeProxy()
''
def reconnect(self):
self.connect(self._addr)
''
def addServiceChannel(self, service):
self._reference.addService(service)
''
def takeProxy(self):
deferedRemote = self._factory.getRootObject() deferedRemote.addCallback(callRemote, 'takeProxy', self._name, self._reference)
''
def callRemote(self, commandId, *args, **kw):
deferedRemote = self._factory.getRootObject() return deferedRemote.addCallback(callRemote, 'callTarget', commandId, *args, **kw)
''
def __init__(self):
self._childs = {}
'根据节点的ID获取节点实䟋'
def getChildById(self, childId):
return self._childs.get(childId)
''
def getChildByName(self, childname):
for (key, child) in self._childs.items(): if (child.getName() == childname): return self._childs[key] return None
'添加䞀䞪child节点 @param child: Child object'
def addChild(self, child):
key = child._id if self._childs.has_key(key): raise ('child node %s exists' % key) self._childs[key] = child
'删陀䞀䞪child 节点 @param child: Child Object'
def dropChild(self, child):
key = child._id try: del self._childs[key] except Exception as e: log.msg(str(e))
'删陀䞀䞪child 节点 @param childId: Child ID'
def dropChildByID(self, childId):
try: del self._childs[childId] except Exception as e: log.msg(str(e))
'@param childId: int 子节点的id'
def callChild(self, childId, *args, **kw):
child = self._childs.get(childId, None) if (not child): log.err(("child %s doesn't exists" % childId)) return return child.callbackChild(*args, **kw)
'@param childname: str 子节点的名称'
def callChildByName(self, childname, *args, **kw):
child = self.getChildByName(childname) if (not child): log.err(("child %s doesn't exists" % childname)) return return child.callbackChild(*args, **kw)
'根据sessionID获取child节点信息'
def getChildBYSessionId(self, session_id):
for child in self._childs.values(): if (child._transport.broker.transport.sessionno == session_id): return child return None
''
def __init__(self, cid, name):
self._id = cid self._name = name self._transport = None
''
def getName(self):
return self._name
''
def setTransport(self, transport):
self._transport = transport
'return a Defered Object (recvdata)'
def callbackChild(self, *args, **kw):
recvdata = self._transport.callRemote('callChild', *args, **kw) return recvdata
''
def __init__(self):
self._service = Service('proxy')
''
def addService(self, service):
self._service = service
''
def remote_callChild(self, command, *arg, **kw):
return self._service.callTarget(command, *arg, **kw)
''
def __init__(self, dnsmanager=ChildsManager()):
self.service = None self.childsmanager = dnsmanager
'@param service: Service Object(In bilateral.services)'
def addServiceChannel(self, service):
self.service = service
'@param addr: (hostname,port)hostname 根节点的䞻机名,根节点的端口'
def remote_takeProxy(self, name, transport):
log.msg(('node [%s] takeProxy ready' % name)) child = Child(name, name) self.childsmanager.addChild(child) child.setTransport(transport) self.doChildConnect(name, transport)
'圓node节点连接时的倄理'
def doChildConnect(self, name, transport):
pass
'@param commandId: int 指什号 @param data: str 调甚参数'
def remote_callTarget(self, command, *args, **kw):
data = self.service.callTarget(command, *args, **kw) return data
''
def dropChild(self, *args, **kw):
self.childsmanager.dropChild(*args, **kw)
''
def dropChildByID(self, childId):
self.doChildLostConnect(childId) self.childsmanager.dropChildByID(childId)
''
def dropChildSessionId(self, session_id):
child = self.childsmanager.getChildBYSessionId(session_id) if (not child): return child_id = child._id self.doChildLostConnect(child_id) self.childsmanager.dropChildByID(child_id)
'圓node节点连接时的倄理'
def doChildLostConnect(self, childId):
pass
'@param childId: int 子节点的id return Defered Object'
def callChild(self, key, *args, **kw):
return self.childsmanager.callChild(key, *args, **kw)
'@param childId: int 子节点的id return Defered Object'
def callChildByName(self, childname, *args, **kw):
return self.childsmanager.callChildByName(childname, *args, **kw)
''
def __init__(self):
self.netfactory = None self.root = None self.webroot = None self.remote = {} self.master_remote = None self.db = None self.mem = None self.servername = None self.remoteportlist = []
''
def config(self, config, servername=None, dbconfig=None, memconfig=None, masterconf=None):
GlobalObject().json_config = config netport = config.get('netport') webport = config.get('webport') rootport = config.get('rootport') self.remoteportlist = config.get('remoteport', []) if (not servername): servername = config.get('name') logpath = config.get('log') hasdb = config.get('db') hasmem = config.get('mem') app = config.get('app') cpuid = config.get('cpu') mreload = config.get('reload') self.servername = servername if netport: self.netfactory = LiberateFactory() netservice = services.CommandService('netservice') self.netfactory.addServiceChannel(netservice) reactor.listenTCP(netport, self.netfactory) if webport: self.webroot = vhost.NameVirtualHost() GlobalObject().webroot = self.webroot reactor.listenTCP(webport, DelaySite(self.webroot)) if rootport: self.root = PBRoot() rootservice = services.Service('rootservice') self.root.addServiceChannel(rootservice) reactor.listenTCP(rootport, BilateralFactory(self.root)) for cnf in self.remoteportlist: rname = cnf.get('rootname') self.remote[rname] = RemoteObject(self.servername) if (hasdb and dbconfig): log.msg(str(dbconfig)) dbpool.initPool(**dbconfig) if (hasmem and memconfig): urls = memconfig.get('urls') hostname = str(memconfig.get('hostname')) mclient.connect(urls, hostname) if logpath: log.addObserver(loogoo(logpath)) log.startLogging(sys.stdout) if cpuid: affinity.set_process_affinity_mask(os.getpid(), cpuid) GlobalObject().config(netfactory=self.netfactory, root=self.root, remote=self.remote) if app: __import__(app) if mreload: _path_list = mreload.split('.') GlobalObject().reloadmodule = __import__(mreload, fromlist=_path_list[:1]) GlobalObject().remote_connect = self.remote_connect if masterconf: masterport = masterconf.get('rootport') masterhost = masterconf.get('roothost') self.master_remote = RemoteObject(servername) addr = (('localhost', masterport) if (not masterhost) else (masterhost, masterport)) self.master_remote.connect(addr) GlobalObject().masterremote = self.master_remote import admin
''
def remote_connect(self, rname, rhost):
for cnf in self.remoteportlist: _rname = cnf.get('rootname') if (rname == _rname): rport = cnf.get('rootport') if (not rhost): addr = ('localhost', rport) else: addr = (rhost, rport) self.remote[rname].connect(addr) break
''
def start(self):
log.msg(('%s start...' % self.servername)) log.msg(('%s pid: %s' % (self.servername, os.getpid()))) reactor.run()
'@param url: str http 访问的路埄'
def __init__(self, url=None):
self._url = url
''
def __call__(self, cls):
from twisted.web.resource import Resource if self._url: child_name = self._url else: child_name = cls.__name__ path_list = child_name.split('/') temp_res = None path_list = [path for path in path_list if path] patn_len = len(path_list) for (index, path) in enumerate(path_list): if (index == 0): temp_res = GlobalObject().webroot if (index == (patn_len - 1)): res = cls() temp_res.putChild(path, res) return else: res = temp_res.children.get(path) if (not res): res = Resource() temp_res.putChild(path, res) temp_res = res
''
def __init__(self, remotename):
self.remotename = remotename
''
def __call__(self, target):
GlobalObject().remote[self.remotename]._reference._service.mapTarget(target)
''
def __init__(self, logpath):
self.file = file(logpath, 'w')
''
def __call__(self, eventDict):
if ('logLevel' in eventDict): level = eventDict['logLevel'] elif eventDict['isError']: level = 'ERROR' else: level = 'INFO' text = log.textFromEventDict(eventDict) if ((text is None) or (level != 'ERROR')): return nowdate = datetime.datetime.now() self.file.write((((((('[' + str(nowdate)) + ']\n') + str(level)) + '\n DCTB ') + text) + '\r\n')) self.file.flush()
'Ask a resource to render itself. @param resrc: a L{twisted.web.resource.IResource}.'
def render(self, resrc):
try: body = resrc.render(self) except UnsupportedMethod as e: allowedMethods = e.allowedMethods if ((self.method == 'HEAD') and ('GET' in allowedMethods)): log.msg(('Using GET to fake a HEAD request for %s' % (resrc,))) self.method = 'GET' self._inFakeHead = True body = resrc.render(self) if (body is NOT_DONE_YET): log.msg(('Tried to fake a HEAD request for %s, but it got away from me.' % resrc)) else: self.setHeader('content-length', str(len(body))) self._inFakeHead = False self.method = 'HEAD' self.write('') self.finish() return if (self.method in supportedMethods): self.setHeader('Allow', ', '.join(allowedMethods)) s = ('Your browser approached me (at %(URI)s) with the method "%(method)s". I only allow the method%(plural)s %(allowed)s here.' % {'URI': escape(self.uri), 'method': self.method, 'plural': (((len(allowedMethods) > 1) and 's') or ''), 'allowed': string.join(allowedMethods, ', ')}) epage = resource.ErrorPage(http.NOT_ALLOWED, 'Method Not Allowed', s) body = epage.render(self) else: epage = resource.ErrorPage(http.NOT_IMPLEMENTED, 'Huh?', ("I don't know how to treat a %s request." % (escape(self.method),))) body = epage.render(self) if (body == NOT_DONE_YET): return if ((not isinstance(body, defer.Deferred)) and (type(body) is not types.StringType)): body = resource.ErrorPage(http.INTERNAL_SERVER_ERROR, 'Request did not return a string', ((((((('Request: ' + html.PRE(reflect.safe_repr(self))) + '<br />') + 'Resource: ') + html.PRE(reflect.safe_repr(resrc))) + '<br />') + 'Value: ') + html.PRE(reflect.safe_repr(body)))).render(self) if (self.method == 'HEAD'): if (len(body) > 0): log.msg(("Warning: HEAD request %s for resource %s is returning a message body. I think I'll eat it." % (self, resrc))) self.setHeader('content-length', str(len(body))) self.write('') self.finish() elif isinstance(body, defer.Deferred): body.addCallback(self._deferwrite) else: self.setHeader('content-length', str(len(body))) self.write(body) self.finish()
''
def _deferwrite(self, body):
self.setHeader('content-length', str(len(body))) self.write(body) self.finish()
''
def getHeadlength():
pass
'Add a target unDisplay when client call it.'
def addUnDisplayTarget(self, command):
self.unDisplay.add(command)
'Add a target to the service.'
def mapTarget(self, target):
self._lock.acquire() try: key = target.__name__ if self._targets.has_key(key): exist_target = self._targets.get(key) raise ('target [%d] Already exists, Conflict between the %s and %s' % (key, exist_target.__name__, target.__name__)) self._targets[key] = target finally: self._lock.release()
'Remove a target from the service.'
def unMapTarget(self, target):
self._lock.acquire() try: key = target.__name__ if (key in self._targets): del self._targets[key] finally: self._lock.release()
'Remove a target from the service.'
def unMapTargetByKey(self, targetKey):
self._lock.acquire() try: del self._targets[targetKey] finally: self._lock.release()
'Get a target from the service by name.'
def getTarget(self, targetKey):
self._lock.acquire() try: target = self._targets.get(targetKey, None) finally: self._lock.release() return target
'call Target @param conn: client connection @param targetKey: target ID @param data: client data'
def callTarget(self, targetKey, *args, **kw):
if (self._runstyle == self.SINGLE_STYLE): result = self.callTargetSingle(targetKey, *args, **kw) else: result = self.callTargetParallel(targetKey, *args, **kw) return result
'call Target by Single @param conn: client connection @param targetKey: target ID @param data: client data'
def callTargetSingle(self, targetKey, *args, **kw):
target = self.getTarget(targetKey) self._lock.acquire() try: if (not target): log.err((('the command ' + str(targetKey)) + ' not Found on service')) return None if (targetKey not in self.unDisplay): log.msg(('call method %s on service[single]' % target.__name__)) defer_data = target(*args, **kw) if (not defer_data): return None if isinstance(defer_data, defer.Deferred): return defer_data d = defer.Deferred() d.callback(defer_data) finally: self._lock.release() return d
'call Target by Single @param conn: client connection @param targetKey: target ID @param data: client data'
def callTargetParallel(self, targetKey, *args, **kw):
self._lock.acquire() try: target = self.getTarget(targetKey) if (not target): log.err((('the command ' + str(targetKey)) + ' not Found on service')) return None log.msg(('call method %s on service[parallel]' % target.__name__)) d = threads.deferToThread(target, *args, **kw) finally: self._lock.release() return d
'Add a target to the service.'
def mapTarget(self, target):
self._lock.acquire() try: key = int(target.__name__.split('_')[(-1)]) if self._targets.has_key(key): exist_target = self._targets.get(key) raise ('target [%d] Already exists, Conflict between the %s and %s' % (key, exist_target.__name__, target.__name__)) self._targets[key] = target finally: self._lock.release()
'Remove a target from the service.'
def unMapTarget(self, target):
self._lock.acquire() try: key = int(target.__name__.split('_')[(-1)]) if (key in self._targets): del self._targets[key] finally: self._lock.release()
''
def __init__(self, subcommond, *args):
self.subcommond = subcommond self.args = args
''
def execute(self):
try: commmd = getattr(commands, self.subcommond) commmd.execute(*self.args) except: modes = dir(commands) lines = [((' DCTB ' + m) + '\n') for m in modes if (not m.startswith('_'))] firstline = 'args error\nargs:\n' print ''.join(([firstline] + lines))
''
def __init__(self, name, pk, data={}):
MemObject.__init__(self, name, mclient) self._state = MMODE_STATE_ORI self._pk = pk self.data = data self._time = time.time()
''
def delete(self):
return MemObject.update(self, '_state', MMODE_STATE_DEL)
''
def mdelete(self):
self.syncDB() MemObject.mdelete(self)
''
def IsEffective(self):
if (self.get('_state') == MMODE_STATE_DEL): return False return True
''
def syncDB(self):
state = self.get('_state') tablename = self._name.split(':')[0] if (state == MMODE_STATE_ORI): return elif (state == MMODE_STATE_NEW): props = self.get('data') pk = self.get('_pk') result = util.InsertIntoDB(tablename, props) elif (state == MMODE_STATE_UPDATE): props = self.get('data') pk = self.get('_pk') prere = {pk: props.get(pk)} util.UpdateWithDict(tablename, props, prere) result = True else: pk = self.get('_pk') props = self.get('data') prere = {pk: props.get(pk)} result = util.DeleteFromDB(tablename, prere) if result: MemObject.update(self, '_state', MMODE_STATE_ORI)
''
def checkSync(self, timeout=TIMEOUT):
ntime = time.time() objtime = MemObject.get(self, '_time') if (((ntime - objtime) >= timeout) and timeout): self.mdelete() else: self.syncDB()
'将MAdmin配眮的信息写入memcached䞭保存。 圓圚其他的进皋䞭实䟋化盞同的配眮的MAdmin可以䜿埗数据同步。'
def insert(self):
if (self._incrkey and (not self.get('_incrvalue'))): self._incrvalue = util.GetTableIncrValue(self._name) MemObject.insert(self)
''
def load(self):
mmname = self._name recordlist = util.ReadDataFromDB(mmname) for record in recordlist: pk = record[self._pk] mm = MMode((self._name + (':%s' % pk)), self._pk, data=record) mm.insert()
'䜜䞺䞀䞪特性属性。可以获取这䞪madmin的盞关信息'
@property def madmininfo(self):
keys = self.__dict__.keys() info = self.get_multi(keys) return info
''
def getAllPkByFk(self, fk):
name = ('%s_fk:%s' % (self._name, fk)) fkmm = MFKMode(name) pklist = fkmm.get('pklist') if (pklist is not None): return pklist props = {self._fk: fk} dbkeylist = util.getAllPkByFkInDB(self._name, self._pk, props) name = ('%s_fk:%s' % (self._name, fk)) fkmm = MFKMode(name, pklist=dbkeylist) fkmm.insert() return dbkeylist
'根据䞻键可以获埗mmode对象的实䟋. >>> m = madmin.getObj(1)'
def getObj(self, pk):
mm = MMode((self._name + (':%s' % pk)), self._pk) if (not mm.IsEffective()): return None if mm.get('data'): return mm props = {self._pk: pk} record = util.GetOneRecordInfo(self._name, props) if (not record): return None mm = MMode((self._name + (':%s' % pk)), self._pk, data=record) mm.insert() return mm
'根据䞻键可以获埗mmode对象的实䟋的数据. >>> m = madmin.getObjData(1)'
def getObjData(self, pk):
mm = MMode((self._name + (':%s' % pk)), self._pk) if (not mm.IsEffective()): return None data = mm.get('data') if mm.get('data'): return data props = {self._pk: pk} record = util.GetOneRecordInfo(self._name, props) if (not record): return None mm = MMode((self._name + (':%s' % pk)), self._pk, data=record) mm.insert() return record
'根据䞻键列衚获取mmode对象的列衚. >>> m = madmin.getObjList([1,2,3,4,5])'
def getObjList(self, pklist):
_pklist = [] objlist = [] for pk in pklist: mm = MMode((self._name + (':%s' % pk)), self._pk) if (not mm.IsEffective()): continue if mm.get('data'): objlist.append(mm) else: _pklist.append(pk) if _pklist: recordlist = util.GetRecordList(self._name, self._pk, _pklist) for record in recordlist: pk = record[self._pk] mm = MMode((self._name + (':%s' % pk)), self._pk, data=record) mm.insert() objlist.append(mm) return objlist
'这里只是修改内存䞭的记圕状态_state䞺删陀状态. >>> m = madmin.deleteMode(1)'
def deleteMode(self, pk):
mm = self.getObj(pk) if mm: if self._fk: data = mm.get('data') if data: fk = data.get(self._fk, 0) name = ('%s_fk:%s' % (self._name, fk)) fkmm = MFKMode(name) pklist = fkmm.get('pklist') if (pklist and (pk in pklist)): pklist.remove(pk) fkmm.update('pklist', pklist) mm.delete() return True
'>>> m = madmin.checkAll()'
def checkAll(self):
key = ('%s:%s:' % (mclient._hostname, self._name)) _pklist = util.getallkeys(key, mclient.connection) for pk in _pklist: mm = MMode((self._name + (':%s' % pk)), self._pk) if (not mm.IsEffective()): mm.mdelete() continue if (not mm.get('data')): continue mm.checkSync(timeout=self._timeout) self.deleteAllFk()
''
def deleteAllFk(self):
key = ('%s:%s_fk:' % (mclient._hostname, self._name)) _fklist = util.getallkeys(key, mclient.connection) for fk in _fklist: name = ('%s_fk:%s' % (self._name, fk)) fkmm = MFKMode(name) fkmm.mdelete()
''
def new(self, data):
incrkey = self._incrkey if incrkey: incrvalue = self.incr('_incrvalue', 1) data[incrkey] = (incrvalue - 1) pk = data.get(self._pk) if (pk is None): raise PKValueError(data) mm = MMode((self._name + (':%s' % pk)), self._pk, data=data) setattr(mm, incrkey, pk) else: pk = data.get(self._pk) mm = MMode((self._name + (':%s' % pk)), self._pk, data=data) if self._fk: fk = data.get(self._fk, 0) name = ('%s_fk:%s' % (self._name, fk)) fkmm = MFKMode(name) pklist = fkmm.get('pklist') if (pklist is None): pklist = self.getAllPkByFk(fk) pklist.append(pk) fkmm.update('pklist', pklist) setattr(mm, '_state', MMODE_STATE_NEW) mm.insert() return mm
'初始化所有管理的的madmin的集合攟圚self.adminsäž­'
def __init__(self):
self.admins = {}
'泚册䞀䞪madmin对象到管理䞭. >>> madmin = MAdmin(\'tb_registe\',\'characterId\',incrkey=\'id\') >>> MAdminManager().registe(madmin)'
def registe(self, admin):
self.admins[admin._name] = admin
'移陀䞀䞪madmin对象. >>> MAdminManager().dropAdmin(madmin)'
def dropAdmin(self, adminname):
if self.admins.has_key(adminname): del self.admins[adminname]
'根据madmin的名字获取madmin对象 >>> madmin = MAdminManager().getAdmin(\'tb_registe\')'
def getAdmin(self, adminname):
return self.admins.get(adminname)
'遍历所有的madmin䞎数据库进行同步。 >>>MAdminManager().checkAdmins()'
def checkAdmins(self):
for admin in self.admins.values(): admin.checkAll()
'Creates a new SQLQuery. >>> SQLQuery("x") <sql: \'x\'> >>> q = SQLQuery([\'SELECT * FROM \', \'test\', \' WHERE x=\', SQLParam(1)]) >>> q <sql: \'SELECT * FROM test WHERE x=1\'> >>> q.query(), q.values() (\'SELECT * FROM test WHERE x=%s\', [1]) >>> SQLQuery(SQLParam(1)) <sql: \'1\'>'
def __init__(self, items=None):
if (items is None): self.items = [] elif isinstance(items, list): self.items = items elif isinstance(items, SQLParam): self.items = [items] elif isinstance(items, SQLQuery): self.items = list(items.items) else: self.items = [items] for (i, item) in enumerate(self.items): if (isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral)): self.items[i] = item.value.v
'Returns the query part of the sql query. >>> q = SQLQuery(["SELECT * FROM test WHERE name=", SQLParam(\'joe\')]) >>> q.query() \'SELECT * FROM test WHERE name=%s\' >>> q.query(paramstyle=\'qmark\') \'SELECT * FROM test WHERE name=?\''
def query(self, paramstyle=None):
s = [] for x in self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) if (paramstyle in ['format', 'pyformat']): if (('%' in x) and ('%%' not in x)): x = x.replace('%', '%%') s.append(x) return ''.join(s)
'Returns the values of the parameters used in the sql query. >>> q = SQLQuery(["SELECT * FROM test WHERE name=", SQLParam(\'joe\')]) >>> q.values() [\'joe\']'
def values(self):
return [i.value for i in self.items if isinstance(i, SQLParam)]
'Joins multiple queries. >>> SQLQuery.join([\'a\', \'b\'], \', \') <sql: \'a, b\'> Optinally, prefix and suffix arguments can be provided. >>> SQLQuery.join([\'a\', \'b\'], \', \', prefix=\'(\', suffix=\')\') <sql: \'(a, b)\'> If target argument is provided, the items are appended to target instead of creating a new SQLQuery.'
def join(items, sep=' ', prefix=None, suffix=None, target=None):
if (target is None): target = SQLQuery() target_items = target.items if prefix: target_items.append(prefix) for (i, item) in enumerate(items): if (i != 0): target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return target
'Creates a database.'
def __init__(self):
pass
'Execute SQL query `sql_query` using dictionary `vars` to interpolate it. If `processed=True`, `vars` is a `reparam`-style list to use instead of interpolating. >>> db = DB(None, {}) >>> db.query("SELECT * FROM foo", _test=True) <sql: \'SELECT * FROM foo\'> >>> db.query("SELECT * FROM foo WHERE x = $x", vars=dict(x=\'f\'), _test=True) <sql: "SELECT * FROM foo WHERE x = \'f\'"> >>> db.query("SELECT * FROM foo WHERE x = " + sqlquote(\'f\'), _test=True) <sql: "SELECT * FROM foo WHERE x = \'f\'">'
def query(self, sql_query, processed=False, svars=None):
if (svars is None): svars = {} if ((not processed) and (not isinstance(sql_query, SQLQuery))): sql_query = reparam(sql_query, svars) return sql_query
'Selects `what` from `tables` with clauses `where`, `order`, `group`, `limit`, and `offset`. Uses vars to interpolate. Otherwise, each clause can be a SQLQuery. >>> db = DB(None, {}) >>> db.select(\'foo\', _test=True) <sql: \'SELECT * FROM foo\'> >>> db.select([\'foo\', \'bar\'], where="foo.bar_id = bar.id", limit=5, _test=True) <sql: \'SELECT * FROM foo, bar WHERE foo.bar_id = bar.id LIMIT 5\'>'
def select(self, tables, svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False):
if (svars is None): svars = {} sql_clauses = self.sql_clauses(what, tables, where, group, order, limit, offset) clauses = [self.gen_clause(sql, val, svars) for (sql, val) in sql_clauses if (val is not None)] qout = SQLQuery.join(clauses) if _test: return qout return self.query(qout, processed=True)