本文整理汇总了Python中psycopg2.extras.register_hstore函数的典型用法代码示例。如果您正苦于以下问题:Python register_hstore函数的具体用法?Python register_hstore怎么用?Python register_hstore使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了register_hstore函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: register_type_handlers
def register_type_handlers(connection, **kwargs):
if connection.vendor != 'postgresql':
return
try:
oids, array_oids = get_hstore_oids(connection.alias)
register_hstore(connection.connection, globally=True, oid=oids, array_oid=array_oids)
except ProgrammingError:
# Hstore is not available on the database.
#
# If someone tries to create an hstore field it will error there.
# This is necessary as someone may be using PSQL without extensions
# installed but be using other features of contrib.postgres.
#
# This is also needed in order to create the connection in order to
# install the hstore extension.
pass
try:
citext_oids = get_citext_oids(connection.alias)
array_type = psycopg2.extensions.new_array_type(citext_oids, 'citext[]', psycopg2.STRING)
psycopg2.extensions.register_type(array_type, None)
except ProgrammingError:
# citext is not available on the database.
#
# The same comments in the except block of the above call to
# register_hstore() also apply here.
pass
示例2: test_array_cast
def test_array_cast(self):
from psycopg2.extras import register_hstore
register_hstore(self.conn)
cur = self.conn.cursor()
cur.execute("select array['a=>1'::hstore, 'b=>2'::hstore];")
a = cur.fetchone()[0]
self.assertEqual(a, [{'a': '1'}, {'b': '2'}])
示例3: register_type_handlers
def register_type_handlers(connection, **kwargs):
if connection.vendor != 'postgresql':
return
try:
register_hstore(connection.connection, globally=True)
except ProgrammingError:
# Hstore is not available on the database.
#
# If someone tries to create an hstore field it will error there.
# This is necessary as someone may be using PSQL without extensions
# installed but be using other features of contrib.postgres.
#
# This is also needed in order to create the connection in order to
# install the hstore extension.
pass
try:
with connection.cursor() as cursor:
# Retrieve oids of citext arrays.
cursor.execute("SELECT typarray FROM pg_type WHERE typname = 'citext'")
oids = tuple(row[0] for row in cursor)
array_type = psycopg2.extensions.new_array_type(oids, 'citext[]', psycopg2.STRING)
psycopg2.extensions.register_type(array_type, None)
except ProgrammingError:
# citext is not available on the database.
#
# The same comments in the except block of the above call to
# register_hstore() also apply here.
pass
示例4: test_roundtrip
def test_roundtrip(self):
from psycopg2.extras import register_hstore
register_hstore(self.conn)
cur = self.conn.cursor()
def ok(d):
cur.execute("select %s", (d,))
d1 = cur.fetchone()[0]
self.assertEqual(len(d), len(d1))
for k in d:
self.assert_(k in d1, k)
self.assertEqual(d[k], d1[k])
ok({})
ok({"a": "b", "c": None})
ab = map(chr, range(32, 128))
ok(dict(zip(ab, ab)))
ok({"".join(ab): "".join(ab)})
self.conn.set_client_encoding("latin1")
if sys.version_info[0] < 3:
ab = map(chr, range(32, 127) + range(160, 255))
else:
ab = bytes(range(32, 127) + range(160, 255)).decode("latin1")
ok({"".join(ab): "".join(ab)})
ok(dict(zip(ab, ab)))
示例5: register_hstore_handler
def register_hstore_handler(connection, **kwargs):
if not connection.settings_dict.get('HAS_HSTORE', True):
return
if sys.version_info[0] < 3:
register_hstore(connection.connection, globally=True, unicode=True)
else:
register_hstore(connection.connection, globally=True)
示例6: test_roundtrip_array
def test_roundtrip_array(self):
from psycopg2.extras import register_hstore
register_hstore(self.conn)
ds = []
ds.append({})
ds.append({"a": "b", "c": None})
ab = map(chr, range(32, 128))
ds.append(dict(zip(ab, ab)))
ds.append({"".join(ab): "".join(ab)})
self.conn.set_client_encoding("latin1")
if sys.version_info[0] < 3:
ab = map(chr, range(32, 127) + range(160, 255))
else:
ab = bytes(range(32, 127) + range(160, 255)).decode("latin1")
ds.append({"".join(ab): "".join(ab)})
ds.append(dict(zip(ab, ab)))
cur = self.conn.cursor()
cur.execute("select %s", (ds,))
ds1 = cur.fetchone()[0]
self.assertEqual(ds, ds1)
示例7: connect
def connect(dsn=None, *, timeout=TIMEOUT, loop=None,
enable_json=True, enable_hstore=True, echo=False, **kwargs):
"""A factory for connecting to PostgreSQL.
The coroutine accepts all parameters that psycopg2.connect() does
plus optional keyword-only `loop` and `timeout` parameters.
Returns instantiated Connection object.
"""
if loop is None:
loop = asyncio.get_event_loop()
waiter = asyncio.Future(loop=loop)
conn = Connection(dsn, loop, timeout, waiter, bool(echo), **kwargs)
try:
yield from conn._poll(waiter, timeout)
except Exception:
conn.close()
raise
if enable_json:
extras.register_default_json(conn._conn)
if enable_hstore:
oids = yield from _enable_hstore(conn)
if oids is not None:
oid, array_oid = oids
extras.register_hstore(conn._conn, oid=oid, array_oid=array_oid)
return conn
示例8: correct_qa_config
def correct_qa_config(cursor, branch_id, merge_base_commit_hash):
""" Return the config_id to release a new commit to this build with """
register_hstore(cursor)
# if there are releases on this branch, use the config from the most recent
# otherwise use the most recent release of the merge base commit
cursor.execute(
("select config_id "
" from release "
" join iteration using (iteration_id) "
" where branch_id=%s "
" or commit_hash=%s "
" order by iteration.created_dt desc, release.created_dt desc "
" limit 1 "),
(branch_id, merge_base_commit_hash),
)
results = cursor.fetchall()
if len(results) is 0:
config_id = save(
cursor,
'config', # table
['key_value_pairs'], # unique columns
['key_value_pairs'], # column
({},), # value
)
elif len(results) is 1:
config_id = results[0][0]
else:
raise ValueError("There should only be one correct config")
return config_id
示例9: __init__
def __init__(self, engine, **kw):
super(HStore, self).__init__(engine, **kw)
spliturl = urlsplit(engine)
try:
self._conn = conn = psycopg2.connect(
host=spliturl.hostname,
port=spliturl.port,
database=spliturl.path,
user=spliturl.username or "",
password=spliturl.password or "",
)
self._store = db = conn.cursor(cursor_factory=extras.RealDictCursor)
except psycopg2.OperationalError:
logging.exception("configuration error")
raise TypeError("configuration error")
try:
db.execute("CREATE EXTENSION hstore")
conn.commit()
except psycopg2.ProgrammingError:
conn.rollback()
extras.register_hstore(conn)
try:
db.execute("CREATE TABLE shove (id serial PRIMARY KEY, data hstore)")
conn.commit()
db.execute("INSERT INTO shove (data) VALUES (%s)", ['"key"=>"value"'])
conn.commit()
db.execute("UPDATE shove SET data = delete(data, %s)", ["key"])
except psycopg2.ProgrammingError:
conn.rollback()
示例10: on_connect
def on_connect(conn):
hstore_oids = self._hstore_oids(conn)
if hstore_oids is not None:
oid, array_oid = hstore_oids
if util.py2k:
extras.register_hstore(conn, oid=oid, array_oid=array_oid, unicode=True)
else:
extras.register_hstore(conn, oid=oid, array_oid=array_oid)
示例11: setup_postgresql_hstore_extension
def setup_postgresql_hstore_extension(sender, connection, **kwargs):
from psycopg2.extras import register_hstore
cursor = connection.connection.cursor()
cursor.execute('CREATE EXTENSION IF NOT EXISTS hstore')
if PY2:
register_hstore(connection.connection, globally=True, unicode=True)
else:
register_hstore(connection.connection, globally=True)
示例12: _register_hstore_converter
def _register_hstore_converter(self, engine):
from psycopg2.extras import register_hstore
from psycopg2 import ProgrammingError
connection = engine.connect()
try:
register_hstore(connection.connection, globally=True)
except ProgrammingError:
pass
示例13: renderTile
def renderTile(self, width, height, srs, coord):
""" Render a single tile, return a SaveableResponse instance.
"""
# tilesize = self.tileSize * 16
#
# # center pixel on zoomlevel
# center = (tilesize << coord.zoom) >> 1
# # maximum coordinate in web mercator
# f900913 = 20037508.342789244
#
# # pixel relative to global center
# dx = (coord.column * tilesize) - center
# # flip y-axis
# dy = center - (coord.row * tilesize)
#
# # size of one pixel
# div = f900913 / center
#
conn = _connect(self.dbdsn)
db = conn.cursor()
register_hstore(conn, True, False)
db.execute(self.query_tile, (coord.column * self.tileSize, coord.row * self.tileSize, coord.zoom))
rows = db.fetchall()
logging.debug(self.query_tile)
bbox = 0
tile = {"bbox": bbox, "granularity":10000, "features":[]}
features = []
for row in rows:
# empty geometry
if (row[0] is None) or (row[1] is None):
continue
#logging.debug(str(row[1]))
geojson = json.loads(str(row[1]))
# tags = {}
# for tag in row[0].iteritems():
# tags[tag[0]] = ("%s" %(tag[1])).decode('utf-8')
#
# print tags
#
# geojson["properties"] = tags
geojson["properties"] = row[0]
features.append(geojson)
tile["features"].extend(features)
try:
conn.commit()
except Exception, e:
logging.error(">>> %s", e)
conn.rollback()
示例14: on_connect
def on_connect(conn):
hstore_oids = self._hstore_oids(conn)
if hstore_oids is not None:
oid, array_oid = hstore_oids
kw = {'oid': oid}
if util.py2k:
kw['unicode'] = True
if self.psycopg2_version >= (2, 4, 3):
kw['array_oid'] = array_oid
extras.register_hstore(conn, **kw)
示例15: _cursor
def _cursor(self):
# ensure that we're connected
cursor = super(DatabaseWrapper, self)._cursor()
# register hstore extension
register_hstore(self.connection, globally=True, unicode=True)
# bypass future registrations
self._cursor = super(DatabaseWrapper, self)._cursor
return cursor