· 6 years ago · Oct 15, 2019, 01:42 AM
1import psycopg2
2
3
4def create_partition_table(connection, table_name, column_defs, partition_by):
5 """
6
7 :param psycopg2.connection connection:
8 :param str table_name:
9 :param list column_defs:
10 :param str partition_by:
11 :return:
12 """
13 cd = ','.join(' '.join(column_def) for column_def in column_defs)
14 with connection.cursor() as cursor:
15 cursor.execute('''
16 CREATE TABLE IF NOT EXISTS {} ({})
17 PARTITION BY HASH ({});
18 '''.format(table_name, cd, partition_by))
19
20
21def create_partition_hash(connection, table_name, modulus, remainder):
22 """
23
24 :param psycopg2.connection connection:
25 :param str table_name:
26 :param int modulus:
27 :param int remainder:
28 :return:
29 """
30 with connection.cursor() as cursor:
31 cursor.execute('''
32 CREATE TABLE IF NOT EXISTS {}_{:02d}
33 PARTITION OF {} FOR VALUES
34 WITH (MODULUS {}, REMAINDER {});
35 '''.format(table_name, remainder, table_name, modulus, remainder))