Skip to content

Commit 9a173ad

Browse files
committed
Specification for postgres uuid functions.
1 parent 2e98b79 commit 9a173ad

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

postpy/uuids.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""Configure psycopg2 to support UUID conversion."""
2+
3+
import psycopg2.extras
4+
5+
from postpy.admin import install_extensions
6+
7+
8+
CRYPTO_EXTENSION = 'pgcrypto'
9+
UUID_OSSP_EXTENSION = 'uuid-ossp'
10+
11+
12+
def register_client():
13+
"""Have psycopg2 marshall UUID objects automatically."""
14+
15+
psycopg2.extras.register_uuid()
16+
17+
18+
def register_crypto():
19+
"""Support for UUID's on server side.
20+
21+
Lighter dependency than uuid-ossp supporting
22+
random_uuid_function for UUID generation.
23+
"""
24+
25+
install_extensions([CRYPTO_EXTENSION])
26+
27+
28+
def register_uuid():
29+
"""Support for UUID's on server side.
30+
31+
Notes
32+
-----
33+
uuid-ossp can be problematic on some platforms. See:
34+
https://www.postgresql.org/docs/current/static/uuid-ossp.html
35+
"""
36+
37+
install_extensions([UUID_OSSP_EXTENSION])
38+
39+
40+
def random_uuid_function(schema=None):
41+
"""Cryptographic random UUID function.
42+
43+
Generates random database side UUID's.
44+
45+
Notes
46+
-----
47+
Lighter dependency than uuid-ossp, but higher
48+
fragmentation on disk if used as auto-generating primary key UUID.
49+
"""
50+
51+
return '{}gen_random_uuid()'.format(_format_schema(schema))
52+
53+
54+
def uuid_sequence_function(schema=None):
55+
"""Sequential UUID generation.
56+
57+
Sequential UUID creation on database side offering
58+
less table fragmentation issues when used as UUID primary key.
59+
"""
60+
61+
return '{}uuid_generate_v1mc()'.format(_format_schema(schema))
62+
63+
64+
def _format_schema(schema):
65+
return '{}.'.format(schema) if schema else ''

tests/test_uuids.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import unittest
2+
3+
from postpy import uuids
4+
5+
6+
class TestUUIDFunctions(unittest.TestCase):
7+
8+
def test_function_formatters(self):
9+
10+
expected = 'gen_random_uuid()'
11+
result = uuids.random_uuid_function()
12+
13+
self.assertEqual(expected, result)
14+
15+
expected = 'my_schema.uuid_generate_v1mc()'
16+
result = uuids.uuid_sequence_function('my_schema')
17+
18+
self.assertEqual(expected, result)

0 commit comments

Comments
 (0)