MCPcopy Create free account
hub / github.com/MagicStack/asyncpg / test_custom_codec_binary

Method test_custom_codec_binary

tests/test_codecs.py:1286–1364  ·  view source on GitHub ↗

Test encoding/decoding using a custom codec in binary mode.

(self)

Source from the content-addressed store, hash-verified

1284 ''')
1285
1286 async def test_custom_codec_binary(self):
1287 """Test encoding/decoding using a custom codec in binary mode."""
1288 await self.con.execute('''
1289 CREATE EXTENSION IF NOT EXISTS hstore
1290 ''')
1291
1292 longstruct = struct.Struct('!L')
1293 ulong_unpack = lambda b: longstruct.unpack_from(b)[0]
1294 ulong_pack = longstruct.pack
1295
1296 def hstore_decoder(data):
1297 result = {}
1298 n = ulong_unpack(data)
1299 view = memoryview(data)
1300 ptr = 4
1301
1302 for i in range(n):
1303 klen = ulong_unpack(view[ptr:ptr + 4])
1304 ptr += 4
1305 k = bytes(view[ptr:ptr + klen]).decode()
1306 ptr += klen
1307 vlen = ulong_unpack(view[ptr:ptr + 4])
1308 ptr += 4
1309 if vlen == -1:
1310 v = None
1311 else:
1312 v = bytes(view[ptr:ptr + vlen]).decode()
1313 ptr += vlen
1314
1315 result[k] = v
1316
1317 return result
1318
1319 def hstore_encoder(obj):
1320 buffer = bytearray(ulong_pack(len(obj)))
1321
1322 for k, v in obj.items():
1323 kenc = k.encode()
1324 buffer += ulong_pack(len(kenc)) + kenc
1325
1326 if v is None:
1327 buffer += b'\xFF\xFF\xFF\xFF' # -1
1328 else:
1329 venc = v.encode()
1330 buffer += ulong_pack(len(venc)) + venc
1331
1332 return buffer
1333
1334 try:
1335 await self.con.set_type_codec('hstore', encoder=hstore_encoder,
1336 decoder=hstore_decoder,
1337 format='binary')
1338
1339 st = await self.con.prepare('''
1340 SELECT $1::hstore AS result
1341 ''')
1342
1343 res = await st.fetchrow({'ham': 'spam'})

Callers

nothing calls this directly

Calls 6

set_type_codecMethod · 0.80
get_parametersMethod · 0.80
get_attributesMethod · 0.80
executeMethod · 0.45
prepareMethod · 0.45
fetchrowMethod · 0.45

Tested by

no test coverage detected