-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcreatetable.py
executable file
·166 lines (146 loc) · 5.64 KB
/
createtable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#!/usr/bin/python3
import argparse
import logging
import psycopg2
import config
import pg
from tabledesc import TableDesc
def postgres_type_raw(field):
sftype = field['type']
if sftype in (
'combobox', 'email', 'encryptedstring', 'id',
'phone', 'reference', 'string', 'textarea', 'url'):
return 'VARCHAR({})'.format(field['length'])
if sftype in ('picklist', 'multipicklist'):
return 'TEXT' # size is not reliable
if sftype == 'int':
return 'INTEGER'
if sftype == 'date':
return 'DATE'
if sftype == 'datetime':
return 'TIMESTAMP'
if sftype == 'boolean':
return 'BOOLEAN'
if sftype == 'currency':
return 'NUMERIC({}, {})'.format(field['precision'], field['scale'])
if sftype in ('double', 'percent'):
return 'DOUBLE PRECISION'
if sftype == 'anyType':
return 'TEXT'
return '"{}" NOT IMPLEMENTED '.format(sftype)
def postgres_const(value):
if isinstance(value, str):
return pg.escape_str(value)
if isinstance(value, bool):
return 'TRUE' if value else 'FALSE'
if isinstance(value, (int, float)):
return str(value)
return 'NOTIMPLEMENTED'
def postgres_coldef_from_sffield(field):
field_name = field['name']
field_type = field['type']
if field_type == 'address':
base_name = field_name
if base_name.endswith('Address'):
base_name = base_name[:-7] # remove suffix
return [
' {} {}'.format(pg.escape_name(base_name+'Street'),
'VARCHAR(255)'),
' {} {}'.format(pg.escape_name(base_name+'City'),
'VARCHAR(40)'),
' {} {}'.format(pg.escape_name(base_name+'State'),
'VARCHAR(80)'),
' {} {}'.format(pg.escape_name(base_name+'PostalCode'),
'VARCHAR(20)'),
' {} {}'.format(pg.escape_name(base_name+'Country'),
'VARCHAR(80)'),
' {} {}'.format(pg.escape_name(base_name+'Latitude'),
'DOUBLE PRECISION'),
' {} {}'.format(pg.escape_name(base_name+'Longitude'),
'DOUBLE PRECISION'),
]
pgtype = postgres_type_raw(field)
if field_name in ('Id', 'DurableId'):
# Id is ignored is DurableId exists (see bellow)
# So any can be used as a primary key
pgtype += ' PRIMARY KEY'
else:
if not field['nillable']:
pgtype += ' NOT NULL'
if field['defaultValue']:
pgtype += ' DEFAULT ' + postgres_const(field['defaultValue'])
if field['unique']:
pgtype += ' UNIQUE'
return [' {} {}'.format(pg.escape_name(field_name), pgtype)]
def get_pgsql_create(table_name, grant_to=None):
logger = logging.getLogger(__name__)
logger.debug('Analyzing %s', table_name)
tabledesc = TableDesc(table_name)
lines = []
sync_fields = tabledesc.get_sync_fields()
for field_name, field in sync_fields.items():
if field['calculated']:
logger.warning('Field %s should be calculated locally',
field_name)
if tabledesc.is_field_compound(field_name):
logger.warning('Field %s should be composed/aggregated locally',
field_name)
if field_name == 'Id' and 'DurableId' in sync_fields.keys():
continue # Ignore 'Id' if 'DurableId' exists
lines += postgres_coldef_from_sffield(field)
statements = [
'CREATE TABLE {} (\n{}\n);'.format(
pg.table_name(table_name),
',\n'.join(lines))
]
indexed_fields_names = tabledesc.get_indexed_sync_field_names()
for field_name, field in sync_fields.items():
if field_name in ('Id', 'DurableId'):
continue # primary key already indexed
if field_name not in indexed_fields_names:
continue
if field.get('IsIndexed'):
statements.append(
'CREATE INDEX {} ON {} ({});'.format(
pg.escape_name('{}_{}_idx'.format(
table_name, field_name)),
pg.table_name(table_name),
pg.escape_name(field_name)))
if grant_to is not None:
statements.append('GRANT SELECT ON {} TO {};'.format(
pg.table_name(table_name), grant_to))
return statements
if __name__ == '__main__':
def main():
parser = argparse.ArgumentParser(
description='create postgresql table')
parser.add_argument(
'--dry-run',
default=False, action='store_true',
help='only print the sql statement to stdout')
parser.add_argument(
'--grant-to',
default=config.GRANT_TO,
help='grant select to this table')
parser.add_argument(
'table',
help='table to create in postgresql')
args = parser.parse_args()
logging.basicConfig(
filename=config.LOGFILE,
format=config.LOGFORMAT.format('createtable '+args.table),
level=config.LOGLEVEL)
sql = get_pgsql_create(args.table, args.grant_to)
if args.dry_run:
for line in sql:
print(line)
else:
cursor = pg.cursor()
for line in sql:
try:
cursor.execute(line)
except (Exception, psycopg2.ProgrammingError):
logging.error('Error while executing %s', line)
raise
pg.commit()
main()