Mercurial > sqlpython
annotate sqlpython/sqlpyPlus.py @ 310:c897add05eb1
fixed grep bug
author | catherine@Elli.myhome.westell.com |
---|---|
date | Thu, 26 Mar 2009 10:21:31 -0400 |
parents | 0d16630d8e04 |
children | 38ac0fbb2b63 |
rev | line source |
---|---|
189 | 1 """sqlpyPlus - extra features (inspired by Oracle SQL*Plus) for Luca Canali's sqlpython.py |
2 | |
3 Features include: | |
4 - SQL*Plus-style bind variables | |
5 - `set autobind on` stores single-line result sets in bind variables automatically | |
6 - SQL buffer with list, run, ed, get, etc.; unlike SQL*Plus, buffer stores session's full history | |
7 - @script.sql loads and runs (like SQL*Plus) | |
8 - ! runs operating-system command | |
9 - show and set to control sqlpython parameters | |
10 - SQL*Plus-style describe, spool | |
11 - write sends query result directly to file | |
12 - comments shows table and column comments | |
13 - compare ... to ... graphically compares results of two queries | |
14 - commands are case-insensitive | |
15 - context-sensitive tab-completion for table names, column names, etc. | |
16 | |
17 Use 'help' within sqlpython for details. | |
18 | |
19 Set bind variables the hard (SQL*Plus) way | |
20 exec :b = 3 | |
21 or with a python-like shorthand | |
22 :b = 3 | |
23 | |
24 - catherinedevlin.blogspot.com May 31, 2006 | |
25 """ | |
220 | 26 import sys, os, re, sqlpython, cx_Oracle, pyparsing, re, completion, datetime, pickle, binascii, subprocess |
189 | 27 from cmd2 import Cmd, make_option, options, Statekeeper, Cmd2TestCase |
28 from output_templates import output_templates | |
29 from plothandler import Plot | |
30 try: | |
31 import pylab | |
198
b2d8bf5f89db
merged with changes from work
catherine@Elli.myhome.westell.com
parents:
196
diff
changeset
|
32 except (RuntimeError, ImportError): |
189 | 33 pass |
34 | |
35 descQueries = { | |
286 | 36 'TABLE': { |
37 True: # long description | |
38 (""" | |
39 SELECT atc.column_id "#", | |
40 atc.column_name, | |
41 CASE atc.nullable WHEN 'Y' THEN 'NULL' ELSE 'NOT NULL' END "Null?", | |
42 atc.data_type || | |
43 CASE atc.data_type WHEN 'DATE' THEN '' | |
44 ELSE '(' || | |
45 CASE atc.data_type WHEN 'NUMBER' THEN TO_CHAR(atc.data_precision) || | |
46 CASE atc.data_scale WHEN 0 THEN '' | |
47 ELSE ',' || TO_CHAR(atc.data_scale) END | |
48 ELSE TO_CHAR(atc.data_length) END | |
49 END || | |
50 CASE atc.data_type WHEN 'DATE' THEN '' ELSE ')' END | |
51 data_type, | |
52 acc.comments | |
53 FROM all_tab_columns atc | |
54 JOIN all_col_comments acc ON (acc.owner = atc.owner AND acc.table_name = atc.table_name AND acc.column_name = atc.column_name) | |
55 WHERE atc.table_name = :object_name | |
56 AND atc.owner = :owner | |
57 ORDER BY atc.column_id;""",), | |
58 None: # short description | |
59 (""" | |
193 | 60 SELECT atc.column_name, |
189 | 61 CASE atc.nullable WHEN 'Y' THEN 'NULL' ELSE 'NOT NULL' END "Null?", |
62 atc.data_type || | |
63 CASE atc.data_type WHEN 'DATE' THEN '' | |
64 ELSE '(' || | |
65 CASE atc.data_type WHEN 'NUMBER' THEN TO_CHAR(atc.data_precision) || | |
66 CASE atc.data_scale WHEN 0 THEN '' | |
67 ELSE ',' || TO_CHAR(atc.data_scale) END | |
68 ELSE TO_CHAR(atc.data_length) END | |
69 END || | |
70 CASE atc.data_type WHEN 'DATE' THEN '' ELSE ')' END | |
71 data_type | |
72 FROM all_tab_columns atc | |
73 WHERE atc.table_name = :object_name | |
74 AND atc.owner = :owner | |
286 | 75 ORDER BY atc.column_id;""",) |
76 } | |
77 , | |
78 | |
189 | 79 'PROCEDURE': (""" |
193 | 80 SELECT NVL(argument_name, 'Return Value') argument_name, |
189 | 81 data_type, |
82 in_out, | |
83 default_value | |
84 FROM all_arguments | |
85 WHERE object_name = :object_name | |
86 AND owner = :owner | |
87 AND package_name IS NULL | |
193 | 88 ORDER BY sequence;""",), |
189 | 89 'PackageObjects':(""" |
90 SELECT DISTINCT object_name | |
91 FROM all_arguments | |
92 WHERE package_name = :package_name | |
93 AND owner = :owner""",), | |
94 'PackageObjArgs':(""" | |
193 | 95 SELECT object_name, |
189 | 96 argument_name, |
97 data_type, | |
98 in_out, | |
99 default_value | |
100 FROM all_arguments | |
101 WHERE package_name = :package_name | |
102 AND object_name = :object_name | |
103 AND owner = :owner | |
104 AND argument_name IS NOT NULL | |
193 | 105 ORDER BY sequence;""",), |
189 | 106 'TRIGGER':(""" |
193 | 107 SELECT description |
189 | 108 FROM all_triggers |
109 WHERE owner = :owner | |
193 | 110 AND trigger_name = :object_name; |
189 | 111 """, |
112 """ | |
193 | 113 SELECT table_owner, |
189 | 114 base_object_type, |
115 table_name, | |
116 column_name, | |
117 when_clause, | |
118 status, | |
119 action_type, | |
120 crossedition | |
121 FROM all_triggers | |
122 WHERE owner = :owner | |
123 AND trigger_name = :object_name | |
124 \\t | |
125 """, | |
126 ), | |
127 'INDEX':(""" | |
193 | 128 SELECT index_type, |
189 | 129 table_owner, |
130 table_name, | |
131 table_type, | |
132 uniqueness, | |
133 compression, | |
134 partitioned, | |
135 temporary, | |
136 generated, | |
137 secondary, | |
138 dropped, | |
139 visibility | |
140 FROM all_indexes | |
141 WHERE owner = :owner | |
142 AND index_name = :object_name | |
143 \\t | |
144 """,) | |
145 } | |
146 descQueries['VIEW'] = descQueries['TABLE'] | |
147 descQueries['FUNCTION'] = descQueries['PROCEDURE'] | |
148 | |
149 queries = { | |
150 'resolve': """ | |
151 SELECT object_type, object_name, owner FROM ( | |
152 SELECT object_type, object_name, user owner, 1 priority | |
153 FROM user_objects | |
154 WHERE object_name = :objName | |
155 UNION ALL | |
156 SELECT ao.object_type, ao.object_name, ao.owner, 2 priority | |
157 FROM all_objects ao | |
158 JOIN user_synonyms us ON (us.table_owner = ao.owner AND us.table_name = ao.object_name) | |
159 WHERE us.synonym_name = :objName | |
160 AND ao.object_type != 'SYNONYM' | |
161 UNION ALL | |
162 SELECT ao.object_type, ao.object_name, ao.owner, 3 priority | |
163 FROM all_objects ao | |
164 JOIN all_synonyms asyn ON (asyn.table_owner = ao.owner AND asyn.table_name = ao.object_name) | |
165 WHERE asyn.synonym_name = :objName | |
166 AND ao.object_type != 'SYNONYM' | |
167 AND asyn.owner = 'PUBLIC' | |
168 UNION ALL | |
169 SELECT 'DIRECTORY' object_type, dir.directory_name, dir.owner, 6 priority | |
170 FROM all_directories dir | |
171 WHERE dir.directory_name = :objName | |
172 UNION ALL | |
173 SELECT 'DATABASE LINK' object_type, db_link, owner, 7 priority | |
174 FROM all_db_links dbl | |
175 WHERE dbl.db_link = :objName | |
176 ) ORDER BY priority ASC, | |
177 length(object_type) ASC, | |
178 object_type DESC""", # preference: PACKAGE before PACKAGE BODY, TABLE before INDEX | |
179 'tabComments': """ | |
180 SELECT comments | |
181 FROM all_tab_comments | |
182 WHERE owner = :owner | |
183 AND table_name = :table_name""", | |
184 'colComments': """ | |
193 | 185 SELECT |
189 | 186 atc.column_name, |
187 acc.comments | |
188 FROM all_tab_columns atc | |
189 JOIN all_col_comments acc ON (atc.owner = acc.owner and atc.table_name = acc.table_name and atc.column_name = acc.column_name) | |
190 WHERE atc.table_name = :object_name | |
191 AND atc.owner = :owner | |
193 | 192 ORDER BY atc.column_id;""", |
189 | 193 'oneColComments': """ |
193 | 194 SELECTatc.column_name, |
189 | 195 acc.comments |
196 FROM all_tab_columns atc | |
197 JOIN all_col_comments acc ON (atc.owner = acc.owner and atc.table_name = acc.table_name and atc.column_name = acc.column_name) | |
198 WHERE atc.table_name = :object_name | |
199 AND atc.owner = :owner | |
200 AND acc.column_name = :column_name | |
193 | 201 ORDER BY atc.column_id;""", |
189 | 202 #thanks to Senora.pm for "refs" |
203 'refs': """ | |
204 NULL referenced_by, | |
205 c2.table_name references, | |
206 c1.constraint_name constraint | |
207 FROM | |
208 user_constraints c1, | |
209 user_constraints c2 | |
210 WHERE | |
211 c1.table_name = :object_name | |
212 and c1.constraint_type ='R' | |
213 and c1.r_constraint_name = c2.constraint_name | |
214 and c1.r_owner = c2.owner | |
215 and c1.owner = :owner | |
216 UNION | |
217 SELECT c1.table_name referenced_by, | |
218 NULL references, | |
219 c1.constraint_name constraint | |
220 FROM | |
221 user_constraints c1, | |
222 user_constraints c2 | |
223 WHERE | |
224 c2.table_name = :object_name | |
225 and c1.constraint_type ='R' | |
226 and c1.r_constraint_name = c2.constraint_name | |
227 and c1.r_owner = c2.owner | |
228 and c1.owner = :owner | |
229 """ | |
230 } | |
231 | |
232 class SoftwareSearcher(object): | |
233 def __init__(self, softwareList, purpose): | |
234 self.softwareList = softwareList | |
235 self.purpose = purpose | |
236 self.software = None | |
237 def invoke(self, *args): | |
238 if not self.software: | |
239 (self.software, self.invokeString) = self.find() | |
240 argTuple = tuple([self.software] + list(args)) | |
241 os.system(self.invokeString % argTuple) | |
242 def find(self): | |
243 if self.purpose == 'text editor': | |
244 software = os.environ.get('EDITOR') | |
245 if software: | |
246 return (software, '%s %s') | |
247 for (n, (software, invokeString)) in enumerate(self.softwareList): | |
248 if os.path.exists(software): | |
249 if n > (len(self.softwareList) * 0.7): | |
250 print """ | |
251 | |
252 Using %s. Note that there are better options available for %s, | |
253 but %s couldn't find a better one in your PATH. | |
254 Feel free to open up %s | |
255 and customize it to find your favorite %s program. | |
256 | |
257 """ % (software, self.purpose, __file__, __file__, self.purpose) | |
258 return (software, invokeString) | |
259 stem = os.path.split(software)[1] | |
260 for p in os.environ['PATH'].split(os.pathsep): | |
261 if os.path.exists(os.sep.join([p, stem])): | |
262 return (stem, invokeString) | |
263 raise (OSError, """Could not find any %s programs. You will need to install one, | |
264 or customize %s to make it aware of yours. | |
265 Looked for these programs: | |
266 %s""" % (self.purpose, __file__, "\n".join([s[0] for s in self.softwareList]))) | |
267 | |
268 softwareLists = { | |
269 'diff/merge': [ | |
270 ('/usr/bin/meld',"%s %s %s"), | |
271 ('/usr/bin/kdiff3',"%s %s %s"), | |
272 (r'C:\Program Files\Araxis\Araxis Merge v6.5\Merge.exe','"%s" %s %s'), | |
273 (r'C:\Program Files\TortoiseSVN\bin\TortoiseMerge.exe', '"%s" /base:"%s" /mine:"%s"'), | |
274 ('FileMerge','%s %s %s'), | |
275 ('kompare','%s %s %s'), | |
276 ('WinMerge','%s %s %s'), | |
277 ('xxdiff','%s %s %s'), | |
278 ('fldiff','%s %s %s'), | |
279 ('gtkdiff','%s %s %s'), | |
280 ('tkdiff','%s %s %s'), | |
281 ('gvimdiff','%s %s %s'), | |
282 ('diff',"%s %s %s"), | |
283 (r'c:\windows\system32\comp.exe',"%s %s %s")], | |
284 'text editor': [ | |
285 ('gedit', '%s %s'), | |
286 ('textpad', '%s %s'), | |
287 ('notepad.exe', '%s %s'), | |
288 ('pico', '%s %s'), | |
289 ('emacs', '%s %s'), | |
290 ('vim', '%s %s'), | |
291 ('vi', '%s %s'), | |
292 ('ed', '%s %s'), | |
293 ('edlin', '%s %s') | |
294 ] | |
295 } | |
296 | |
297 diffMergeSearcher = SoftwareSearcher(softwareLists['diff/merge'],'diff/merge') | |
298 editSearcher = SoftwareSearcher(softwareLists['text editor'], 'text editor') | |
299 editor = os.environ.get('EDITOR') | |
300 if editor: | |
301 editSearcher.find = lambda: (editor, "%s %s") | |
302 | |
303 class CaselessDict(dict): | |
304 """dict with case-insensitive keys. | |
305 | |
306 Posted to ASPN Python Cookbook by Jeff Donner - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66315""" | |
307 def __init__(self, other=None): | |
308 if other: | |
309 # Doesn't do keyword args | |
310 if isinstance(other, dict): | |
311 for k,v in other.items(): | |
312 dict.__setitem__(self, k.lower(), v) | |
313 else: | |
314 for k,v in other: | |
315 dict.__setitem__(self, k.lower(), v) | |
316 def __getitem__(self, key): | |
317 return dict.__getitem__(self, key.lower()) | |
318 def __setitem__(self, key, value): | |
273
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
319 try: |
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
320 key = key.lower() |
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
321 except AttributeError: |
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
322 pass |
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
323 dict.__setitem__(self, key, value) |
189 | 324 def __contains__(self, key): |
325 return dict.__contains__(self, key.lower()) | |
326 def has_key(self, key): | |
327 return dict.has_key(self, key.lower()) | |
328 def get(self, key, def_val=None): | |
329 return dict.get(self, key.lower(), def_val) | |
330 def setdefault(self, key, def_val=None): | |
331 return dict.setdefault(self, key.lower(), def_val) | |
332 def update(self, other): | |
333 for k,v in other.items(): | |
334 dict.__setitem__(self, k.lower(), v) | |
335 def fromkeys(self, iterable, value=None): | |
336 d = CaselessDict() | |
337 for k in iterable: | |
338 dict.__setitem__(d, k.lower(), value) | |
339 return d | |
340 def pop(self, key, def_val=None): | |
341 return dict.pop(self, key.lower(), def_val) | |
342 | |
343 class Parser(object): | |
246 | 344 comment_def = "--" + ~ ('-' + pyparsing.CaselessKeyword('begin')) + pyparsing.ZeroOrMore(pyparsing.CharsNotIn("\n")) |
189 | 345 def __init__(self, scanner, retainSeparator=True): |
346 self.scanner = scanner | |
347 self.scanner.ignore(pyparsing.sglQuotedString) | |
348 self.scanner.ignore(pyparsing.dblQuotedString) | |
349 self.scanner.ignore(self.comment_def) | |
350 self.scanner.ignore(pyparsing.cStyleComment) | |
351 self.retainSeparator = retainSeparator | |
352 def separate(self, txt): | |
353 itms = [] | |
354 for (sqlcommand, start, end) in self.scanner.scanString(txt): | |
355 if sqlcommand: | |
356 if type(sqlcommand[0]) == pyparsing.ParseResults: | |
357 if self.retainSeparator: | |
358 itms.append("".join(sqlcommand[0])) | |
359 else: | |
360 itms.append(sqlcommand[0][0]) | |
361 else: | |
362 if sqlcommand[0]: | |
363 itms.append(sqlcommand[0]) | |
364 return itms | |
365 | |
366 bindScanner = Parser(pyparsing.Literal(':') + pyparsing.Word( pyparsing.alphanums + "_$#" )) | |
367 | |
368 def findBinds(target, existingBinds, givenBindVars = {}): | |
369 result = givenBindVars | |
370 for finding, startat, endat in bindScanner.scanner.scanString(target): | |
371 varname = finding[1] | |
372 try: | |
373 result[varname] = existingBinds[varname] | |
374 except KeyError: | |
375 if not givenBindVars.has_key(varname): | |
376 print 'Bind variable %s not defined.' % (varname) | |
377 return result | |
192
6bb8a112af6b
accept special terminators on most anything
catherine@dellzilla
parents:
191
diff
changeset
|
378 |
271 | 379 class ResultSet(list): |
380 pass | |
381 | |
382 class Result(tuple): | |
383 def __str__(self): | |
272 | 384 return '\n'.join('%s: %s' % (colname, self[idx]) |
385 for (idx, colname) in enumerate(self.resultset.colnames)) | |
271 | 386 def __getattr__(self, attr): |
387 attr = attr.lower() | |
388 try: | |
389 return self[self.resultset.colnames.index(attr)] | |
390 except ValueError: | |
307 | 391 if attr in ('colnames', 'statement', 'bindvars', 'resultset'): |
271 | 392 return getattr(self.resultset, attr) |
393 else: | |
394 raise AttributeError, "available columns are: " + ", ".join(self.resultset.colnames) | |
273
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
395 def bind(self): |
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
396 for (idx, colname) in enumerate(self.resultset.colnames): |
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
397 self.resultset.pystate['binds'][colname] = self[idx] |
277 | 398 self.resultset.pystate['binds'][str(idx+1)] = self[idx] |
271 | 399 |
288 | 400 def centeredSlice(lst, center=0, width=1): |
401 width = max(width, -1) | |
402 if center < 0: | |
403 end = center + width + 1 | |
404 if end >= 0: | |
405 end = None | |
406 return lst[center-width:end] | |
407 else: | |
408 return lst[max(center-width,0):center+width+1] | |
409 | |
189 | 410 class sqlpyPlus(sqlpython.sqlpython): |
411 defaultExtension = 'sql' | |
289
3cade02da892
replacing manual abbreviations with abbrev param
catherine@Elli.myhome.westell.com
parents:
285
diff
changeset
|
412 abbrev = True |
189 | 413 sqlpython.sqlpython.shortcuts.update({':': 'setbind', |
414 '\\': 'psql', | |
286 | 415 '@': 'get'}) |
189 | 416 multilineCommands = '''select insert update delete tselect |
417 create drop alter _multiline_comment'''.split() | |
418 sqlpython.sqlpython.noSpecialParse.append('spool') | |
419 commentGrammars = pyparsing.Or([pyparsing.Literal('--') + pyparsing.restOfLine, pyparsing.cStyleComment]) | |
246 | 420 commentGrammars = pyparsing.Or([Parser.comment_def, pyparsing.cStyleComment]) |
259
c0847a4c7f49
one-shot connection changes
catherine@Elli.myhome.westell.com
parents:
257
diff
changeset
|
421 prefixParser = pyparsing.Optional(pyparsing.Word(pyparsing.nums)('connection_number') |
c0847a4c7f49
one-shot connection changes
catherine@Elli.myhome.westell.com
parents:
257
diff
changeset
|
422 + ':') |
309
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
423 reserved_words = [ |
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
424 'alter', 'begin', 'comment', 'create', 'delete', 'drop', 'end', 'for', 'grant', |
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
425 'insert', 'intersect', 'lock', 'minus', 'on', 'order', 'rename', |
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
426 'resource', 'revoke', 'select', 'share', 'start', 'union', 'update', |
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
427 'where', 'with'] |
247 | 428 default_file_name = 'afiedt.buf' |
189 | 429 def __init__(self): |
430 sqlpython.sqlpython.__init__(self) | |
431 self.binds = CaselessDict() | |
281 | 432 self.settable += 'autobind commit_on_exit maxfetch maxtselctrows scan serveroutput sql_echo store_results timeout heading wildsql'.split() |
247 | 433 self.settable.remove('case_insensitive') |
230 | 434 self.settable.sort() |
189 | 435 self.stdoutBeforeSpool = sys.stdout |
249 | 436 self.sql_echo = False |
189 | 437 self.spoolFile = None |
438 self.autobind = False | |
229 | 439 self.heading = True |
240 | 440 self.wildsql = False |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
441 self.serveroutput = True |
271 | 442 self.scan = True |
292 | 443 self.nonpythoncommand = 'sql' |
271 | 444 self.substvars = {} |
445 self.result_history = [] | |
281 | 446 self.store_results = True |
309
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
447 |
284 | 448 self.pystate = {'r': [], 'binds': self.binds, 'substs': self.substvars} |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
449 |
189 | 450 # overrides cmd's parseline |
451 def parseline(self, line): | |
452 """Parse the line into a command name and a string containing | |
453 the arguments. Returns a tuple containing (command, args, line). | |
454 'command' and 'args' may be None if the line couldn't be parsed. | |
455 Overrides cmd.cmd.parseline to accept variety of shortcuts..""" | |
456 | |
457 cmd, arg, line = sqlpython.sqlpython.parseline(self, line) | |
458 if cmd in ('select', 'sleect', 'insert', 'update', 'delete', 'describe', | |
459 'desc', 'comments', 'pull', 'refs', 'desc', 'triggers', 'find') \ | |
460 and not hasattr(self, 'curs'): | |
461 print 'Not connected.' | |
462 return '', '', '' | |
463 return cmd, arg, line | |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
464 |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
465 def dbms_output(self): |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
466 "Dumps contents of Oracle's DBMS_OUTPUT buffer (where PUT_LINE goes)" |
261 | 467 try: |
468 line = self.curs.var(cx_Oracle.STRING) | |
469 status = self.curs.var(cx_Oracle.NUMBER) | |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
470 self.curs.callproc('dbms_output.get_line', [line, status]) |
261 | 471 while not status.getvalue(): |
472 self.stdout.write(line.getvalue()) | |
473 self.stdout.write('\n') | |
474 self.curs.callproc('dbms_output.get_line', [line, status]) | |
475 except AttributeError: | |
476 pass | |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
477 |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
478 def postcmd(self, stop, line): |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
479 """Hook method executed just after a command dispatch is finished.""" |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
480 if self.serveroutput: |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
481 self.dbms_output() |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
482 return stop |
241 | 483 |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
484 def do_remark(self, line): |
242 | 485 ''' |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
486 REMARK is one way to denote a comment in SQL*Plus. |
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
487 |
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
488 Wrapping a *single* SQL or PL/SQL statement in `REMARK BEGIN` and `REMARK END` |
241 | 489 tells sqlpython to submit the enclosed code directly to Oracle as a single |
242 | 490 unit of code. |
241 | 491 |
492 Without these markers, sqlpython fails to properly distinguish the beginning | |
493 and end of all but the simplest PL/SQL blocks, causing errors. sqlpython also | |
494 slows down when parsing long SQL statements as it tries to determine whether | |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
495 the statement has ended yet; `REMARK BEGIN` and `REMARK END` allow it to skip this |
241 | 496 parsing. |
497 | |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
498 Standard SQL*Plus interprets REMARK BEGIN and REMARK END as comments, so it is |
242 | 499 safe to include them in SQL*Plus scripts. |
241 | 500 ''' |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
501 if not line.lower().strip().startswith('begin'): |
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
502 return |
241 | 503 statement = [] |
247 | 504 next = self.pseudo_raw_input(self.continuation_prompt) |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
505 while next.lower().split()[:2] != ['remark','end']: |
241 | 506 statement.append(next) |
247 | 507 next = self.pseudo_raw_input(self.continuation_prompt) |
242 | 508 return self.onecmd('\n'.join(statement)) |
272 | 509 |
292 | 510 def do_py(self, arg): |
272 | 511 ''' |
512 py <command>: Executes a Python command. | |
297 | 513 py: Enters interactive Python mode. |
514 End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, 'exit()`. | |
292 | 515 Past SELECT results are exposed as list `r`; |
275 | 516 most recent resultset is `r[-1]`. |
292 | 517 SQL bind, substitution variables are exposed as `binds`, `substs`. |
296 | 518 SQL and sqlpython commands can be issued with `sql("your command")`. |
272 | 519 ''' |
292 | 520 return Cmd.do_py(self, arg) |
284 | 521 |
522 def do_get(self, args): | |
523 """ | |
524 `get {script.sql}` or `@{script.sql}` runs the command(s) in {script.sql}. | |
525 If additional arguments are supplied, they are assigned to &1, &2, etc. | |
526 """ | |
527 fname, args = args.split()[0], args.split()[1:] | |
528 for (idx, arg) in enumerate(args): | |
529 self.substvars[str(idx+1)] = arg | |
530 return Cmd.do__load(self, fname) | |
531 | |
189 | 532 def onecmd_plus_hooks(self, line): |
533 line = self.precmd(line) | |
534 stop = self.onecmd(line) | |
535 stop = self.postcmd(stop, line) | |
536 | |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
537 def _onchange_serveroutput(self, old, new): |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
538 if new: |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
539 self.curs.callproc('dbms_output.enable', []) |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
540 else: |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
541 self.curs.callproc('dbms_output.disable', []) |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
542 |
189 | 543 def do_shortcuts(self,arg): |
544 """Lists available first-character shortcuts | |
545 (i.e. '!dir' is equivalent to 'shell dir')""" | |
546 for (scchar, scto) in self.shortcuts.items(): | |
547 print '%s: %s' % (scchar, scto) | |
548 | |
254
b61e21386383
oops, restore lines of code after sql_format_item
catherine@Elli.myhome.westell.com
parents:
253
diff
changeset
|
549 tableNameFinder = re.compile(r'from\s+([\w$#_"]+)', re.IGNORECASE | re.MULTILINE | re.DOTALL) |
b61e21386383
oops, restore lines of code after sql_format_item
catherine@Elli.myhome.westell.com
parents:
253
diff
changeset
|
550 inputStatementFormatters = { |
b61e21386383
oops, restore lines of code after sql_format_item
catherine@Elli.myhome.westell.com
parents:
253
diff
changeset
|
551 cx_Oracle.STRING: "'%s'", |
b61e21386383
oops, restore lines of code after sql_format_item
catherine@Elli.myhome.westell.com
parents:
253
diff
changeset
|
552 cx_Oracle.DATETIME: "TO_DATE('%s', 'YYYY-MM-DD HH24:MI:SS')"} |
b61e21386383
oops, restore lines of code after sql_format_item
catherine@Elli.myhome.westell.com
parents:
253
diff
changeset
|
553 inputStatementFormatters[cx_Oracle.CLOB] = inputStatementFormatters[cx_Oracle.STRING] |
b61e21386383
oops, restore lines of code after sql_format_item
catherine@Elli.myhome.westell.com
parents:
253
diff
changeset
|
554 inputStatementFormatters[cx_Oracle.TIMESTAMP] = inputStatementFormatters[cx_Oracle.DATETIME] |
189 | 555 def output(self, outformat, rowlimit): |
556 self.tblname = self.tableNameFinder.search(self.curs.statement).group(1) | |
557 self.colnames = [d[0] for d in self.curs.description] | |
558 if outformat in output_templates: | |
559 self.colnamelen = max(len(colname) for colname in self.colnames) | |
560 self.coltypes = [d[1] for d in self.curs.description] | |
561 self.formatters = [self.inputStatementFormatters.get(typ, '%s') for typ in self.coltypes] | |
562 result = output_templates[outformat].generate(**self.__dict__) | |
563 elif outformat == '\\t': # transposed | |
564 rows = [self.colnames] | |
565 rows.extend(list(self.rows)) | |
566 transpr = [[rows[y][x] for y in range(len(rows))]for x in range(len(rows[0]))] # matrix transpose | |
567 newdesc = [['ROW N.'+str(y),10] for y in range(len(rows))] | |
568 for x in range(len(self.curs.description)): | |
569 if str(self.curs.description[x][1]) == "<type 'cx_Oracle.BINARY'>": # handles RAW columns | |
570 rname = transpr[x][0] | |
571 transpr[x] = map(binascii.b2a_hex, transpr[x]) | |
572 transpr[x][0] = rname | |
573 newdesc[0][0] = 'COLUMN NAME' | |
574 result = '\n' + sqlpython.pmatrix(transpr,newdesc) | |
575 elif outformat in ('\\l', '\\L', '\\p', '\\b'): | |
576 plot = Plot() | |
577 plot.build(self, outformat) | |
578 plot.shelve() | |
579 plot.draw() | |
580 return '' | |
581 else: | |
308 | 582 result = sqlpython.pmatrix(self.rows, self.curs.description, |
583 self.maxfetch, heading=self.heading, | |
584 restructuredtext = (outformat == '\\r')) | |
189 | 585 return result |
586 | |
587 legalOracle = re.compile('[a-zA-Z_$#]') | |
588 | |
589 def select_scalar_list(self, sql, binds={}): | |
249 | 590 self._execute(sql, binds) |
189 | 591 return [r[0] for r in self.curs.fetchall()] |
592 | |
593 columnNameRegex = re.compile( | |
594 r'select\s+(.*)from', | |
595 re.IGNORECASE | re.DOTALL | re.MULTILINE) | |
596 def completedefault(self, text, line, begidx, endidx): | |
597 segment = completion.whichSegment(line) | |
598 text = text.upper() | |
599 completions = [] | |
600 if segment == 'select': | |
601 stmt = "SELECT column_name FROM user_tab_columns WHERE column_name LIKE '%s%%'" | |
602 completions = self.select_scalar_list(stmt % (text)) | |
603 if not completions: | |
604 stmt = "SELECT column_name FROM all_tab_columns WHERE column_name LIKE '%s%%'" | |
605 completions = self.select_scalar_list(stmt % (text)) | |
606 if segment == 'from': | |
607 columnNames = self.columnNameRegex.search(line) | |
608 if columnNames: | |
609 columnNames = columnNames.group(1) | |
610 columnNames = [c.strip().upper() for c in columnNames.split(',')] | |
611 stmt1 = "SELECT table_name FROM all_tab_columns WHERE column_name = '%s' AND table_name LIKE '%s%%'" | |
612 for columnName in columnNames: | |
613 # and if columnName is * ? | |
614 completions.extend(self.select_scalar_list(stmt1 % (columnName, text))) | |
615 if segment in ('from', 'update', 'insert into') and (not completions): | |
616 stmt = "SELECT table_name FROM user_tables WHERE table_name LIKE '%s%%'" | |
617 completions = self.select_scalar_list(stmt % (text)) | |
618 if not completions: | |
619 stmt = """SELECT table_name FROM user_tables WHERE table_name LIKE '%s%%' | |
620 UNION | |
621 SELECT DISTINCT owner FROM all_tables WHERE owner LIKE '%%%s'""" | |
622 completions = self.select_scalar_list(stmt % (text, text)) | |
623 if segment in ('where', 'group by', 'order by', 'having', 'set'): | |
624 tableNames = completion.tableNamesFromFromClause(line) | |
625 if tableNames: | |
626 stmt = """SELECT column_name FROM all_tab_columns | |
627 WHERE table_name IN (%s)""" % \ | |
628 (','.join("'%s'" % (t) for t in tableNames)) | |
629 stmt = "%s AND column_name LIKE '%s%%'" % (stmt, text) | |
630 completions = self.select_scalar_list(stmt) | |
631 if not segment: | |
632 stmt = "SELECT object_name FROM all_objects WHERE object_name LIKE '%s%%'" | |
633 completions = self.select_scalar_list(stmt % (text)) | |
634 return completions | |
233 | 635 |
234
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
636 columnlistPattern = pyparsing.SkipTo(pyparsing.CaselessKeyword('from'))('columns') + \ |
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
637 pyparsing.SkipTo(pyparsing.stringEnd)('remainder') |
233 | 638 |
236 | 639 negator = pyparsing.Literal('!')('exclude') |
242 | 640 colNumber = pyparsing.Optional(negator) + pyparsing.Literal('#') + pyparsing.Word('-' + pyparsing.nums, pyparsing.nums)('column_number') |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
641 colName = negator + pyparsing.Word('$_#' + pyparsing.alphas, '$_#' + pyparsing.alphanums)('column_name') |
241 | 642 wildColName = pyparsing.Optional(negator) + pyparsing.Word('?*%$_#' + pyparsing.alphas, '?*%$_#' + pyparsing.alphanums, min=2)('column_name') |
242 | 643 colNumber.ignore(pyparsing.cStyleComment).ignore(Parser.comment_def). \ |
644 ignore(pyparsing.sglQuotedString).ignore(pyparsing.dblQuotedString) | |
235 | 645 wildSqlParser = colNumber ^ colName ^ wildColName |
646 wildSqlParser.ignore(pyparsing.cStyleComment).ignore(Parser.comment_def). \ | |
236 | 647 ignore(pyparsing.sglQuotedString).ignore(pyparsing.dblQuotedString) |
648 emptyCommaRegex = re.compile(',\s*,', re.DOTALL) | |
649 deadStarterCommaRegex = re.compile('^\s*,', re.DOTALL) | |
650 deadEnderCommaRegex = re.compile(',\s*$', re.DOTALL) | |
233 | 651 def expandWildSql(self, arg): |
652 try: | |
234
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
653 columnlist = self.columnlistPattern.parseString(arg) |
233 | 654 except pyparsing.ParseException: |
655 return arg | |
236 | 656 parseresults = list(self.wildSqlParser.scanString(columnlist.columns)) |
239
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
657 # I would rather exclude non-wild column names in the grammar, |
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
658 # but can't figure out how |
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
659 parseresults = [p for p in parseresults if |
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
660 p[0].column_number or |
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
661 '*' in p[0].column_name or |
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
662 '%' in p[0].column_name or |
241 | 663 '?' in p[0].column_name or |
239
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
664 p[0].exclude] |
236 | 665 if not parseresults: |
666 return arg | |
234
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
667 self.curs.execute('select * ' + columnlist.remainder, self.varsUsed) |
236 | 668 columns_available = [d[0] for d in self.curs.description] |
234
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
669 replacers = {} |
236 | 670 included = set() |
671 excluded = set() | |
672 for (col, startpos, endpos) in parseresults: | |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
673 replacers[arg[startpos:endpos]] = [] |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
674 if col.column_name: |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
675 finder = col.column_name.replace('*','.*') |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
676 finder = finder.replace('%','.*') |
241 | 677 finder = finder.replace('?','.') |
678 colnames = [c for c in columns_available if re.match(finder + '$', c, re.IGNORECASE)] | |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
679 elif col.column_number: |
236 | 680 idx = int(col.column_number) |
681 if idx > 0: | |
682 idx -= 1 | |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
683 colnames = [columns_available[idx]] |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
684 if not colnames: |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
685 print 'No columns found matching criteria.' |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
686 return 'null from dual' |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
687 for colname in colnames: |
236 | 688 if col.exclude: |
689 included.discard(colname) | |
690 include_here = columns_available[:] | |
691 include_here.remove(colname) | |
240 | 692 replacers[arg[startpos:endpos]].extend(i for i in include_here if i not in replacers[arg[startpos:endpos]]) |
236 | 693 excluded.add(colname) |
694 else: | |
695 excluded.discard(colname) | |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
696 replacers[arg[startpos:endpos]].append(colname) |
236 | 697 |
234
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
698 replacers = sorted(replacers.items(), key=len, reverse=True) |
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
699 result = columnlist.columns |
236 | 700 for (target, replacement) in replacers: |
242 | 701 cols = [r for r in replacement if r not in excluded and r not in included] |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
702 replacement = ', '.join(cols) |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
703 included.update(cols) |
236 | 704 result = result.replace(target, replacement) |
242 | 705 # some column names could get wiped out completely, so we fix their dangling commas |
236 | 706 result = self.emptyCommaRegex.sub(',', result) |
707 result = self.deadStarterCommaRegex.sub('', result) | |
708 result = self.deadEnderCommaRegex.sub('', result) | |
242 | 709 if not result.strip(): |
710 print 'No columns found matching criteria.' | |
711 return 'null from dual' | |
237 | 712 return result + ' ' + columnlist.remainder |
284 | 713 |
714 def do_prompt(self, args): | |
715 print args | |
233 | 716 |
284 | 717 def do_accept(self, args): |
718 try: | |
719 prompt = args[args.lower().index('prompt ')+7:] | |
720 except ValueError: | |
721 prompt = '' | |
722 varname = args.lower().split()[0] | |
723 self.substvars[varname] = self.pseudo_raw_input(prompt) | |
724 | |
281 | 725 def ampersand_substitution(self, raw, regexpr, isglobal): |
271 | 726 subst = regexpr.search(raw) |
727 while subst: | |
728 fullexpr, var = subst.group(1), subst.group(2) | |
729 print 'Substitution variable %s found in:' % fullexpr | |
730 print raw[max(subst.start()-20, 0):subst.end()+20] | |
284 | 731 if var in self.substvars: |
271 | 732 val = self.substvars[var] |
733 else: | |
734 val = raw_input('Substitution for %s (SET SCAN OFF to halt substitution): ' % fullexpr) | |
735 if val.lower().split() == ['set','scan','off']: | |
736 self.scan = False | |
737 return raw | |
738 if isglobal: | |
739 self.substvars[var] = val | |
740 raw = raw.replace(fullexpr, val) | |
741 print 'Substituted %s for %s' % (val, fullexpr) | |
742 subst = regexpr.search(raw) # do not FINDALL b/c we don't want to ask twice | |
743 return raw | |
284 | 744 |
745 numericampre = re.compile('(&(\d+))') | |
746 doubleampre = re.compile('(&&([a-zA-Z\d_$#]+))', re.IGNORECASE) | |
747 singleampre = re.compile( '(&([a-zA-Z\d_$#]+))', re.IGNORECASE) | |
271 | 748 def preparse(self, raw, **kwargs): |
749 if self.scan: | |
284 | 750 raw = self.ampersand_substitution(raw, regexpr=self.numericampre, isglobal=False) |
751 if self.scan: | |
281 | 752 raw = self.ampersand_substitution(raw, regexpr=self.doubleampre, isglobal=True) |
271 | 753 if self.scan: |
281 | 754 raw = self.ampersand_substitution(raw, regexpr=self.singleampre, isglobal=False) |
271 | 755 return raw |
756 | |
189 | 757 rowlimitPattern = pyparsing.Word(pyparsing.nums)('rowlimit') |
308 | 758 terminators = '; \\C \\t \\i \\p \\l \\L \\b \\r'.split() + output_templates.keys() |
199
09592342a33d
ugh - parsing stripping command causes real trouble
catherine@dellzilla
parents:
198
diff
changeset
|
759 |
281 | 760 @options([make_option('-r', '--row', type="int", default=-1, |
761 help='Bind row #ROW instead of final row (zero-based)')]) | |
762 def do_bind(self, arg=None, opts={}): | |
763 ''' | |
764 Inserts the results from the final row in the last completed SELECT statement | |
765 into bind variables with names corresponding to the column names. When the optional | |
766 `autobind` setting is on, this will be issued automatically after every query that | |
767 returns exactly one row. | |
768 ''' | |
769 try: | |
770 self.pystate['r'][-1][opts.row].bind() | |
771 except IndexError: | |
772 print self.do_bind.__doc__ | |
271 | 773 |
192
6bb8a112af6b
accept special terminators on most anything
catherine@dellzilla
parents:
191
diff
changeset
|
774 def do_select(self, arg, bindVarsIn=None, terminator=None): |
189 | 775 """Fetch rows from a table. |
776 | |
777 Limit the number of rows retrieved by appending | |
778 an integer after the terminator | |
779 (example: SELECT * FROM mytable;10 ) | |
780 | |
781 Output may be formatted by choosing an alternative terminator | |
782 ("help terminators" for details) | |
783 """ | |
784 bindVarsIn = bindVarsIn or {} | |
196 | 785 try: |
786 rowlimit = int(arg.parsed.suffix or 0) | |
787 except ValueError: | |
788 rowlimit = 0 | |
206 | 789 print "Specify desired number of rows after terminator (not '%s')" % arg.parsed.suffix |
281 | 790 if arg.parsed.terminator == '\\t': |
791 rowlimit = rowlimit or self.maxtselctrows | |
194 | 792 self.varsUsed = findBinds(arg, self.binds, bindVarsIn) |
233 | 793 if self.wildsql: |
234
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
794 selecttext = self.expandWildSql(arg) |
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
795 else: |
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
796 selecttext = arg |
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
797 self.curs.execute('select ' + selecttext, self.varsUsed) |
194 | 798 self.rows = self.curs.fetchmany(min(self.maxfetch, (rowlimit or self.maxfetch))) |
189 | 799 self.rc = self.curs.rowcount |
800 if self.rc > 0: | |
271 | 801 resultset = ResultSet() |
802 resultset.colnames = [d[0].lower() for d in self.curs.description] | |
281 | 803 resultset.pystate = self.pystate |
271 | 804 resultset.statement = 'select ' + selecttext |
273
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
805 resultset.varsUsed = self.varsUsed |
271 | 806 resultset.extend([Result(r) for r in self.rows]) |
807 for row in resultset: | |
808 row.resultset = resultset | |
281 | 809 self.pystate['r'].append(resultset) |
194 | 810 self.stdout.write('\n%s\n' % (self.output(arg.parsed.terminator, rowlimit))) |
189 | 811 if self.rc == 0: |
812 print '\nNo rows Selected.\n' | |
813 elif self.rc == 1: | |
814 print '\n1 row selected.\n' | |
815 if self.autobind: | |
281 | 816 self.do_bind() |
189 | 817 elif self.rc < self.maxfetch: |
818 print '\n%d rows selected.\n' % self.rc | |
819 else: | |
820 print '\nSelected Max Num rows (%d)' % self.rc | |
193 | 821 |
822 def do_cat(self, arg): | |
226 | 823 '''Shortcut for SELECT * FROM''' |
200 | 824 return self.do_select(self.parsed('SELECT * FROM %s;' % arg, |
825 terminator = arg.parsed.terminator or ';', | |
826 suffix = arg.parsed.suffix)) | |
220 | 827 |
828 def _pull(self, arg, opts, vc=None): | |
829 """Displays source code.""" | |
830 if opts.dump: | |
831 statekeeper = Statekeeper(self, ('stdout',)) | |
832 try: | |
833 for (owner, object_type, object_name) in self.resolve_many(arg, opts): | |
834 if object_type in self.supported_ddl_types: | |
835 object_type = {'DATABASE LINK': 'DB_LINK', 'JAVA CLASS': 'JAVA_SOURCE' | |
836 }.get(object_type) or object_type | |
837 object_type = object_type.replace(' ', '_') | |
838 if opts.dump: | |
839 try: | |
840 os.makedirs(os.path.join(owner.lower(), object_type.lower())) | |
841 except OSError: | |
842 pass | |
843 filename = os.path.join(owner.lower(), object_type.lower(), '%s.sql' % object_name.lower()) | |
844 self.stdout = open(filename, 'w') | |
845 if vc: | |
846 subprocess.call(vc + [filename]) | |
248 | 847 if object_type == 'PACKAGE': |
848 ddl = [['PACKAGE_SPEC', object_name, owner],['PACKAGE_BODY', object_name, owner]] | |
849 elif object_type in ['CONTEXT', 'DIRECTORY', 'JOB']: | |
850 ddl = [[object_type, object_name]] | |
851 else: | |
852 ddl = [[object_type, object_name, owner]] | |
853 for ddlargs in ddl: | |
854 try: | |
288 | 855 code = str(self.curs.callfunc('DBMS_METADATA.GET_DDL', cx_Oracle.CLOB, ddlargs)) |
305 | 856 if hasattr(opts, 'lines') and opts.lines: |
288 | 857 code = code.splitlines() |
858 template = "%%-%dd:%%s" % len(str(len(code))) | |
859 code = '\n'.join(template % (n+1, line) for (n, line) in enumerate(code)) | |
305 | 860 if hasattr(opts, 'num') and (opts.num is not None): |
288 | 861 code = code.splitlines() |
862 code = centeredSlice(code, center=opts.num+1, width=opts.width) | |
863 code = '\n'.join(code) | |
864 self.stdout.write('REMARK BEGIN %s\n%s\nREMARK END\n\n' % (object_name, code)) | |
248 | 865 except cx_Oracle.DatabaseError, errmsg: |
866 if object_type == 'JOB': | |
867 print '%s: DBMS_METADATA.GET_DDL does not support JOBs (MetaLink DocID 567504.1)' % object_name | |
868 elif 'ORA-31603' in str(errmsg): # not found, as in package w/o package body | |
869 pass | |
870 else: | |
871 raise | |
220 | 872 if opts.full: |
873 for dependent_type in ('OBJECT_GRANT', 'CONSTRAINT', 'TRIGGER'): | |
874 try: | |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
875 self.stdout.write('REMARK BEGIN\n%s\nREMARK END\n\n' % str(self.curs.callfunc('DBMS_METADATA.GET_DEPENDENT_DDL', cx_Oracle.CLOB, |
220 | 876 [dependent_type, object_name, owner]))) |
877 except cx_Oracle.DatabaseError: | |
878 pass | |
879 if opts.dump: | |
880 self.stdout.close() | |
881 except: | |
882 if opts.dump: | |
883 statekeeper.restore() | |
884 raise | |
885 if opts.dump: | |
886 statekeeper.restore() | |
887 | |
221 | 888 def do_show(self, arg): |
889 ''' | |
890 show - display value of all sqlpython parameters | |
891 show (parameter name) - display value of a sqlpython parameter | |
892 show parameter (parameter name) - display value of an ORACLE parameter | |
265
041c656dc8e5
show err working nicely now
catherine@Elli.myhome.westell.com
parents:
264
diff
changeset
|
893 show err (object type/name) - errors from latest PL/SQL object compilation. |
041c656dc8e5
show err working nicely now
catherine@Elli.myhome.westell.com
parents:
264
diff
changeset
|
894 show all err (type/name) - all compilation errors from the user's PL/SQL objects. |
221 | 895 ''' |
896 if arg.startswith('param'): | |
897 try: | |
898 paramname = arg.split()[1].lower() | |
899 except IndexError: | |
900 paramname = '' | |
901 self.onecmd("""SELECT name, | |
902 CASE type WHEN 1 THEN 'BOOLEAN' | |
903 WHEN 2 THEN 'STRING' | |
904 WHEN 3 THEN 'INTEGER' | |
905 WHEN 4 THEN 'PARAMETER FILE' | |
906 WHEN 5 THEN 'RESERVED' | |
907 WHEN 6 THEN 'BIG INTEGER' END type, | |
908 value FROM v$parameter WHERE name LIKE '%%%s%%';""" % paramname) | |
909 else: | |
264
a8deaa38f11e
show errors works. limiting ls
catherine@Elli.myhome.westell.com
parents:
261
diff
changeset
|
910 argpieces = arg.lower().split() |
a8deaa38f11e
show errors works. limiting ls
catherine@Elli.myhome.westell.com
parents:
261
diff
changeset
|
911 try: |
a8deaa38f11e
show errors works. limiting ls
catherine@Elli.myhome.westell.com
parents:
261
diff
changeset
|
912 if argpieces[0][:3] == 'err': |
265
041c656dc8e5
show err working nicely now
catherine@Elli.myhome.westell.com
parents:
264
diff
changeset
|
913 return self._show_errors(all_users=False, limit=1, targets=argpieces[1:]) |
264
a8deaa38f11e
show errors works. limiting ls
catherine@Elli.myhome.westell.com
parents:
261
diff
changeset
|
914 elif (argpieces[0], argpieces[1][:3]) == ('all','err'): |
265
041c656dc8e5
show err working nicely now
catherine@Elli.myhome.westell.com
parents:
264
diff
changeset
|
915 return self._show_errors(all_users=False, limit=None, targets=argpieces[2:]) |
264
a8deaa38f11e
show errors works. limiting ls
catherine@Elli.myhome.westell.com
parents:
261
diff
changeset
|
916 except IndexError: |
a8deaa38f11e
show errors works. limiting ls
catherine@Elli.myhome.westell.com
parents:
261
diff
changeset
|
917 pass |
221 | 918 return Cmd.do_show(self, arg) |
919 | |
218
397979c7f6d6
dumping working but not for wildcards
catherine@Elli.myhome.westell.com
parents:
217
diff
changeset
|
920 @options([make_option('-d', '--dump', action='store_true', help='dump results to files'), |
397979c7f6d6
dumping working but not for wildcards
catherine@Elli.myhome.westell.com
parents:
217
diff
changeset
|
921 make_option('-f', '--full', action='store_true', help='get dependent objects as well'), |
288 | 922 make_option('-l', '--lines', action='store_true', help='print line numbers'), |
923 make_option('-n', '--num', type='int', help='only code near line #num'), | |
924 make_option('-w', '--width', type='int', default=5, | |
925 help='# of lines before and after --lineNo'), | |
217
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
926 make_option('-a', '--all', action='store_true', help="all schemas' objects"), |
218
397979c7f6d6
dumping working but not for wildcards
catherine@Elli.myhome.westell.com
parents:
217
diff
changeset
|
927 make_option('-x', '--exact', action='store_true', help="match object name exactly")]) |
189 | 928 def do_pull(self, arg, opts): |
929 """Displays source code.""" | |
220 | 930 self._pull(arg, opts) |
931 | |
247 | 932 supported_ddl_types = 'CLUSTER, CONTEXT, DATABASE LINK, DIRECTORY, FUNCTION, INDEX, JOB, LIBRARY, MATERIALIZED VIEW, PACKAGE, PACKAGE BODY, PACKAGE SPEC, OPERATOR, PACKAGE, PROCEDURE, SEQUENCE, SYNONYM, TABLE, TRIGGER, VIEW, TYPE, TYPE BODY, XML SCHEMA' |
220 | 933 do_pull.__doc__ += '\n\nSupported DDL types: ' + supported_ddl_types |
934 supported_ddl_types = supported_ddl_types.split(', ') | |
189 | 935 |
224 | 936 def _vc(self, arg, opts, program): |
248 | 937 if not os.path.exists('.%s' % program): |
938 create = raw_input('%s repository not yet in current directory (%s). Create (y/N)? ' % | |
939 (program, os.getcwd())) | |
940 if not create.strip().lower().startswith('y'): | |
941 return | |
224 | 942 subprocess.call([program, 'init']) |
220 | 943 opts.dump = True |
944 self._pull(arg, opts, vc=[program, 'add']) | |
945 subprocess.call([program, 'commit', '-m', '"%s"' % opts.message or 'committed from sqlpython']) | |
946 | |
947 @options([ | |
948 make_option('-f', '--full', action='store_true', help='get dependent objects as well'), | |
949 make_option('-a', '--all', action='store_true', help="all schemas' objects"), | |
950 make_option('-x', '--exact', action='store_true', help="match object name exactly"), | |
951 make_option('-m', '--message', action='store', type='string', dest='message', help="message to save to hg log during commit")]) | |
952 def do_hg(self, arg, opts): | |
953 '''hg (opts) (objects): | |
226 | 954 Stores DDL on disk and puts files under Mercurial version control. |
955 Args specify which objects to store, same format as `ls`.''' | |
224 | 956 self._vc(arg, opts, 'hg') |
189 | 957 |
220 | 958 @options([ |
959 make_option('-f', '--full', action='store_true', help='get dependent objects as well'), | |
960 make_option('-a', '--all', action='store_true', help="all schemas' objects"), | |
961 make_option('-x', '--exact', action='store_true', help="match object name exactly"), | |
962 make_option('-m', '--message', action='store', type='string', dest='message', help="message to save to hg log during commit")]) | |
963 def do_bzr(self, arg, opts): | |
964 '''bzr (opts) (objects): | |
226 | 965 Stores DDL on disk and puts files under Bazaar version control. |
966 Args specify which objects to store, same format as `ls`.''' | |
224 | 967 self._vc(arg, opts, 'bzr') |
220 | 968 |
969 @options([ | |
970 make_option('-f', '--full', action='store_true', help='get dependent objects as well'), | |
971 make_option('-a', '--all', action='store_true', help="all schemas' objects"), | |
972 make_option('-x', '--exact', action='store_true', help="match object name exactly"), | |
973 make_option('-m', '--message', action='store', type='string', dest='message', help="message to save to hg log during commit")]) | |
224 | 974 def do_git(self, arg, opts): |
975 '''git (opts) (objects): | |
226 | 976 Stores DDL on disk and puts files under git version control. |
977 Args specify which objects to store, same format as `ls`.''' | |
224 | 978 self._vc(arg, opts, 'git') |
220 | 979 |
196 | 980 all_users_option = make_option('-a', action='store_const', dest="scope", |
222 | 981 default={'col':'', 'view':'user', 'schemas':'user', 'firstcol': ''}, |
982 const={'col':', owner', 'view':'all', 'schemas':'all', 'firstcol': 'owner, '}, | |
194 | 983 help='Describe all objects (not just my own)') |
984 @options([all_users_option, | |
189 | 985 make_option('-c', '--col', action='store_true', help='find column'), |
986 make_option('-t', '--table', action='store_true', help='find table')]) | |
987 def do_find(self, arg, opts): | |
988 """Finds argument in source code or (with -c) in column definitions.""" | |
193 | 989 |
990 capArg = arg.upper() | |
189 | 991 |
992 if opts.col: | |
222 | 993 sql = "SELECT table_name, column_name %s FROM %s_tab_columns where column_name like '%%%s%%' ORDER BY %s table_name, column_name;" \ |
994 % (opts.scope['col'], opts.scope['view'], capArg, opts.scope['firstcol']) | |
189 | 995 elif opts.table: |
222 | 996 sql = "SELECT table_name %s from %s_tables where table_name like '%%%s%%' ORDER BY %s table_name;" \ |
997 % (opts.scope['col'], opts.scope['view'], capArg, opts.scope['firstcol']) | |
189 | 998 else: |
196 | 999 sql = "SELECT * from %s_source where UPPER(text) like '%%%s%%';" % (opts.scope['view'], capArg) |
200 | 1000 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
193 | 1001 |
286 | 1002 |
1003 @options([all_users_option, | |
1004 make_option('-l', '--long', action='store_true', help='include column #, comments')]) | |
189 | 1005 def do_describe(self, arg, opts): |
1006 "emulates SQL*Plus's DESCRIBE" | |
193 | 1007 target = arg.upper() |
286 | 1008 objnameclause = '' |
1009 if target: | |
1010 objnameclause = "AND object_name LIKE '%%%s%%' " % target | |
1011 object_type, owner, object_name = self.resolve(target) | |
1012 if (not target) or (not object_type): | |
1013 if opts.long: | |
1014 query = """SELECT o.object_name, o.object_type, o.owner, c.comments | |
1015 FROM all_objects o | |
1016 LEFT OUTER JOIN all_tab_comments c ON (o.owner = c.owner AND o.object_name = c.table_name AND o.object_type = 'TABLE') | |
1017 WHERE object_type IN ('TABLE','VIEW','INDEX') | |
1018 %sORDER BY object_name;""" % objnameclause | |
1019 else: | |
1020 query = """SELECT object_name, object_type%s | |
1021 FROM %s_objects | |
1022 WHERE object_type IN ('TABLE','VIEW','INDEX') | |
1023 %sORDER BY object_name;""" % \ | |
1024 (opts.scope['col'], opts.scope['view'], objnameclause) | |
1025 return self.do_select(self.parsed(query, terminator=arg.parsed.terminator or ';', | |
1026 suffix=arg.parsed.suffix)) | |
189 | 1027 self.stdout.write("%s %s.%s\n" % (object_type, owner, object_name)) |
286 | 1028 try: |
1029 if object_type == 'TABLE': | |
309
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
1030 if opts.long: |
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
1031 self._execute(queries['tabComments'], {'table_name':object_name, 'owner':owner}) |
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
1032 self.stdout.write(self.curs.fetchone()[0]) |
286 | 1033 descQ = descQueries[object_type][opts.long] |
1034 else: | |
1035 descQ = descQueries[object_type][opts.long] | |
189 | 1036 for q in descQ: |
204 | 1037 self.do_select(self.parsed(q, terminator=arg.parsed.terminator or ';' , suffix=arg.parsed.suffix), |
286 | 1038 bindVarsIn={'object_name':object_name, 'owner':owner}) |
1039 except KeyError: | |
1040 if object_type == 'PACKAGE': | |
1041 packageContents = self.select_scalar_list(descQueries['PackageObjects'][0], {'package_name':object_name, 'owner':owner}) | |
1042 for packageObj_name in packageContents: | |
1043 self.stdout.write('Arguments to %s\n' % (packageObj_name)) | |
1044 sql = self.parsed(descQueries['PackageObjArgs'][0], terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix) | |
1045 self.do_select(sql, bindVarsIn={'package_name':object_name, 'owner':owner, 'object_name':packageObj_name}) | |
1046 | |
189 | 1047 |
1048 def do_deps(self, arg): | |
286 | 1049 '''Lists all objects that are dependent upon the object.''' |
193 | 1050 target = arg.upper() |
1051 object_type, owner, object_name = self.resolve(target) | |
189 | 1052 if object_type == 'PACKAGE BODY': |
1053 q = "and (type != 'PACKAGE BODY' or name != :object_name)'" | |
1054 object_type = 'PACKAGE' | |
1055 else: | |
1056 q = "" | |
193 | 1057 q = """SELECT name, |
189 | 1058 type |
1059 from user_dependencies | |
1060 where | |
1061 referenced_name like :object_name | |
1062 and referenced_type like :object_type | |
1063 and referenced_owner like :owner | |
193 | 1064 %s;""" % (q) |
200 | 1065 self.do_select(self.parsed(q, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix), |
1066 bindVarsIn={'object_name':object_name, 'object_type':object_type, 'owner':owner}) | |
189 | 1067 |
1068 def do_comments(self, arg): | |
1069 'Prints comments on a table and its columns.' | |
193 | 1070 target = arg.upper() |
1071 object_type, owner, object_name, colName = self.resolve_with_column(target) | |
189 | 1072 if object_type: |
249 | 1073 self._execute(queries['tabComments'], {'table_name':object_name, 'owner':owner}) |
189 | 1074 self.stdout.write("%s %s.%s: %s\n" % (object_type, owner, object_name, self.curs.fetchone()[0])) |
1075 if colName: | |
194 | 1076 sql = queries['oneColComments'] |
1077 bindVarsIn={'owner':owner, 'object_name': object_name, 'column_name': colName} | |
189 | 1078 else: |
194 | 1079 sql = queries['colComments'] |
1080 bindVarsIn={'owner':owner, 'object_name': object_name} | |
200 | 1081 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix), |
1082 bindVarsIn=bindVarsIn) | |
189 | 1083 |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1084 def _resolve(self, identifier): |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1085 parts = identifier.split('.') |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1086 if len(parts) == 2: |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1087 owner, object_name = parts |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1088 object_type = self.select_scalar_list('SELECT object_type FROM all_objects WHERE owner = :owner AND object_name = :object_name', |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1089 {'owner': owner, 'object_name': object_name.upper()} |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1090 )[0] |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1091 elif len(parts) == 1: |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1092 object_name = parts[0] |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1093 self._execute(queries['resolve'], {'objName':object_name.upper()}) |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1094 object_type, object_name, owner = self.curs.fetchone() |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1095 return object_type, owner, object_name |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1096 |
189 | 1097 def resolve(self, identifier): |
1098 """Checks (my objects).name, (my synonyms).name, (public synonyms).name | |
1099 to resolve a database object's name. """ | |
1100 try: | |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1101 return self._resolve(identifier) |
189 | 1102 except (TypeError, IndexError): |
1103 print 'Could not resolve object %s.' % identifier | |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1104 return '', '', '' |
189 | 1105 |
1106 def resolve_with_column(self, identifier): | |
1107 colName = None | |
1108 object_type, owner, object_name = self.resolve(identifier) | |
1109 if not object_type: | |
1110 parts = identifier.split('.') | |
1111 if len(parts) > 1: | |
1112 colName = parts[-1] | |
1113 identifier = '.'.join(parts[:-1]) | |
1114 object_type, owner, object_name = self.resolve(identifier) | |
1115 return object_type, owner, object_name, colName | |
1116 | |
1117 def do_resolve(self, arg): | |
195 | 1118 target = arg.upper() |
1119 self.stdout.write(','.join(self.resolve(target))+'\n') | |
189 | 1120 |
1121 def spoolstop(self): | |
1122 if self.spoolFile: | |
1123 self.stdout = self.stdoutBeforeSpool | |
1124 print 'Finished spooling to ', self.spoolFile.name | |
1125 self.spoolFile.close() | |
1126 self.spoolFile = None | |
1127 | |
1128 def do_spool(self, arg): | |
1129 """spool [filename] - begins redirecting output to FILENAME.""" | |
1130 self.spoolstop() | |
1131 arg = arg.strip() | |
1132 if not arg: | |
1133 arg = 'output.lst' | |
1134 if arg.lower() != 'off': | |
1135 if '.' not in arg: | |
1136 arg = '%s.lst' % arg | |
1137 print 'Sending output to %s (until SPOOL OFF received)' % (arg) | |
1138 self.spoolFile = open(arg, 'w') | |
1139 self.stdout = self.spoolFile | |
1140 | |
1141 def do_write(self, args): | |
281 | 1142 'Obsolete command. Use (query) > outfilename instead.' |
1143 print self.do_write.__doc__ | |
189 | 1144 return |
1145 | |
1146 def do_compare(self, args): | |
1147 """COMPARE query1 TO query2 - uses external tool to display differences. | |
1148 | |
1149 Sorting is recommended to avoid false hits. | |
1150 Will attempt to use a graphical diff/merge tool like kdiff3, meld, or Araxis Merge, | |
1151 if they are installed.""" | |
193 | 1152 #TODO: Update this to use pyparsing |
189 | 1153 fnames = [] |
1154 args2 = args.split(' to ') | |
1155 if len(args2) < 2: | |
1156 print self.do_compare.__doc__ | |
1157 return | |
1158 for n in range(len(args2)): | |
1159 query = args2[n] | |
1160 fnames.append('compare%s.txt' % n) | |
1161 #TODO: update this terminator-stripping | |
1162 if query.rstrip()[-1] != self.terminator: | |
1163 query = '%s%s' % (query, self.terminator) | |
1164 self.onecmd_plus_hooks('%s > %s' % (query, fnames[n])) | |
1165 diffMergeSearcher.invoke(fnames[0], fnames[1]) | |
1166 | |
1167 bufferPosPattern = re.compile('\d+') | |
1168 rangeIndicators = ('-',':') | |
1169 | |
1170 def do_psql(self, arg): | |
1171 '''Shortcut commands emulating psql's backslash commands. | |
1172 | |
1173 \c connect | |
1174 \d desc | |
1175 \e edit | |
1176 \g run | |
1177 \h help | |
1178 \i load | |
1179 \o spool | |
1180 \p list | |
1181 \q quit | |
1182 \w save | |
1183 \db _dir_tablespaces | |
1184 \dd comments | |
1185 \dn _dir_schemas | |
1186 \dt _dir_tables | |
1187 \dv _dir_views | |
1188 \di _dir_indexes | |
1189 \? help psql''' | |
1190 commands = {} | |
1191 for c in self.do_psql.__doc__.splitlines()[2:]: | |
1192 (abbrev, command) = c.split(None, 1) | |
1193 commands[abbrev[1:]] = command | |
1194 words = arg.split(None,1) | |
1195 try: | |
1196 abbrev = words[0] | |
1197 except IndexError: | |
1198 return | |
1199 try: | |
1200 args = words[1] | |
1201 except IndexError: | |
1202 args = '' | |
1203 try: | |
200 | 1204 return self.onecmd('%s %s%s%s' % (commands[abbrev], args, arg.parsed.terminator, arg.parsed.suffix)) |
189 | 1205 except KeyError: |
1206 print 'psql command \%s not yet supported.' % abbrev | |
1207 | |
194 | 1208 @options([all_users_option]) |
189 | 1209 def do__dir_tables(self, arg, opts): |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1210 ''' |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1211 Lists all tables whose names match argument. |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1212 ''' |
194 | 1213 sql = """SELECT table_name, 'TABLE' as type%s FROM %s_tables WHERE table_name LIKE '%%%s%%';""" % \ |
196 | 1214 (opts.scope['col'], opts.scope['view'], arg.upper()) |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1215 if self.sql_echo: |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1216 print sql |
200 | 1217 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
194 | 1218 |
1219 @options([all_users_option]) | |
189 | 1220 def do__dir_views(self, arg, opts): |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1221 ''' |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1222 Lists all views whose names match argument. |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1223 ''' |
194 | 1224 sql = """SELECT view_name, 'VIEW' as type%s FROM %s_views WHERE view_name LIKE '%%%s%%';""" % \ |
196 | 1225 (opts.scope['col'], opts.scope['view'], arg.upper()) |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1226 if self.sql_echo: |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1227 print sql |
200 | 1228 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
194 | 1229 |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1230 def do__dir_indexes(self, arg): |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1231 ''' |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1232 Called with an exact table name, lists the indexes of that table. |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1233 Otherwise, acts as shortcut for `ls index/*(arg)*` |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1234 ''' |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1235 try: |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1236 table_type, table_owner, table_name = self._resolve(arg) |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1237 except TypeError, IndexError: |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1238 return self.onecmd('ls Index/*%s*' % arg) |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1239 sql = """SELECT owner, index_name, index_type FROM all_indexes |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1240 WHERE table_owner = :table_owner |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1241 AND table_name = :table_name; |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1242 ORDER BY owner, index_name""" |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1243 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix), |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1244 bindVarsIn = {'table_owner': table_owner, 'table_name': table_name}) |
189 | 1245 |
1246 def do__dir_tablespaces(self, arg): | |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1247 ''' |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1248 Lists all tablespaces. |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1249 ''' |
194 | 1250 sql = """SELECT tablespace_name, file_name from dba_data_files;""" |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1251 if self.sql_echo: |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1252 print sql |
200 | 1253 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
189 | 1254 |
1255 def do__dir_schemas(self, arg): | |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1256 ''' |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1257 Lists all object owners, together with the number of objects they own. |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1258 ''' |
194 | 1259 sql = """SELECT owner, count(*) AS objects FROM all_objects GROUP BY owner ORDER BY owner;""" |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1260 if self.sql_echo: |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1261 print sql |
200 | 1262 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
189 | 1263 |
1264 def do_head(self, arg): | |
226 | 1265 '''Shortcut for SELECT * FROM <arg>;10 |
1266 The terminator (\\t, \\g, \\x, etc.) and number of rows can | |
1267 be changed as for any other SELECT statement.''' | |
200 | 1268 sql = self.parsed('SELECT * FROM %s;' % arg, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix) |
195 | 1269 sql.parsed['suffix'] = sql.parsed.suffix or '10' |
196 | 1270 self.do_select(self.parsed(sql)) |
189 | 1271 |
1272 def do_print(self, arg): | |
1273 'print VARNAME: Show current value of bind variable VARNAME.' | |
1274 if arg: | |
1275 if arg[0] == ':': | |
1276 arg = arg[1:] | |
1277 try: | |
1278 self.stdout.write(str(self.binds[arg])+'\n') | |
1279 except KeyError: | |
1280 self.stdout.write('No bind variable %s\n' % arg) | |
1281 else: | |
250 | 1282 for (var, val) in sorted(self.binds.items()): |
189 | 1283 print ':%s = %s' % (var, val) |
1284 | |
285 | 1285 def split_on_parser(self, parser, arg): |
1286 try: | |
1287 assigner, startat, endat = parser.scanner.scanString(arg).next() | |
1288 return (arg[:startat].strip(), arg[endat:].strip()) | |
1289 except StopIteration: | |
1290 return ''.join(arg.split()[:1]), '' | |
1291 | |
189 | 1292 assignmentScanner = Parser(pyparsing.Literal(':=') ^ '=') |
285 | 1293 def interpret_variable_assignment(self, arg): |
1294 ''' | |
1295 Accepts strings like `foo = 'bar'` or `baz := 22`, returning Python | |
1296 variables as appropriate | |
1297 ''' | |
1298 var, val = self.split_on_parser(self.assignmentScanner, arg) | |
1299 if not var: | |
1300 return None, None | |
1301 if (len(val) > 1) and ((val[0] == val[-1] == "'") or (val[0] == val[-1] == '"')): | |
1302 return var, val[1:-1] | |
1303 try: | |
1304 return var, int(val) | |
1305 except ValueError: | |
1306 try: | |
1307 return var, float(val) | |
1308 except ValueError: | |
1309 # use the conversions implicit in cx_Oracle's select to | |
1310 # cast the value into an appropriate type (dates, for instance) | |
1311 try: | |
1312 self.curs.execute('SELECT %s FROM dual' % val) | |
1313 return var, self.curs.fetchone()[0] | |
1314 except cx_Oracle.DatabaseError: | |
1315 return var, val # we give up and assume it's a string | |
1316 | |
189 | 1317 def do_setbind(self, arg): |
285 | 1318 '''Sets or shows values of bind (`:`) variables.''' |
189 | 1319 if not arg: |
1320 return self.do_print(arg) | |
285 | 1321 var, val = self.interpret_variable_assignment(arg) |
1322 if val: | |
1323 self.binds[var] = val | |
1324 else: | |
1325 return self.do_print(var) | |
189 | 1326 |
285 | 1327 def do_define(self, arg): |
1328 '''Sets or shows values of substitution (`&`) variables.''' | |
1329 if not arg: | |
1330 for (substvar, val) in sorted(self.substvars.items()): | |
1331 print 'DEFINE %s = "%s" (%s)' % (substvar, val, type(val)) | |
1332 var, val = self.interpret_variable_assignment(arg) | |
1333 if val: | |
1334 self.substvars[var] = val | |
1335 else: | |
1336 if var in self.substvars: | |
1337 print 'DEFINE %s = "%s" (%s)' % (var, self.substvars[var], type(self.substvars[var])) | |
1338 | |
189 | 1339 def do_exec(self, arg): |
213 | 1340 if arg.startswith(':'): |
189 | 1341 self.do_setbind(arg[1:]) |
1342 else: | |
1343 varsUsed = findBinds(arg, self.binds, {}) | |
1344 try: | |
1345 self.curs.execute('begin\n%s;end;' % arg, varsUsed) | |
1346 except Exception, e: | |
1347 print e | |
1348 | |
1349 ''' | |
1350 Fails: | |
1351 select n into :n from test;''' | |
1352 | |
1353 def anon_plsql(self, line1): | |
1354 lines = [line1] | |
1355 while True: | |
247 | 1356 line = self.pseudo_raw_input(self.continuation_prompt) |
241 | 1357 if line == 'EOF': |
1358 return | |
189 | 1359 if line.strip() == '/': |
1360 try: | |
1361 self.curs.execute('\n'.join(lines)) | |
1362 except Exception, e: | |
1363 print e | |
1364 return | |
1365 lines.append(line) | |
1366 | |
1367 def do_begin(self, arg): | |
281 | 1368 ''' |
1369 PL/SQL blocks can be used normally in sqlpython, though enclosing statements in | |
1370 REMARK BEGIN... REMARK END statements can help with parsing speed.''' | |
189 | 1371 self.anon_plsql('begin ' + arg) |
1372 | |
1373 def do_declare(self, arg): | |
1374 self.anon_plsql('declare ' + arg) | |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1375 |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1376 def _ls_statement(self, arg, opts): |
189 | 1377 if arg: |
280
8ea39093ddf2
struggling with catching terminator after /*
catherine@dellzilla
parents:
277
diff
changeset
|
1378 target = arg.upper().replace('*','%') |
8ea39093ddf2
struggling with catching terminator after /*
catherine@dellzilla
parents:
277
diff
changeset
|
1379 where = """\nWHERE object_type || '/' || object_name LIKE '%s' |
8ea39093ddf2
struggling with catching terminator after /*
catherine@dellzilla
parents:
277
diff
changeset
|
1380 OR object_name LIKE '%s'""" % (target, target) |
189 | 1381 else: |
1382 where = '' | |
1383 if opts.all: | |
1384 whose = 'all' | |
1385 objname = "owner || '.' || object_name" | |
1386 else: | |
1387 whose = 'user' | |
1388 objname = 'object_name' | |
232
52adb09094b3
fixed bugs in VC introduced by sort-order options
catherine@dellzilla
parents:
230
diff
changeset
|
1389 if hasattr(opts, 'long') and opts.long: |
228 | 1390 moreColumns = ', status, last_ddl_time' |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1391 else: |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1392 moreColumns = '' |
227 | 1393 |
1394 # 'Normal' sort order is DATE DESC (maybe), object type ASC, object name ASC | |
244 | 1395 sortdirection = (hasattr(opts, 'reverse') and opts.reverse and 'DESC') or 'ASC' |
227 | 1396 orderby = 'object_type %s, object_name %s' % (sortdirection, sortdirection) |
232
52adb09094b3
fixed bugs in VC introduced by sort-order options
catherine@dellzilla
parents:
230
diff
changeset
|
1397 if hasattr(opts, 'timesort') and opts.timesort: |
52adb09094b3
fixed bugs in VC introduced by sort-order options
catherine@dellzilla
parents:
230
diff
changeset
|
1398 orderby = 'last_ddl_time %s, %s' % (('ASC' if hasattr(opts, 'reverse') and opts.reverse else 'DESC'), orderby) |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1399 return {'objname': objname, 'moreColumns': moreColumns, |
227 | 1400 'whose': whose, 'where': where, 'orderby': orderby} |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1401 |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1402 def resolve_many(self, arg, opts): |
217
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
1403 opts.long = False |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1404 clauses = self._ls_statement(arg, opts) |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1405 if opts.all: |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1406 clauses['owner'] = 'owner' |
189 | 1407 else: |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1408 clauses['owner'] = 'user' |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1409 statement = '''SELECT %(owner)s, object_type, object_name |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1410 FROM %(whose)s_objects %(where)s |
217
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
1411 ORDER BY object_type, object_name''' % clauses |
249 | 1412 self._execute(statement) |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1413 return self.curs.fetchall() |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1414 |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1415 @options([make_option('-l', '--long', action='store_true', help='long descriptions'), |
217
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
1416 make_option('-a', '--all', action='store_true', help="all schemas' objects"), |
227 | 1417 make_option('-t', '--timesort', action='store_true', help="Sort by last_ddl_time"), |
280
8ea39093ddf2
struggling with catching terminator after /*
catherine@dellzilla
parents:
277
diff
changeset
|
1418 make_option('-r', '--reverse', action='store_true', help="Reverse order while sorting")]) |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1419 def do_ls(self, arg, opts): |
281 | 1420 ''' |
1421 Lists objects as through they were in an {object_type}/{object_name} UNIX | |
1422 directory structure. `*` and `%` may be used as wildcards. | |
1423 ''' | |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1424 statement = '''SELECT object_type || '/' || %(objname)s AS name %(moreColumns)s |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1425 FROM %(whose)s_objects %(where)s |
227 | 1426 ORDER BY %(orderby)s;''' % self._ls_statement(arg, opts) |
200 | 1427 self.do_select(self.parsed(statement, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
189 | 1428 |
1429 @options([make_option('-i', '--ignore-case', dest='ignorecase', action='store_true', help='Case-insensitive search')]) | |
1430 def do_grep(self, arg, opts): | |
281 | 1431 """grep {target} {table} [{table2,...}] - search for {target} in any of {table}'s fields""" |
189 | 1432 |
195 | 1433 targetnames = arg.split() |
189 | 1434 pattern = targetnames.pop(0) |
1435 targets = [] | |
1436 for target in targetnames: | |
1437 if '*' in target: | |
310 | 1438 self._execute("""SELECT owner, object_name FROM all_objects |
1439 WHERE object_type IN ('TABLE','VIEW') | |
1440 AND object_name LIKE '%s'%s""" % | |
1441 (target.upper().replace('*','%'), arg.parsed.terminator)) | |
189 | 1442 for row in self.curs: |
1443 targets.append('%s.%s' % row) | |
1444 else: | |
1445 targets.append(target) | |
1446 for target in targets: | |
1447 print target | |
1448 target = target.rstrip(';') | |
1449 try: | |
249 | 1450 self._execute('select * from %s where 1=0' % target) # just to fill description |
189 | 1451 if opts.ignorecase: |
1452 sql = ' or '.join("LOWER(%s) LIKE '%%%s%%'" % (d[0], pattern.lower()) for d in self.curs.description) | |
1453 else: | |
1454 sql = ' or '.join("%s LIKE '%%%s%%'" % (d[0], pattern) for d in self.curs.description) | |
200 | 1455 sql = self.parsed('SELECT * FROM %s WHERE %s;' % (target, sql), terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix) |
199
09592342a33d
ugh - parsing stripping command causes real trouble
catherine@dellzilla
parents:
198
diff
changeset
|
1456 self.do_select(sql) |
189 | 1457 except Exception, e: |
1458 print e | |
1459 import traceback | |
1460 traceback.print_exc(file=sys.stdout) | |
1461 | |
249 | 1462 def _execute(self, sql, bindvars={}): |
1463 if self.sql_echo: | |
1464 print sql | |
1465 self.curs.execute(sql, bindvars) | |
1466 | |
286 | 1467 #@options([make_option('-l', '--long', action='store_true', |
1468 # help='Wordy, easy-to-understand form'),]) | |
189 | 1469 def do_refs(self, arg): |
286 | 1470 '''Lists referential integrity (foreign key constraints) on an object or referring to it.''' |
211 | 1471 |
1472 if not arg.strip(): | |
1473 print 'Usage: refs (table name)' | |
190 | 1474 result = [] |
205 | 1475 (type, owner, table_name) = self.resolve(arg.upper()) |
249 | 1476 sql = """SELECT constraint_name, r_owner, r_constraint_name |
191 | 1477 FROM all_constraints |
1478 WHERE constraint_type = 'R' | |
1479 AND owner = :owner | |
249 | 1480 AND table_name = :table_name""" |
1481 self._execute(sql, {"owner": owner, "table_name": table_name}) | |
191 | 1482 for (constraint_name, remote_owner, remote_constraint_name) in self.curs.fetchall(): |
1483 result.append('%s on %s.%s:' % (constraint_name, owner, table_name)) | |
249 | 1484 |
1485 self._execute("SELECT column_name FROM all_cons_columns WHERE owner = :owner AND constraint_name = :constraint_name ORDER BY position", | |
1486 {'constraint_name': constraint_name, 'owner': owner}) | |
191 | 1487 result.append(" (%s)" % (",".join(col[0] for col in self.curs.fetchall()))) |
249 | 1488 self._execute("SELECT table_name FROM all_constraints WHERE owner = :remote_owner AND constraint_name = :remote_constraint_name", |
1489 {'remote_owner': remote_owner, 'remote_constraint_name': remote_constraint_name}) | |
191 | 1490 remote_table_name = self.curs.fetchone()[0] |
1491 result.append("must be in %s:" % (remote_table_name)) | |
249 | 1492 self._execute("SELECT column_name FROM all_cons_columns WHERE owner = :remote_owner AND constraint_name = :remote_constraint_name ORDER BY position", |
191 | 1493 {'remote_constraint_name': remote_constraint_name, 'remote_owner': remote_owner}) |
1494 result.append(' (%s)\n' % (",".join(col[0] for col in self.curs.fetchall()))) | |
1495 remote_table_name = table_name | |
1496 remote_owner = owner | |
249 | 1497 self._execute("""SELECT owner, constraint_name, table_name, r_constraint_name |
191 | 1498 FROM all_constraints |
1499 WHERE (r_owner, r_constraint_name) IN | |
1500 ( SELECT owner, constraint_name | |
1501 FROM all_constraints | |
192
6bb8a112af6b
accept special terminators on most anything
catherine@dellzilla
parents:
191
diff
changeset
|
1502 WHERE table_name = :remote_table_name |
191 | 1503 AND owner = :remote_owner )""", |
1504 {'remote_table_name': remote_table_name, 'remote_owner': remote_owner}) | |
1505 for (owner, constraint_name, table_name, remote_constraint_name) in self.curs.fetchall(): | |
1506 result.append('%s on %s.%s:' % (constraint_name, owner, table_name)) | |
249 | 1507 self._execute("SELECT column_name FROM all_cons_columns WHERE owner = :owner AND constraint_name = :constraint_name ORDER BY position", |
191 | 1508 {'constraint_name': constraint_name, 'owner': owner}) |
1509 result.append(" (%s)" % (",".join(col[0] for col in self.curs.fetchall()))) | |
249 | 1510 self._execute("SELECT table_name FROM all_constraints WHERE owner = :remote_owner AND constraint_name = :remote_constraint_name", |
191 | 1511 {'remote_owner': remote_owner, 'remote_constraint_name': remote_constraint_name}) |
1512 remote_table_name = self.curs.fetchone()[0] | |
1513 result.append("must be in %s:" % (remote_table_name)) | |
249 | 1514 self._execute("SELECT column_name FROM all_cons_columns WHERE owner = :remote_owner AND constraint_name = :remote_constraint_name ORDER BY position", |
191 | 1515 {'remote_constraint_name': remote_constraint_name, 'remote_owner': remote_owner}) |
1516 result.append(' (%s)\n' % (",".join(col[0] for col in self.curs.fetchall()))) | |
1517 self.stdout.write('\n'.join(result) + "\n") | |
190 | 1518 |
189 | 1519 def _test(): |
1520 import doctest | |
1521 doctest.testmod() | |
1522 | |
1523 if __name__ == "__main__": | |
1524 "Silent return implies that all unit tests succeeded. Use -v to see details." | |
1525 _test() | |
198
b2d8bf5f89db
merged with changes from work
catherine@Elli.myhome.westell.com
parents:
196
diff
changeset
|
1526 if __name__ == "__main__": |
b2d8bf5f89db
merged with changes from work
catherine@Elli.myhome.westell.com
parents:
196
diff
changeset
|
1527 "Silent return implies that all unit tests succeeded. Use -v to see details." |
b2d8bf5f89db
merged with changes from work
catherine@Elli.myhome.westell.com
parents:
196
diff
changeset
|
1528 _test() |