-
Notifications
You must be signed in to change notification settings - Fork 18
/
xsd2pgsql.py
executable file
·279 lines (251 loc) · 8.36 KB
/
xsd2pgsql.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#! /usr/bin/python
""" xsd2pgsql.py
========================================
Create a database based on an XSD schema.
Usage
========================================
<file> XSD file to base the Postgres Schema on
-f --fail Fail on finding a bad XS type
-a --as-is Don't normalize element names.
-d --database DB name
-u --user DB Username
-p --password DB Password
-h --host DB host
-P --port DB port
"""
""" You can set default DB connection settings here if you'd like
"""
DB = {
'user': None,
'pass': None,
'port': 5432,
'host': 'localhost',
}
""" Some configuration items """
MAX_RECURSE_LEVEL = 10
""" XSD to Postgres data type translation dictionary.
"""
class SDict(dict):
def __getitem__(self, item):
return dict.__getitem__(self, item) % self
def get(self, item):
try:
return dict.__getitem__(self, item) % self
except KeyError:
return None
DEFX2P = SDict({
'string': 'varchar',
'boolean': 'boolean',
'decimal': 'numeric',
'float': 'real',
'double': 'double precision',
'duration': 'interval',
'dateTime': 'timestamp',
'time': 'time',
'date': 'date',
'gYearMonth': 'timestamp',
'gYear': 'timestamp',
'gMonthDay': 'timestamp',
'gDay': 'timestamp',
'gMonth': 'timestamp',
'hexBinary': 'bytea',
'base64Binary': 'bytea',
'anyURI': 'varchar',
'QName': None,
'NOTATION': None,
'normalizedString': '%(string)s',
'token': '%(string)s',
'language': '%(string)s',
'NMTOKEN': None,
'NMTOKENS': None,
'Name': '%(string)s',
'NCName': '%(string)s',
'ID': None,
'IDREF': None,
'IDREFS': None,
'ENTITY': None,
'ENTITIES': None,
'integer': 'integer',
'nonPositiveInteger': '%(integer)s',
'negativeInteger': '%(integer)s',
'long': '%(integer)s',
'int': '%(integer)s',
'short': '%(integer)s',
'byte': '%(integer)s',
'nonNegativeInteger': '%(integer)s',
'unsignedLong': '%(integer)s',
'unsignedInt': '%(integer)s',
'unsignedShort': '%(integer)s',
'unsignedByte': '%(integer)s',
'positiveInteger': '%(integer)s',
})
USER_TYPES = {}
XMLS = "{http://www.w3.org/2001/XMLSchema}"
XMLS_PREFIX = "xs:"
""" Output """
SQL = ''
""" Helpers
"""
class InvalidXMLType(Exception): pass
class MaxRecursion(Exception): pass
""" Normalize strings like column names for PG """
def pg_normalize(string):
if not string: string = ''
string = string.replace('-', '_')
string = string.replace('.', '_')
string = string.replace(' ', '_')
string = string.lower()
return string
""" Look for elements recursively
returns tuple (children bool, sql string)
"""
def look4element(ns, el, parent=None, recurse_level=0, fail=False, normalize=True):
if recurse_level > MAX_RECURSE_LEVEL: raise MaxRecursion()
cols = ''
children = False
sql = ''
for x in el.findall(ns + 'element'):
children = True
rez = look4element(ns, x, x.get('name') or parent, recurse_level + 1, fail=fail)
sql += rez[1] + '\n'
if not rez[0]:
#print 'parent(%s) <%s name=%s type=%s> %s' % (parent, x.tag, x.get('name'), x.get('type'), x.text)
thisType = x.get('type') or x.get('ref') or 'string'
k = thisType.replace(XMLS_PREFIX, '')
pgType = DEFX2P.get(k) or USER_TYPES.get(k) or None
if not pgType and fail:
raise InvalidXMLType("%s is an invalid XSD type." % (XMLS_PREFIX + thisType))
elif pgType:
colName = x.get('name') or x.get('ref')
if normalize:
colName = pg_normalize(colName)
if not cols:
cols = "%s %s" % (colName, pgType)
else:
cols += ", %s %s" % (colName, pgType)
if cols:
sql += """CREATE TABLE %s (%s);""" % (parent, cols)
for x in el.findall(ns + 'complexType'):
children = True
rez = look4element(ns, x, x.get('name') or parent, recurse_level + 1, fail=fail)
sql += rez[1] + '\n'
for x in el.findall(ns + 'sequence'):
children = True
rez = look4element(ns, x, x.get('name') or parent, recurse_level + 1, fail=fail)
sql += rez[1] + '\n'
return (children, sql)
""" Take care of any types that were defined in the XSD """
def buildTypes(ns, root_element):
for el in root_element.findall(ns + 'element'):
if el.get('name') and el.get('type'):
USER_TYPES[pg_normalize(el.get('name'))] = DEFX2P.get(el.get('type').replace(XMLS_PREFIX, ''))
for el in root_element.findall(ns + 'simpleType'):
restr = el.find(ns + 'restriction')
USER_TYPES[pg_normalize(el.get('name'))] = restr.get('base').replace(XMLS_PREFIX, '')
""" Do it
"""
if __name__ == '__main__':
""" Imports
"""
import argparse, psycopg2
import pyxb.utils.domutils as domutils
from lxml import etree
""" Handle options
"""
parser = argparse.ArgumentParser(description='Create a database based on an XSD schema. If no database name is specified, SQL is output to stdout.')
parser.add_argument(
'xsd',
metavar='FILE',
type=file,
nargs='+',
help='XSD file to base the Postgres Schema on'
)
parser.add_argument(
'-f', '--fail',
dest = 'failOnBadType',
action = 'store_true',
default = False,
help = 'Fail on finding a bad XS type'
)
parser.add_argument(
'-a', '--as-is',
dest = 'as_is',
action = 'store_true',
default = False,
help = "Don't normalize element names"
)
parser.add_argument(
'-d', '--database',
metavar='NAME',
dest='db_name',
type=str,
nargs='?',
help='DB Name'
)
parser.add_argument(
'-u', '--user',
metavar='USERNAME',
dest='db_username',
type=str,
nargs='?',
help='DB Username'
)
parser.add_argument(
'-p', '--password',
metavar = 'PASSWORD',
dest='db_password',
type = str,
nargs = '?',
help = 'DB Password'
)
parser.add_argument(
'-n', '--host',
metavar = 'HOSTNAME',
dest='db_host',
type = str,
nargs = '?',
default = 'localhost',
help = 'DB Host'
)
parser.add_argument(
'-P', '--port',
metavar = 'PORT',
dest='db_port',
type = int,
nargs = '?',
default = 5432,
help = 'DB Port (Default: 5432)'
)
args = parser.parse_args()
""" MEAT
"""
if not args.xsd:
sys.exit('XSD file not specified.')
else:
for f in args.xsd:
#xsdFile = open(f, 'r')
""" Parse the XSD file
"""
xsd = etree.parse(f)
# glean out defined types
buildTypes(XMLS, xsd)
# parse structure
if args.as_is:
norm = False
else:
norm = True
result = look4element(XMLS, xsd, pg_normalize(f.name.split('.')[0]), fail=args.failOnBadType, normalize=norm)
if result[1] and not args.db_name:
print result[1].replace('\n\n', '')
elif result[1]:
dsn = "dbname=%s host=%s port=%s" % (args.db_name, args.db_host, args.db_port)
if args.db_username: dsn += "user=%s" % args.db_username
if args.db_username: dsn += "user=%s" % args.db_password
conn = psycopg2.connect(dsn)
cur = conn.cursor()
cur.execute(result[1])
conn.commit()
cur.close()
conn.close()
else:
raise Exception("This shouldn't happen.")