|
| 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 '' |
0 commit comments