-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathgdbpg.py
386 lines (263 loc) · 9.6 KB
/
gdbpg.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import gdb
def format_plan_tree(tree, indent=0):
'formats a plan (sub)tree, with custom indentation'
# if the pointer is NULL, just return (null) string
if (str(tree) == '0x0'):
return '-> (NULL)'
# format all the important fields (similarly to EXPLAIN)
retval = '''
-> %(type)s (cost=%(startup).3f...%(total).3f rows=%(rows)s width=%(width)s)
\ttarget list:
%(target)s
\t%(left)s
\t%(right)s''' % {
'type' : format_type(tree['type']), # type of the Node
'startup' : float(tree['startup_cost']), # startup cost
'total' : float(tree['total_cost']), # total cost
'rows' : str(tree['plan_rows']), # number of rows
'width' : str(tree['plan_width']), # tuple width (no header)
# format target list
'target' : format_node_list(tree['targetlist'], 2, True),
# left subtree
'left' : format_plan_tree(tree['lefttree'], 0),
# right subtree
'right' : format_plan_tree(tree['righttree'], 0)
}
return add_indent(retval, indent+1)
def format_type(t, indent=0):
'strip the leading T_ from the node type tag'
t = str(t)
if t.startswith('T_'):
t = t[2:]
return add_indent(t, indent)
def format_int_list(lst, indent=0):
'format list containing integer values directly (not warapped in Node)'
# handle NULL pointer (for List we return NIL
if (str(lst) == '0x0'):
return '(NIL)'
# we'll collect the formatted items into a Python list
tlist = []
item = lst['head']
# walk the list until we reach the last item
while str(item) != '0x0':
# get item from the list and just grab 'int_value as int'
tlist.append(int(item['data']['int_value']))
# next item
item = item['next']
return add_indent(str(tlist), indent)
def format_oid_list(lst, indent=0):
'format list containing Oid values directly (not warapped in Node)'
# handle NULL pointer (for List we return NIL)
if (str(lst) == '0x0'):
return '(NIL)'
# we'll collect the formatted items into a Python list
tlist = []
item = lst['head']
# walk the list until we reach the last item
while str(item) != '0x0':
# get item from the list and just grab 'oid_value as int'
tlist.append(int(item['data']['oid_value']))
# next item
item = item['next']
return add_indent(str(tlist), indent)
def format_node_list(lst, indent=0, newline=False):
'format list containing Node values'
# handle NULL pointer (for List we return NIL)
if (str(lst) == '0x0'):
return '(NIL)'
# we'll collect the formatted items into a Python list
tlist = []
item = lst['head']
# walk the list until we reach the last item
while str(item) != '0x0':
# we assume the list contains Node instances, so grab a reference
# and cast it to (Node*)
node = cast(item['data']['ptr_value'], 'Node')
# append the formatted Node to the result list
tlist.append(format_node(node))
# next item
item = item['next']
retval = str(tlist)
if newline:
retval = "\n".join([str(t) for t in tlist])
return add_indent(retval, indent)
def format_char(value):
'''convert the 'value' into a single-character string (ugly, maybe there's a better way'''
str_val = str(value.cast(gdb.lookup_type('char')))
# remove the quotes (start/end)
return str_val.split(' ')[1][1:-1]
def format_relids(relids):
return '(not implemented)'
def format_node_array(array, start_idx, length, indent=0):
items = []
for i in range(start_idx,start_idx + length - 1):
items.append(str(i) + " => " + format_node(array[i]))
return add_indent(("\n".join(items)), indent)
def format_node(node, indent=0):
'format a single Node instance (only selected Node types supported)'
if str(node) == '0x0':
return add_indent('(NULL)', indent)
retval = '';
type_str = str(node['type'])
if is_a(node, 'TargetEntry'):
# we assume the list contains Node instances (probably safe for Plan fields)
node = cast(node, 'TargetEntry')
name_ptr = node['resname'].cast(gdb.lookup_type('char').pointer())
name = "(NULL)"
if str(name_ptr) != '0x0':
name = '"' + (name_ptr.string()) + '"'
retval = 'TargetEntry (resno=%(resno)s resname=%(name)s origtbl=%(tbl)s origcol=%(col)s junk=%(junk)s expr=[%(expr)s])' % {
'resno' : node['resno'],
'name' : name,
'tbl' : node['resorigtbl'],
'col' : node['resorigcol'],
'junk' : (int(node['resjunk']) == 1),
'expr' : format_node(node['expr'])
}
elif is_a(node, 'Var'):
# we assume the list contains Node instances (probably safe for Plan fields)
node = cast(node, 'Var')
retval = 'Var (varno=%(no)s varattno=%(attno)s levelsup=%(levelsup)s)' % {
'no' : node['varno'],
'attno' : node['varattno'],
'levelsup' : node['varlevelsup']
}
elif is_a(node, 'RangeTblRef'):
node = cast(node, 'RangeTblRef')
retval = 'RangeTblRef (rtindex=%d)' % (int(node['rtindex']),)
elif is_a(node, 'RelOptInfo'):
node = cast(node, 'RelOptInfo')
retval = 'RelOptInfo (kind=%(kind)s relids=%(relids)s rtekind=%(rtekind)s relid=%(relid)s rows=%(rows)s width=%(width)s fk=%(fk)s)' % {
'kind' : node['reloptkind'],
'rows' : node['rows'],
'width' : node['width'],
'relid' : node['relid'],
'relids' : format_relids(node['relids']),
'rtekind' : node['rtekind'],
'fk' : (int(node['has_fk_join']) == 1)
}
elif is_a(node, 'RangeTblEntry'):
node = cast(node, 'RangeTblEntry')
retval = 'RangeTblEntry (kind=%(rtekind)s relid=%(relid)s relkind=%(relkind)s)' % {
'relid' : node['relid'],
'rtekind' : node['rtekind'],
'relkind' : format_char(node['relkind'])
}
elif is_a(node, 'PlannerInfo'):
retval = format_planner_info(node)
elif is_a(node, 'PlannedStmt'):
retval = format_planned_stmt(node)
elif is_a(node, 'List'):
retval = format_node_list(node, 0, True)
elif is_a(node, 'Plan'):
retval = format_plan_tree(node)
elif is_a(node, 'RestrictInfo'):
node = cast(node, 'RestrictInfo')
retval = '''RestrictInfo (pushed_down=%(push_down)s can_join=%(can_join)s delayed=%(delayed)s)
%(clause)s
%(orclause)s''' % {
'clause' : format_node(node['clause'], 1),
'orclause' : format_node(node['orclause'], 1),
'push_down' : (int(node['is_pushed_down']) == 1),
'can_join' : (int(node['can_join']) == 1),
'delayed' : (int(node['outerjoin_delayed']) == 1)
}
elif is_a(node, 'OpExpr'):
node = cast(node, 'OpExpr')
retval = format_op_expr(node)
elif is_a(node, 'BoolExpr'):
node = cast(node, 'BoolExpr')
print node
retval = format_bool_expr(node)
else:
# default - just print the type name
retval = format_type(type_str)
return add_indent(str(retval), indent)
def format_planner_info(info, indent=0):
# Query *parse; /* the Query being planned */
# *glob; /* global info for current planner run */
# Index query_level; /* 1 at the outermost Query */
# struct PlannerInfo *parent_root; /* NULL at outermost Query */
# List *plan_params; /* list of PlannerParamItems, see below */
retval = '''rel:
%(rel)s
rte:
%(rte)s
''' % {'rel' : format_node_array(info['simple_rel_array'], 1, int(info['simple_rel_array_size'])),
'rte' : format_node_array(info['simple_rte_array'], 1, int(info['simple_rel_array_size']))}
return add_indent(retval, indent)
def format_planned_stmt(plan, indent=0):
retval = ''' type: %(type)s
query ID: %(qid)s
param exec: %(nparam)s
returning: %(has_returning)s
modifying CTE: %(has_modify_cte)s
can set tag: %(can_set_tag)s
transient: %(transient)s
row security: %(row_security)s
plan tree: %(tree)s
range table:
%(rtable)s
relation OIDs: %(relation_oids)s
result rels: %(result_rels)s
utility stmt: %(util_stmt)s
subplans: %(subplans)s''' % {
'type' : plan['commandType'],
'qid' : plan['queryId'],
'nparam' : plan['nParamExec'],
'has_returning' : (int(plan['hasReturning']) == 1),
'has_modify_cte' : (int(plan['hasModifyingCTE']) == 1),
'can_set_tag' : (int(plan['canSetTag']) == 1),
'transient' : (int(plan['transientPlan']) == 1),
'row_security' : (int(plan['hasRowSecurity']) == 1),
'tree' : format_plan_tree(plan['planTree']),
'rtable' : format_node_list(plan['rtable'], 1, True),
'relation_oids' : format_oid_list(plan['relationOids']),
'result_rels' : format_int_list(plan['resultRelations']),
'util_stmt' : format_node(plan['utilityStmt']),
'subplans' : format_node_list(plan['subplans'], 1, True)
}
return add_indent(retval, indent)
def format_op_expr(node, indent=0):
return """OpExpr [opno=%(opno)s]
%(clauses)s""" % { 'opno' : node['opno'],
'clauses' : format_node_list(node['args'], 1, True)}
def format_bool_expr(node, indent=0):
return """BoolExpr [op=%(op)s]
%(clauses)s""" % { 'op' : node['boolop'],
'clauses' : format_node_list(node['args'], 1, True)}
def is_a(n, t):
'''checks that the node has type 't' (just like IsA() macro)'''
if not is_node(n):
return False
return (str(n['type']) == ('T_' + t))
def is_node(l):
'''return True if the value looks like a Node (has 'type' field)'''
try:
x = l['type']
return True
except:
return False
def cast(node, type_name):
'''wrap the gdb cast to proper node type'''
# lookup the type with name 'type_name' and cast the node to it
t = gdb.lookup_type(type_name)
return node.cast(t.pointer())
def add_indent(val, indent):
return "\n".join([(("\t"*indent) + l) for l in val.split("\n")])
class PgPrintCommand(gdb.Command):
"print PostgreSQL structures"
def __init__ (self):
super (PgPrintCommand, self).__init__ ("pgprint",
gdb.COMMAND_SUPPORT,
gdb.COMPLETE_NONE, False)
def invoke (self, arg, from_tty):
arg_list = gdb.string_to_argv(arg)
if len(arg_list) != 1:
print "usage: pgprint var"
return
l = gdb.parse_and_eval(arg_list[0])
if not is_node(l):
print "not a node type"
print format_node(l)
PgPrintCommand()