本文整理汇总了Python中psycopg2.extensions.adapt函数的典型用法代码示例。如果您正苦于以下问题:Python adapt函数的具体用法?Python adapt怎么用?Python adapt使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了adapt函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: updateRequest
def updateRequest(self, team_id, requestDict):
'''
Method to a update a request in missions_request table
@param team_id: team_id code e.g index in DB table of the team... as returned by rest api
@param requestDict: request dictiionary - keys have to be the same key of Db
'''
self.checkConnection()
# preare dictionary to be used for DB
requestOdered = self.prepareRequestDict(team_id, requestDict)
# create query
sqlquery = "UPDATE missions_request SET "
for k,v in requestOdered.items():
if k == "id":
continue
sqlquery += '%s=%s, ' % (k,adapt(v))
sqlquery = sqlquery[0:-2] + " "
sqlquery += "WHERE id=%s" % adapt(requestOdered["id"])
QgsLogger.debug(self.tr("Aggiorna request con la query: %s" % sqlquery), 1 )
try:
self.cursor.execute(sqlquery)
except Exception as ex:
raise(ex)
示例2: updateTeam
def updateTeam(self, teamDict):
'''
Method to a update a team in organization_team table
@param teamDict: team dictiionary - keys have to be the same key of Db
'''
self.checkConnection()
# preare dictionary to be used for DB
teamOdered = self.prepareTeamDict(teamDict)
# create query
sqlquery = "UPDATE organization_team SET "
for k,v in teamOdered.items():
if k == "id":
continue
sqlquery += '%s=%s, ' % (k,adapt(v))
sqlquery = sqlquery[0:-2] + " "
sqlquery += "WHERE id=%s" % adapt(teamOdered["id"])
QgsLogger.debug(self.tr("Aggiorna team con la query: %s" % sqlquery), 1 )
try:
self.cursor.execute(sqlquery)
except Exception as ex:
raise(ex)
示例3: execute
def execute(self, operation, parameters=None):
if self.closed():
raise errors.Error('Cursor is closed')
if parameters:
# optional requirement
from psycopg2.extensions import adapt
if isinstance(parameters, dict):
for key in parameters:
v = adapt(parameters[key]).getquoted()
operation = operation.replace(':' + key, v)
elif isinstance(parameters, tuple):
operation = operation % tuple(adapt(p).getquoted() for p in parameters)
else:
raise errors.Error("Argument 'parameters' must be dict or tuple")
self.rowcount = 0
self.buffered_rows = collections.deque()
self.last_execution = operation
self.connection.write(messages.Query(operation))
self.fetch_rows()
if self.error is not None:
raise self.error
示例4: add_command
def add_command(self,command):
TAG = 'add_command'
if isinstance(command, dict):
if command.get(C.SAMSUNG_COMMANDS_TABLE_ACTION) and \
command.get(C.SAMSUNG_COMMANDS_TABLE_DEVICE) \
and command.get(C.SAMSUNG_COMMANDS_TABLE_UUID):
if not command[C.SAMSUNG_COMMANDS_TABLE_ATTRIBUTE]:
command[C.SAMSUNG_COMMANDS_TABLE_ATTRIBUTE]= "{}"
self.cursor.execute(""" insert into samsung_commands
(device_id, action,attribute,command_uuid)
values( %s,%s,%s,%s) returning id""",
[command[C.SAMSUNG_COMMANDS_TABLE_DEVICE],
command[C.SAMSUNG_COMMANDS_TABLE_ACTION],
adapt(command[C.SAMSUNG_COMMANDS_TABLE_ATTRIBUTE]),
adapt(command[C.SAMSUNG_COMMANDS_TABLE_UUID])])
if self.cursor.rowcount>0:
row = self.cursor.fetchone();
return row[0]
else:
return None
else:
self.log.i(TAG, 'Not all required parameters sent in '+command.__repr__())
return None
示例5: adapt_box
def adapt_box(box):
return AsIs("'(%s,%s),(%s,%s)'::box" % (
adapt(box.first_vertex.x),
adapt(box.first_vertex.y),
adapt(box.second_vertex.x),
adapt(box.second_vertex.y)
))
示例6: add_device
def add_device(self, device):
TAG = 'add_device'
## if user_id, udid and os is present then only we can do entry
if type(device) == dict and C.DEVICE_TABLE_USER in device:
if UserDBHelper().is_user_valid(str(device.get('user_id'))):
if device.has_key(C.DEVICE_TABLE_OS):
if device.has_key(C.DEVICE_TABLE_UDID):
try:
self.cursor.execute("""INSERT INTO devices
(os, udid, user_id) VALUES({0}, {1}, {2})
RETURNING id""".format(adapt(device.get('os')),
adapt(device.get('udid')),
adapt(device.get('user_id'))))
except Exception,err:
self.log.e(TAG,'Exception : ' + repr(err))
return None
if self.cursor.rowcount > 0:
row = self.cursor.fetchone()
return row[0]
else:
self.log.e(TAG,'Not abe to insert in device table')
return None
else:
self.log.e(TAG,'UDID not found in dictionary')
return None
else:
self.log.e(TAG, 'OS is not found in dictionary')
return None
else:
self.log.e(TAG, 'USER ID not found in dictionary')
return None
示例7: getquoted
def getquoted(self):
if self.name is None:
raise NotImplementedError(
"RangeAdapter must be subclassed overriding its name " "or the getquoted() method"
)
r = self.adapted
if r.isempty:
return b("'empty'::" + self.name)
if r.lower is not None:
a = adapt(r.lower)
if hasattr(a, "prepare"):
a.prepare(self._conn)
lower = a.getquoted()
else:
lower = b("NULL")
if r.upper is not None:
a = adapt(r.upper)
if hasattr(a, "prepare"):
a.prepare(self._conn)
upper = a.getquoted()
else:
upper = b("NULL")
return b(self.name + "(") + lower + b(", ") + upper + b(", '%s')" % r._bounds)
示例8: adapt_lseg
def adapt_lseg(l):
return AsIs("'[(%s,%s), (%s,%s)]'::lseg" % (\
adapt(l.init_point.x),
adapt(l.init_point.y),
adapt(l.end_point.x),
adapt(l.end_point.y)
))
示例9: adapt_range
def adapt_range(pgrange, pyrange):
if isinstance(pgrange, ustr):
pgrange = pgrange.encode("utf8")
if not isinstance(pyrange, range_):
raise ValueError((
"Trying to adapt range {range.__class__.__name__} which does not "
"extend base range type.").format(range=pyrange))
if not pyrange:
return AsIs((b"'empty'::" + pgrange).decode("utf8"))
lower = b"NULL"
if not pyrange.lower_inf:
lower = adapt(pyrange.lower).getquoted()
upper = b"NULL"
if not pyrange.upper_inf:
upper = adapt(pyrange.upper).getquoted()
return AsIs(b"".join([
pgrange,
b"(",
lower,
b", ",
upper,
b", '",
b"[" if pyrange.lower_inc else b"(",
b"]" if pyrange.upper_inc else b")",
b"')",
]).decode("utf8"))
示例10: adapt_box
def adapt_box(box):
return AsIs("'(%s,%s),(%s,%s)'::box" % (
adapt(box.init_point.x),
adapt(box.init_point.y),
adapt(box.end_point.x),
adapt(box.end_point.y)
))
示例11: topologyInsert
def topologyInsert(con, simulationId, atomNum, atomName, atomType, residueCode, residueNumber, chainCode, description):
sql_insert_topology="INSERT INTO dnamodel.topology (simulationId, atomNum, atomName, atomType, residueNum, residueCode, chainCode, description) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) RETURNING topologyId;"
cur = con.cursor()
cur.execute(sql_insert_topology, (simulationId, atomNum, adapt(atomName), adapt(atomType), residueNumber, adapt(residueCode), adapt(chainCode), adapt(description)))
topologyId = cur.fetchone()[0]
cur.close()
return topologyId
示例12: getquoted
def getquoted(self):
if self.name is None:
raise NotImplementedError(
"RangeAdapter must be subclassed overriding its name " "or the getquoted() method"
)
r = self.adapted
if r.isempty:
return b"'empty'::" + self.name.encode("utf8")
if r.lower is not None:
a = adapt(r.lower)
if hasattr(a, "prepare"):
a.prepare(self._conn)
lower = a.getquoted()
else:
lower = b"NULL"
if r.upper is not None:
a = adapt(r.upper)
if hasattr(a, "prepare"):
a.prepare(self._conn)
upper = a.getquoted()
else:
upper = b"NULL"
return self.name.encode("utf8") + b"(" + lower + b", " + upper + b", '" + r._bounds.encode("utf8") + b"')"
示例13: adapt_range
def adapt_range(pgrange, pyrange):
if not isinstance(pyrange, range_):
raise ValueError((
"Trying to adapt range {range.__class__.__name__} which does not "
"extend base range type.").format(range=pyrange))
if not pyrange:
return AsIs("'empty'::" + pgrange)
lower = b("NULL")
if not pyrange.lower_inf:
lower = adapt(pyrange.lower).getquoted()
upper = b("NULL")
if not pyrange.upper_inf:
upper = adapt(pyrange.upper).getquoted()
return AsIs(b"".join([
b(pgrange),
b("("),
lower,
b(", "),
upper,
b(", '"),
b("[" if pyrange.lower_inc else "("),
b("]" if pyrange.upper_inc else ")"),
b("')")
]).decode("utf8"))
示例14: getquoted
def getquoted(self):
if self.name is None:
raise NotImplementedError(
'RangeAdapter must be subclassed overriding its name '
'or the getquoted() method')
r = self.adapted
if r.isempty:
return b"'empty'::" + self.name.encode('utf8')
if r.lower is not None:
a = adapt(r.lower)
if hasattr(a, 'prepare'):
a.prepare(self._conn)
lower = a.getquoted()
else:
lower = b'NULL'
if r.upper is not None:
a = adapt(r.upper)
if hasattr(a, 'prepare'):
a.prepare(self._conn)
upper = a.getquoted()
else:
upper = b'NULL'
return self.name.encode('utf8') + b'(' + lower + b', ' + upper \
+ b", '" + r._bounds.encode('utf8') + b"')"
示例15: getSingleTableSql
def getSingleTableSql(host, name, interval=None):
if interval==None:
interval = "AND tsd_timestamp > ('now'::timestamp - '8 days'::interval)"
else:
if 'interval' in interval:
interval = "AND tsd_timestamp > %s::interval" % (adapt(interval['interval']), )
else:
interval = "AND tsd_timestamp BETWEEN %s::timestamp and %s::timestamp" % (adapt(interval['from']),adapt(interval['to']), )
sql = """
SELECT tsd_table_id,
tsd_timestamp,
tsd_table_size,
tsd_index_size,
tsd_seq_scans,
tsd_index_scans,
tsd_tup_ins,
tsd_tup_upd,
tsd_tup_del,
tsd_tup_hot_upd
FROM monitor_data.table_size_data
WHERE tsd_table_id = ( SELECT t_id FROM monitor_data.tables WHERE t_schema || '.' || t_name = """ + str(adapt(name)) + """ AND t_host_id = """ + str(adapt(host)) + """ )
AND tsd_host_id = """ + str(adapt(host)) + """
"""+interval+"""
ORDER BY tsd_timestamp ASC
"""
return sql