-
Notifications
You must be signed in to change notification settings - Fork 388
Expand file tree
/
Copy pathpg_sql_codes.py
More file actions
executable file
·296 lines (251 loc) · 8.76 KB
/
pg_sql_codes.py
File metadata and controls
executable file
·296 lines (251 loc) · 8.76 KB
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import argparse
import collections
import logging
import re
import requests
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
ERR_CODES_PAGE = 'https://www.postgresql.org/docs/12/static/errcodes-appendix.html'
HTML_REGEX = r'(?:class=\"bold\"[\S]*>([^<]+))' '|' r'(?:class=\"literal\">([^<]+).*?class=.*?\"symbol\">([^<]+))'
DEF_OFFSET = ' '
LIT_OFFSET = ' '
CLASSES_ENUM = """
// PostgreSQL error classes
/// Docs: https://www.postgresql.org/docs/12/static/errcodes-appendix.html
/// Enumeration was generated by userver/scripts/postgres/pg_sql_codes.py
enum class SqlStateClass : std::int64_t {"""
ERRORS_ENUM = """
/// PostgreSQL error codes
/// Docs: https://www.postgresql.org/docs/12/static/errcodes-appendix.html
/// Enumeration was generated by userver/scripts/postgres/pg_sql_codes.py
enum class SqlState : std::int64_t {
kUnknownState, ///!< Unknown state, not in PostgreSQL docs"""
ERROR_LITERALS = """
// This goes to the cpp file in an anonymous namespace
// Data was generated by userver/scripts/postgres/pg_sql_codes.py
const std::unordered_map<std::string_view, SqlState> kCodeStrToState{"""
DISAMBIGUATIONS = {
'kWarning': 'Warn',
'kExternalRoutineException': 'Ex',
'kExternalRoutineInvocationException': 'Ex',
}
def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
@static_vars(value=0)
def class_value(prev_count):
if class_value.value == 0:
class_value.value = 1
else:
val = class_value.value * 2
while class_value.value + prev_count > val:
val *= 2
class_value.value = val
return class_value.value
def gen_enum_value(snake_str):
components = snake_str.split('_')
return 'k' + ''.join(x.title() for x in components)
def print_with_offset(stream, offset, *args):
lines = '\n'.join(args).split('\n')
print(offset + ('\n' + offset).join(lines), file=stream)
class ErrorClass:
error_cnt_by_symbol: dict = collections.Counter()
class ErrorCode:
def __init__(self, klass, symbol, literal):
self.klass = klass
self.symbol = symbol
self.literal = literal
def disambiguated_symbol(self):
disambiguation = ''
if ErrorClass.error_cnt_by_symbol[self.symbol] > 1:
disambiguation = DISAMBIGUATIONS.get(self.klass, '')
return self.symbol + disambiguation
def print_decl(self, stream):
if self.symbol == self.klass:
print_with_offset(
stream,
DEF_OFFSET,
'{symbol} = static_cast<std::int64_t>(SqlStateClass::{symbol}), //!< {literal}'.format(
symbol=self.disambiguated_symbol(),
literal=self.literal,
),
)
else:
print_with_offset(
stream,
DEF_OFFSET,
'{symbol}, //!< {literal}'.format(
symbol=self.disambiguated_symbol(),
literal=self.literal,
),
)
def print_literal(self, stream):
print_with_offset(
stream,
LIT_OFFSET,
'{{"{literal}", SqlState::{symbol}}},'.format(
literal=self.literal,
symbol=self.disambiguated_symbol(),
),
)
def print_class_test(self, stream):
print_with_offset(
stream,
LIT_OFFSET,
'EXPECT_EQ(pg::SqlStateClass::{klass}, pg::GetSqlStateClass(pg::SqlState::{symbol}));'.format(
klass=self.klass,
symbol=self.disambiguated_symbol(),
),
)
def print_parse_test(self, stream):
print_with_offset(
stream,
LIT_OFFSET,
'EXPECT_EQ(pg::SqlState::{symbol}, pg::SqlStateFromString("{literal}"));'.format(
symbol=self.disambiguated_symbol(),
literal=self.literal,
),
)
def __init__(self, desc, prev_count):
self.desc = desc
self.value = class_value(prev_count)
self.errors = []
self.name = None
def add_error(self, symbol, literal):
if self.name is None:
self.name = symbol
self.errors.append(ErrorClass.ErrorCode(self.name, symbol, literal))
ErrorClass.error_cnt_by_symbol[symbol] += 1
def print_class(self, stream):
print_with_offset(
stream,
DEF_OFFSET,
'{name} = 0x{value:02x},'.format(name=self.name, value=self.value),
)
def print_symbols(self, stream):
print_with_offset(
stream,
DEF_OFFSET,
'//@{',
'/** @name {desc} */'.format(desc=self.desc),
)
for err_class in self.errors:
err_class.print_decl(stream)
print_with_offset(stream, DEF_OFFSET, '//@}')
def print_literals(self, stream):
print_with_offset(
stream,
LIT_OFFSET,
'//@{',
'/** @name {desc} */'.format(desc=self.desc),
)
for err_class in self.errors:
err_class.print_literal(stream)
print_with_offset(stream, LIT_OFFSET, '//@}')
def print_test(self, stream):
print_with_offset(
stream,
LIT_OFFSET,
'// {desc}'.format(desc=self.desc),
)
for err_class in self.errors:
err_class.print_parse_test(stream)
err_class.print_class_test(stream)
def main():
parser = argparse.ArgumentParser(description='SqlCode enum generator')
parser.add_argument(
'-o',
'--header',
help='Output header',
metavar='out.hpp',
)
parser.add_argument(
'-s',
'--source',
help='Output source',
metavar='out.cpp',
)
parser.add_argument(
'-t',
'--test',
help='Generate test',
metavar='test.cpp',
)
args = parser.parse_args()
logger.info('Retrieving documentation')
page = requests.get(ERR_CODES_PAGE)
logger.info('Cleaning html')
page_text = re.sub(
r'.*?<table[^>]+summary=\"PostgreSQL Error Codes\"[^>]*>',
'',
page.text,
flags=re.MULTILINE | re.DOTALL,
)
page_text = re.sub(
r'</table>.*',
'',
page_text,
flags=re.MULTILINE | re.DOTALL,
)
logger.info('Parsing html')
matches = re.finditer(HTML_REGEX, page_text, re.MULTILINE | re.DOTALL)
err_count = 0
current_class = None
error_classes = []
logger.info('Collecting definitions')
for match in matches:
if match.group(1):
class_desc = match.group(1).replace('\n', ' ')
current_class = ErrorClass(class_desc, err_count)
error_classes.append(current_class)
err_count = 0
elif match.group(2):
literal = match.group(2)
symbol = gen_enum_value(match.group(3))
current_class.add_error(symbol, literal)
err_count += 1
logger.info('Printing sources')
if args.header:
with open(args.header, 'w') as header:
print(CLASSES_ENUM, file=header)
for err_class in error_classes:
err_class.print_class(header)
print('};\n\n', file=header)
print(ERRORS_ENUM, file=header)
for err_class in error_classes:
err_class.print_symbols(header)
print('};\n', file=header)
if args.source:
with open(args.source, 'w') as source:
print(ERROR_LITERALS, file=source)
for err_class in error_classes:
err_class.print_literals(source)
print('};\n', file=source)
if args.test:
with open(args.test, 'w') as test:
print(
'// Test was generated by userver/scripts/postgres/pg_sql_codes.py',
'#include <userver/utest/utest.hpp>',
'',
'#include <userver/storages/postgres/exceptions.hpp>',
'',
'namespace pg = storages::postgres;',
'',
sep='\n',
file=test,
)
for err_class in error_classes:
print(
'TEST(PostgreError, SqlState' + err_class.name[1:] + ') {',
file=test,
)
err_class.print_test(test)
print('}\n', file=test)
logger.info('Done')
if __name__ == '__main__':
main()