Mercurial > sqlpython
annotate sqlpython/sqlpyPlus.py @ 194:932893dcf0c9
useTerminatorFrom
author | catherine@dellzilla |
---|---|
date | Mon, 24 Nov 2008 16:26:11 -0500 |
parents | 01548a399ccf |
children | 4a3af9ac215f |
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 """ | |
26 import sys, os, re, sqlpython, cx_Oracle, pyparsing, re, completion, datetime, pickle | |
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 | |
32 except: | |
33 pass | |
34 | |
35 descQueries = { | |
36 'TABLE': (""" | |
193 | 37 SELECT atc.column_name, |
189 | 38 CASE atc.nullable WHEN 'Y' THEN 'NULL' ELSE 'NOT NULL' END "Null?", |
39 atc.data_type || | |
40 CASE atc.data_type WHEN 'DATE' THEN '' | |
41 ELSE '(' || | |
42 CASE atc.data_type WHEN 'NUMBER' THEN TO_CHAR(atc.data_precision) || | |
43 CASE atc.data_scale WHEN 0 THEN '' | |
44 ELSE ',' || TO_CHAR(atc.data_scale) END | |
45 ELSE TO_CHAR(atc.data_length) END | |
46 END || | |
47 CASE atc.data_type WHEN 'DATE' THEN '' ELSE ')' END | |
48 data_type | |
49 FROM all_tab_columns atc | |
50 WHERE atc.table_name = :object_name | |
51 AND atc.owner = :owner | |
193 | 52 ORDER BY atc.column_id;""",), |
189 | 53 'PROCEDURE': (""" |
193 | 54 SELECT NVL(argument_name, 'Return Value') argument_name, |
189 | 55 data_type, |
56 in_out, | |
57 default_value | |
58 FROM all_arguments | |
59 WHERE object_name = :object_name | |
60 AND owner = :owner | |
61 AND package_name IS NULL | |
193 | 62 ORDER BY sequence;""",), |
189 | 63 'PackageObjects':(""" |
64 SELECT DISTINCT object_name | |
65 FROM all_arguments | |
66 WHERE package_name = :package_name | |
67 AND owner = :owner""",), | |
68 'PackageObjArgs':(""" | |
193 | 69 SELECT object_name, |
189 | 70 argument_name, |
71 data_type, | |
72 in_out, | |
73 default_value | |
74 FROM all_arguments | |
75 WHERE package_name = :package_name | |
76 AND object_name = :object_name | |
77 AND owner = :owner | |
78 AND argument_name IS NOT NULL | |
193 | 79 ORDER BY sequence;""",), |
189 | 80 'TRIGGER':(""" |
193 | 81 SELECT description |
189 | 82 FROM all_triggers |
83 WHERE owner = :owner | |
193 | 84 AND trigger_name = :object_name; |
189 | 85 """, |
86 """ | |
193 | 87 SELECT table_owner, |
189 | 88 base_object_type, |
89 table_name, | |
90 column_name, | |
91 when_clause, | |
92 status, | |
93 action_type, | |
94 crossedition | |
95 FROM all_triggers | |
96 WHERE owner = :owner | |
97 AND trigger_name = :object_name | |
98 \\t | |
99 """, | |
100 ), | |
101 'INDEX':(""" | |
193 | 102 SELECT index_type, |
189 | 103 table_owner, |
104 table_name, | |
105 table_type, | |
106 uniqueness, | |
107 compression, | |
108 partitioned, | |
109 temporary, | |
110 generated, | |
111 secondary, | |
112 dropped, | |
113 visibility | |
114 FROM all_indexes | |
115 WHERE owner = :owner | |
116 AND index_name = :object_name | |
117 \\t | |
118 """,) | |
119 } | |
120 descQueries['VIEW'] = descQueries['TABLE'] | |
121 descQueries['FUNCTION'] = descQueries['PROCEDURE'] | |
122 | |
123 queries = { | |
124 'resolve': """ | |
125 SELECT object_type, object_name, owner FROM ( | |
126 SELECT object_type, object_name, user owner, 1 priority | |
127 FROM user_objects | |
128 WHERE object_name = :objName | |
129 UNION ALL | |
130 SELECT ao.object_type, ao.object_name, ao.owner, 2 priority | |
131 FROM all_objects ao | |
132 JOIN user_synonyms us ON (us.table_owner = ao.owner AND us.table_name = ao.object_name) | |
133 WHERE us.synonym_name = :objName | |
134 AND ao.object_type != 'SYNONYM' | |
135 UNION ALL | |
136 SELECT ao.object_type, ao.object_name, ao.owner, 3 priority | |
137 FROM all_objects ao | |
138 JOIN all_synonyms asyn ON (asyn.table_owner = ao.owner AND asyn.table_name = ao.object_name) | |
139 WHERE asyn.synonym_name = :objName | |
140 AND ao.object_type != 'SYNONYM' | |
141 AND asyn.owner = 'PUBLIC' | |
142 UNION ALL | |
143 SELECT 'DIRECTORY' object_type, dir.directory_name, dir.owner, 6 priority | |
144 FROM all_directories dir | |
145 WHERE dir.directory_name = :objName | |
146 UNION ALL | |
147 SELECT 'DATABASE LINK' object_type, db_link, owner, 7 priority | |
148 FROM all_db_links dbl | |
149 WHERE dbl.db_link = :objName | |
150 ) ORDER BY priority ASC, | |
151 length(object_type) ASC, | |
152 object_type DESC""", # preference: PACKAGE before PACKAGE BODY, TABLE before INDEX | |
153 'tabComments': """ | |
154 SELECT comments | |
155 FROM all_tab_comments | |
156 WHERE owner = :owner | |
157 AND table_name = :table_name""", | |
158 'colComments': """ | |
193 | 159 SELECT |
189 | 160 atc.column_name, |
161 acc.comments | |
162 FROM all_tab_columns atc | |
163 JOIN all_col_comments acc ON (atc.owner = acc.owner and atc.table_name = acc.table_name and atc.column_name = acc.column_name) | |
164 WHERE atc.table_name = :object_name | |
165 AND atc.owner = :owner | |
193 | 166 ORDER BY atc.column_id;""", |
189 | 167 'oneColComments': """ |
193 | 168 SELECTatc.column_name, |
189 | 169 acc.comments |
170 FROM all_tab_columns atc | |
171 JOIN all_col_comments acc ON (atc.owner = acc.owner and atc.table_name = acc.table_name and atc.column_name = acc.column_name) | |
172 WHERE atc.table_name = :object_name | |
173 AND atc.owner = :owner | |
174 AND acc.column_name = :column_name | |
193 | 175 ORDER BY atc.column_id;""", |
189 | 176 #thanks to Senora.pm for "refs" |
177 'refs': """ | |
178 NULL referenced_by, | |
179 c2.table_name references, | |
180 c1.constraint_name constraint | |
181 FROM | |
182 user_constraints c1, | |
183 user_constraints c2 | |
184 WHERE | |
185 c1.table_name = :object_name | |
186 and c1.constraint_type ='R' | |
187 and c1.r_constraint_name = c2.constraint_name | |
188 and c1.r_owner = c2.owner | |
189 and c1.owner = :owner | |
190 UNION | |
191 SELECT c1.table_name referenced_by, | |
192 NULL references, | |
193 c1.constraint_name constraint | |
194 FROM | |
195 user_constraints c1, | |
196 user_constraints c2 | |
197 WHERE | |
198 c2.table_name = :object_name | |
199 and c1.constraint_type ='R' | |
200 and c1.r_constraint_name = c2.constraint_name | |
201 and c1.r_owner = c2.owner | |
202 and c1.owner = :owner | |
203 """ | |
204 } | |
205 | |
206 if float(sys.version[:3]) < 2.3: | |
207 def enumerate(lst): | |
208 return zip(range(len(lst)), lst) | |
209 | |
210 class SoftwareSearcher(object): | |
211 def __init__(self, softwareList, purpose): | |
212 self.softwareList = softwareList | |
213 self.purpose = purpose | |
214 self.software = None | |
215 def invoke(self, *args): | |
216 if not self.software: | |
217 (self.software, self.invokeString) = self.find() | |
218 argTuple = tuple([self.software] + list(args)) | |
219 os.system(self.invokeString % argTuple) | |
220 def find(self): | |
221 if self.purpose == 'text editor': | |
222 software = os.environ.get('EDITOR') | |
223 if software: | |
224 return (software, '%s %s') | |
225 for (n, (software, invokeString)) in enumerate(self.softwareList): | |
226 if os.path.exists(software): | |
227 if n > (len(self.softwareList) * 0.7): | |
228 print """ | |
229 | |
230 Using %s. Note that there are better options available for %s, | |
231 but %s couldn't find a better one in your PATH. | |
232 Feel free to open up %s | |
233 and customize it to find your favorite %s program. | |
234 | |
235 """ % (software, self.purpose, __file__, __file__, self.purpose) | |
236 return (software, invokeString) | |
237 stem = os.path.split(software)[1] | |
238 for p in os.environ['PATH'].split(os.pathsep): | |
239 if os.path.exists(os.sep.join([p, stem])): | |
240 return (stem, invokeString) | |
241 raise (OSError, """Could not find any %s programs. You will need to install one, | |
242 or customize %s to make it aware of yours. | |
243 Looked for these programs: | |
244 %s""" % (self.purpose, __file__, "\n".join([s[0] for s in self.softwareList]))) | |
245 #v2.4: %s""" % (self.purpose, __file__, "\n".join(s[0] for s in self.softwareList))) | |
246 | |
247 softwareLists = { | |
248 'diff/merge': [ | |
249 ('/usr/bin/meld',"%s %s %s"), | |
250 ('/usr/bin/kdiff3',"%s %s %s"), | |
251 (r'C:\Program Files\Araxis\Araxis Merge v6.5\Merge.exe','"%s" %s %s'), | |
252 (r'C:\Program Files\TortoiseSVN\bin\TortoiseMerge.exe', '"%s" /base:"%s" /mine:"%s"'), | |
253 ('FileMerge','%s %s %s'), | |
254 ('kompare','%s %s %s'), | |
255 ('WinMerge','%s %s %s'), | |
256 ('xxdiff','%s %s %s'), | |
257 ('fldiff','%s %s %s'), | |
258 ('gtkdiff','%s %s %s'), | |
259 ('tkdiff','%s %s %s'), | |
260 ('gvimdiff','%s %s %s'), | |
261 ('diff',"%s %s %s"), | |
262 (r'c:\windows\system32\comp.exe',"%s %s %s")], | |
263 'text editor': [ | |
264 ('gedit', '%s %s'), | |
265 ('textpad', '%s %s'), | |
266 ('notepad.exe', '%s %s'), | |
267 ('pico', '%s %s'), | |
268 ('emacs', '%s %s'), | |
269 ('vim', '%s %s'), | |
270 ('vi', '%s %s'), | |
271 ('ed', '%s %s'), | |
272 ('edlin', '%s %s') | |
273 ] | |
274 } | |
275 | |
276 diffMergeSearcher = SoftwareSearcher(softwareLists['diff/merge'],'diff/merge') | |
277 editSearcher = SoftwareSearcher(softwareLists['text editor'], 'text editor') | |
278 editor = os.environ.get('EDITOR') | |
279 if editor: | |
280 editSearcher.find = lambda: (editor, "%s %s") | |
281 | |
282 class CaselessDict(dict): | |
283 """dict with case-insensitive keys. | |
284 | |
285 Posted to ASPN Python Cookbook by Jeff Donner - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66315""" | |
286 def __init__(self, other=None): | |
287 if other: | |
288 # Doesn't do keyword args | |
289 if isinstance(other, dict): | |
290 for k,v in other.items(): | |
291 dict.__setitem__(self, k.lower(), v) | |
292 else: | |
293 for k,v in other: | |
294 dict.__setitem__(self, k.lower(), v) | |
295 def __getitem__(self, key): | |
296 return dict.__getitem__(self, key.lower()) | |
297 def __setitem__(self, key, value): | |
298 dict.__setitem__(self, key.lower(), value) | |
299 def __contains__(self, key): | |
300 return dict.__contains__(self, key.lower()) | |
301 def has_key(self, key): | |
302 return dict.has_key(self, key.lower()) | |
303 def get(self, key, def_val=None): | |
304 return dict.get(self, key.lower(), def_val) | |
305 def setdefault(self, key, def_val=None): | |
306 return dict.setdefault(self, key.lower(), def_val) | |
307 def update(self, other): | |
308 for k,v in other.items(): | |
309 dict.__setitem__(self, k.lower(), v) | |
310 def fromkeys(self, iterable, value=None): | |
311 d = CaselessDict() | |
312 for k in iterable: | |
313 dict.__setitem__(d, k.lower(), value) | |
314 return d | |
315 def pop(self, key, def_val=None): | |
316 return dict.pop(self, key.lower(), def_val) | |
317 | |
318 class Parser(object): | |
319 comment_def = "--" + pyparsing.ZeroOrMore(pyparsing.CharsNotIn("\n")) | |
320 def __init__(self, scanner, retainSeparator=True): | |
321 self.scanner = scanner | |
322 self.scanner.ignore(pyparsing.sglQuotedString) | |
323 self.scanner.ignore(pyparsing.dblQuotedString) | |
324 self.scanner.ignore(self.comment_def) | |
325 self.scanner.ignore(pyparsing.cStyleComment) | |
326 self.retainSeparator = retainSeparator | |
327 def separate(self, txt): | |
328 itms = [] | |
329 for (sqlcommand, start, end) in self.scanner.scanString(txt): | |
330 if sqlcommand: | |
331 if type(sqlcommand[0]) == pyparsing.ParseResults: | |
332 if self.retainSeparator: | |
333 itms.append("".join(sqlcommand[0])) | |
334 else: | |
335 itms.append(sqlcommand[0][0]) | |
336 else: | |
337 if sqlcommand[0]: | |
338 itms.append(sqlcommand[0]) | |
339 return itms | |
340 | |
341 bindScanner = Parser(pyparsing.Literal(':') + pyparsing.Word( pyparsing.alphanums + "_$#" )) | |
342 | |
343 def findBinds(target, existingBinds, givenBindVars = {}): | |
344 result = givenBindVars | |
345 for finding, startat, endat in bindScanner.scanner.scanString(target): | |
346 varname = finding[1] | |
347 try: | |
348 result[varname] = existingBinds[varname] | |
349 except KeyError: | |
350 if not givenBindVars.has_key(varname): | |
351 print 'Bind variable %s not defined.' % (varname) | |
352 return result | |
353 | |
192
6bb8a112af6b
accept special terminators on most anything
catherine@dellzilla
parents:
191
diff
changeset
|
354 def copyStatementEnding(newString, parsedOldStatement): |
6bb8a112af6b
accept special terminators on most anything
catherine@dellzilla
parents:
191
diff
changeset
|
355 return newString + (parsedOldStatement.terminator or ';') + str(parsedOldStatement.rowlimit or '') |
6bb8a112af6b
accept special terminators on most anything
catherine@dellzilla
parents:
191
diff
changeset
|
356 |
189 | 357 class sqlpyPlus(sqlpython.sqlpython): |
358 defaultExtension = 'sql' | |
359 sqlpython.sqlpython.shortcuts.update({':': 'setbind', | |
360 '\\': 'psql', | |
361 '@': '_load'}) | |
362 multilineCommands = '''select insert update delete tselect | |
363 create drop alter _multiline_comment'''.split() | |
364 sqlpython.sqlpython.noSpecialParse.append('spool') | |
365 commentGrammars = pyparsing.Or([pyparsing.Literal('--') + pyparsing.restOfLine, pyparsing.cStyleComment]) | |
366 defaultFileName = 'afiedt.buf' | |
367 def __init__(self): | |
368 sqlpython.sqlpython.__init__(self) | |
369 self.binds = CaselessDict() | |
370 self.settable = 'autobind commit_on_exit echo maxfetch maxtselctrows timeout'.split() | |
371 # settables must be lowercase | |
372 self.stdoutBeforeSpool = sys.stdout | |
373 self.spoolFile = None | |
374 self.autobind = False | |
375 def default(self, arg): | |
376 sqlpython.sqlpython.default(self, arg) | |
377 | |
378 # overrides cmd's parseline | |
379 def parseline(self, line): | |
380 """Parse the line into a command name and a string containing | |
381 the arguments. Returns a tuple containing (command, args, line). | |
382 'command' and 'args' may be None if the line couldn't be parsed. | |
383 Overrides cmd.cmd.parseline to accept variety of shortcuts..""" | |
384 | |
385 cmd, arg, line = sqlpython.sqlpython.parseline(self, line) | |
386 if cmd in ('select', 'sleect', 'insert', 'update', 'delete', 'describe', | |
387 'desc', 'comments', 'pull', 'refs', 'desc', 'triggers', 'find') \ | |
388 and not hasattr(self, 'curs'): | |
389 print 'Not connected.' | |
390 return '', '', '' | |
391 return cmd, arg, line | |
392 | |
393 do__load = Cmd.do_load | |
394 | |
395 def onecmd_plus_hooks(self, line): | |
396 line = self.precmd(line) | |
397 stop = self.onecmd(line) | |
398 stop = self.postcmd(stop, line) | |
399 | |
400 def do_shortcuts(self,arg): | |
401 """Lists available first-character shortcuts | |
402 (i.e. '!dir' is equivalent to 'shell dir')""" | |
403 for (scchar, scto) in self.shortcuts.items(): | |
404 print '%s: %s' % (scchar, scto) | |
405 | |
406 def colnames(self): | |
407 return [d[0] for d in curs.description] | |
408 | |
409 def sql_format_itm(self, itm, needsquotes): | |
410 if itm is None: | |
411 return 'NULL' | |
412 if needsquotes: | |
413 return "'%s'" % str(itm) | |
414 return str(itm) | |
415 tableNameFinder = re.compile(r'from\s+([\w$#_"]+)', re.IGNORECASE | re.MULTILINE | re.DOTALL) | |
416 inputStatementFormatters = { | |
417 cx_Oracle.STRING: "'%s'", | |
418 cx_Oracle.DATETIME: "TO_DATE('%s', 'YYYY-MM-DD HH24:MI:SS')"} | |
419 inputStatementFormatters[cx_Oracle.CLOB] = inputStatementFormatters[cx_Oracle.STRING] | |
420 inputStatementFormatters[cx_Oracle.TIMESTAMP] = inputStatementFormatters[cx_Oracle.DATETIME] | |
421 def output(self, outformat, rowlimit): | |
422 self.tblname = self.tableNameFinder.search(self.curs.statement).group(1) | |
423 self.colnames = [d[0] for d in self.curs.description] | |
424 if outformat in output_templates: | |
425 self.colnamelen = max(len(colname) for colname in self.colnames) | |
426 self.coltypes = [d[1] for d in self.curs.description] | |
427 self.formatters = [self.inputStatementFormatters.get(typ, '%s') for typ in self.coltypes] | |
428 result = output_templates[outformat].generate(**self.__dict__) | |
429 elif outformat == '\\t': # transposed | |
430 rows = [self.colnames] | |
431 rows.extend(list(self.rows)) | |
432 transpr = [[rows[y][x] for y in range(len(rows))]for x in range(len(rows[0]))] # matrix transpose | |
433 newdesc = [['ROW N.'+str(y),10] for y in range(len(rows))] | |
434 for x in range(len(self.curs.description)): | |
435 if str(self.curs.description[x][1]) == "<type 'cx_Oracle.BINARY'>": # handles RAW columns | |
436 rname = transpr[x][0] | |
437 transpr[x] = map(binascii.b2a_hex, transpr[x]) | |
438 transpr[x][0] = rname | |
439 newdesc[0][0] = 'COLUMN NAME' | |
440 result = '\n' + sqlpython.pmatrix(transpr,newdesc) | |
441 elif outformat in ('\\l', '\\L', '\\p', '\\b'): | |
442 plot = Plot() | |
443 plot.build(self, outformat) | |
444 plot.shelve() | |
445 plot.draw() | |
446 return '' | |
447 else: | |
448 result = sqlpython.pmatrix(self.rows, self.curs.description, self.maxfetch) | |
449 return result | |
450 | |
451 legalOracle = re.compile('[a-zA-Z_$#]') | |
452 | |
453 def select_scalar_list(self, sql, binds={}): | |
454 self.curs.execute(sql, binds) | |
455 return [r[0] for r in self.curs.fetchall()] | |
456 | |
457 columnNameRegex = re.compile( | |
458 r'select\s+(.*)from', | |
459 re.IGNORECASE | re.DOTALL | re.MULTILINE) | |
460 def completedefault(self, text, line, begidx, endidx): | |
461 segment = completion.whichSegment(line) | |
462 text = text.upper() | |
463 completions = [] | |
464 if segment == 'select': | |
465 stmt = "SELECT column_name FROM user_tab_columns WHERE column_name LIKE '%s%%'" | |
466 completions = self.select_scalar_list(stmt % (text)) | |
467 if not completions: | |
468 stmt = "SELECT column_name FROM all_tab_columns WHERE column_name LIKE '%s%%'" | |
469 completions = self.select_scalar_list(stmt % (text)) | |
470 if segment == 'from': | |
471 columnNames = self.columnNameRegex.search(line) | |
472 if columnNames: | |
473 columnNames = columnNames.group(1) | |
474 columnNames = [c.strip().upper() for c in columnNames.split(',')] | |
475 stmt1 = "SELECT table_name FROM all_tab_columns WHERE column_name = '%s' AND table_name LIKE '%s%%'" | |
476 for columnName in columnNames: | |
477 # and if columnName is * ? | |
478 completions.extend(self.select_scalar_list(stmt1 % (columnName, text))) | |
479 if segment in ('from', 'update', 'insert into') and (not completions): | |
480 stmt = "SELECT table_name FROM user_tables WHERE table_name LIKE '%s%%'" | |
481 completions = self.select_scalar_list(stmt % (text)) | |
482 if not completions: | |
483 stmt = """SELECT table_name FROM user_tables WHERE table_name LIKE '%s%%' | |
484 UNION | |
485 SELECT DISTINCT owner FROM all_tables WHERE owner LIKE '%%%s'""" | |
486 completions = self.select_scalar_list(stmt % (text, text)) | |
487 if segment in ('where', 'group by', 'order by', 'having', 'set'): | |
488 tableNames = completion.tableNamesFromFromClause(line) | |
489 if tableNames: | |
490 stmt = """SELECT column_name FROM all_tab_columns | |
491 WHERE table_name IN (%s)""" % \ | |
492 (','.join("'%s'" % (t) for t in tableNames)) | |
493 stmt = "%s AND column_name LIKE '%s%%'" % (stmt, text) | |
494 completions = self.select_scalar_list(stmt) | |
495 if not segment: | |
496 stmt = "SELECT object_name FROM all_objects WHERE object_name LIKE '%s%%'" | |
497 completions = self.select_scalar_list(stmt % (text)) | |
498 return completions | |
499 | |
500 rowlimitPattern = pyparsing.Word(pyparsing.nums)('rowlimit') | |
501 rawTerminators = '; \\s \\S \\c \\C \\t \\i \\p \\l \\L \\b ' + ' '.join(output_templates.keys()) | |
502 terminatorPattern = (pyparsing.oneOf(rawTerminators) | |
503 ^ pyparsing.Literal('\n/') ^ \ | |
504 (pyparsing.Literal('\nEOF') + pyparsing.stringEnd)) \ | |
505 ('terminator') + \ | |
506 pyparsing.Optional(rowlimitPattern) #+ \ | |
507 #pyparsing.FollowedBy(pyparsing.LineEnd()) | |
192
6bb8a112af6b
accept special terminators on most anything
catherine@dellzilla
parents:
191
diff
changeset
|
508 def do_select(self, arg, bindVarsIn=None, terminator=None): |
189 | 509 """Fetch rows from a table. |
510 | |
511 Limit the number of rows retrieved by appending | |
512 an integer after the terminator | |
513 (example: SELECT * FROM mytable;10 ) | |
514 | |
515 Output may be formatted by choosing an alternative terminator | |
516 ("help terminators" for details) | |
517 """ | |
518 bindVarsIn = bindVarsIn or {} | |
194 | 519 rowlimit = int(arg.parsed.suffix or 0) |
520 self.varsUsed = findBinds(arg, self.binds, bindVarsIn) | |
193 | 521 self.curs.execute('select ' + arg, self.varsUsed) |
194 | 522 self.rows = self.curs.fetchmany(min(self.maxfetch, (rowlimit or self.maxfetch))) |
189 | 523 self.rc = self.curs.rowcount |
524 if self.rc > 0: | |
194 | 525 self.stdout.write('\n%s\n' % (self.output(arg.parsed.terminator, rowlimit))) |
189 | 526 if self.rc == 0: |
527 print '\nNo rows Selected.\n' | |
528 elif self.rc == 1: | |
529 print '\n1 row selected.\n' | |
530 if self.autobind: | |
531 self.binds.update(dict(zip([''.join(l for l in d[0] if l.isalnum()) for d in self.curs.description], self.rows[0]))) | |
532 for (i, val) in enumerate(self.rows[0]): | |
533 varname = ''.join(letter for letter in self.curs.description[i][0] if letter.isalnum() or letter == '_') | |
534 self.binds[varname] = val | |
535 self.binds[str(i+1)] = val | |
536 elif self.rc < self.maxfetch: | |
537 print '\n%d rows selected.\n' % self.rc | |
538 else: | |
539 print '\nSelected Max Num rows (%d)' % self.rc | |
193 | 540 |
541 def do_cat(self, arg): | |
194 | 542 return self.do_select(self.parsed('SELECT * FROM %s;' % arg, useTerminatorFrom=arg)) |
189 | 543 |
544 @options([make_option('-f', '--full', action='store_true', help='get dependent objects as well')]) | |
545 def do_pull(self, arg, opts): | |
546 """Displays source code.""" | |
547 | |
548 arg = self.parsed(arg).unterminated.upper() | |
549 object_type, owner, object_name = self.resolve(arg) | |
550 if not object_type: | |
551 return | |
552 self.stdout.write("%s %s.%s\n" % (object_type, owner, object_name)) | |
553 self.stdout.write(str(self.curs.callfunc('DBMS_METADATA.GET_DDL', cx_Oracle.CLOB, | |
554 [object_type, object_name, owner]))) | |
555 if opts.full: | |
556 for dependent_type in ('OBJECT_GRANT', 'CONSTRAINT', 'TRIGGER'): | |
557 try: | |
558 self.stdout.write(str(self.curs.callfunc('DBMS_METADATA.GET_DEPENDENT_DDL', cx_Oracle.CLOB, | |
559 [dependent_type, object_name, owner]))) | |
560 except cx_Oracle.DatabaseError: | |
561 pass | |
562 | |
194 | 563 all_users_option = make_option('-a', action='store_const', dest="which_schemas", |
564 default=('','user'), const=(', owner','all'), | |
565 help='Describe all objects (not just my own)') | |
566 @options([all_users_option, | |
189 | 567 make_option('-c', '--col', action='store_true', help='find column'), |
568 make_option('-t', '--table', action='store_true', help='find table')]) | |
569 def do_find(self, arg, opts): | |
570 """Finds argument in source code or (with -c) in column definitions.""" | |
193 | 571 |
572 capArg = arg.upper() | |
189 | 573 |
574 if opts.col: | |
193 | 575 sql = "SELECT owner, table_name, column_name from all_tab_columns where column_name like '%%%s%%';" % (capArg) |
189 | 576 elif opts.table: |
193 | 577 sql = "SELECT owner, table_name from all_tables where table_name like '%%%s%%';" % (capArg) |
189 | 578 else: |
193 | 579 sql = "SELECT * from all_source where UPPER(text) like '%%%s%%';" % (capArg) |
189 | 580 if not opts.all: |
581 sql = '%s and owner = user' % (sql) | |
194 | 582 self.do_select(self.parsed(sql, useTerminatorFrom=arg)) |
193 | 583 |
194 | 584 @options([all_users_option]) |
189 | 585 def do_describe(self, arg, opts): |
586 "emulates SQL*Plus's DESCRIBE" | |
193 | 587 which_view = self._which_view(opts) |
588 target = arg.upper() | |
589 if not target: | |
194 | 590 return self.do_select(self.parsed("""SELECT object_name, object_type%s |
591 FROM %s_objects | |
592 WHERE object_type IN ('TABLE','VIEW','INDEX') | |
593 ORDER BY object_name;""" % opts.which_schemas, | |
594 useTerminatorFrom=arg)) | |
193 | 595 object_type, owner, object_name = self.resolve(target) |
189 | 596 if not object_type: |
194 | 597 return self.do_select(self.parsed("""SELECT object_name, object_type%s FROM %s_objects |
598 WHERE object_type IN ('TABLE','VIEW','INDEX') | |
599 AND object_name LIKE '%%%s%%' | |
600 ORDER BY object_name;""" % | |
601 (opts.which_schemas[0], opts.which_schemas[1], target) | |
602 , useTerminatorFrom=arg)) | |
189 | 603 self.stdout.write("%s %s.%s\n" % (object_type, owner, object_name)) |
604 descQ = descQueries.get(object_type) | |
605 if descQ: | |
606 for q in descQ: | |
193 | 607 self.do_select(arg.newCommand(q), bindVarsIn={'object_name':object_name, 'owner':owner}) |
189 | 608 elif object_type == 'PACKAGE': |
609 packageContents = self.select_scalar_list(descQueries['PackageObjects'][0], {'package_name':object_name, 'owner':owner}) | |
610 for packageObj_name in packageContents: | |
611 self.stdout.write('Arguments to %s\n' % (packageObj_name)) | |
194 | 612 sql = self.parsed(descQueries['PackageObjArgs'][0], useTerminatorFrom=arg) |
613 self.do_select(sql, bindVarsIn={'package_name':object_name, 'owner':owner, 'object_name':packageObj_name}) | |
189 | 614 do_desc = do_describe |
615 | |
616 def do_deps(self, arg): | |
193 | 617 target = arg.upper() |
618 object_type, owner, object_name = self.resolve(target) | |
189 | 619 if object_type == 'PACKAGE BODY': |
620 q = "and (type != 'PACKAGE BODY' or name != :object_name)'" | |
621 object_type = 'PACKAGE' | |
622 else: | |
623 q = "" | |
193 | 624 q = """SELECT name, |
189 | 625 type |
626 from user_dependencies | |
627 where | |
628 referenced_name like :object_name | |
629 and referenced_type like :object_type | |
630 and referenced_owner like :owner | |
193 | 631 %s;""" % (q) |
194 | 632 self.do_select(self.parsed(q, useTerminatorFrom=arg), bindVarsIn={'object_name':object_name, 'object_type':object_type, 'owner':owner}) |
189 | 633 |
634 def do_comments(self, arg): | |
635 'Prints comments on a table and its columns.' | |
193 | 636 target = arg.upper() |
637 object_type, owner, object_name, colName = self.resolve_with_column(target) | |
189 | 638 if object_type: |
193 | 639 self.curs.execute(queries['tabComments'], {'table_name':object_name, 'owner':owner}) |
189 | 640 self.stdout.write("%s %s.%s: %s\n" % (object_type, owner, object_name, self.curs.fetchone()[0])) |
641 if colName: | |
194 | 642 sql = queries['oneColComments'] |
643 bindVarsIn={'owner':owner, 'object_name': object_name, 'column_name': colName} | |
189 | 644 else: |
194 | 645 sql = queries['colComments'] |
646 bindVarsIn={'owner':owner, 'object_name': object_name} | |
647 self.do_select(self.parsed(sql, useTerminatorFrom=arg), bindVarsIn=bindVarsIn) | |
189 | 648 |
649 def resolve(self, identifier): | |
650 """Checks (my objects).name, (my synonyms).name, (public synonyms).name | |
651 to resolve a database object's name. """ | |
652 parts = identifier.split('.') | |
653 try: | |
654 if len(parts) == 2: | |
655 owner, object_name = parts | |
656 object_type = self.select_scalar_list('SELECT object_type FROM all_objects WHERE owner = :owner AND object_name = :object_name', | |
657 {'owner': owner, 'object_name': object_name} | |
658 )[0] | |
659 elif len(parts) == 1: | |
660 object_name = parts[0] | |
661 self.curs.execute(queries['resolve'], {'objName':object_name}) | |
662 object_type, object_name, owner = self.curs.fetchone() | |
663 except (TypeError, IndexError): | |
664 print 'Could not resolve object %s.' % identifier | |
665 object_type, owner, object_name = '', '', '' | |
666 return object_type, owner, object_name | |
667 | |
668 def resolve_with_column(self, identifier): | |
669 colName = None | |
670 object_type, owner, object_name = self.resolve(identifier) | |
671 if not object_type: | |
672 parts = identifier.split('.') | |
673 if len(parts) > 1: | |
674 colName = parts[-1] | |
675 identifier = '.'.join(parts[:-1]) | |
676 object_type, owner, object_name = self.resolve(identifier) | |
677 return object_type, owner, object_name, colName | |
678 | |
679 def do_resolve(self, arg): | |
680 arg = self.parsed(arg).unterminated.upper() | |
681 self.stdout.write(','.join(self.resolve(arg))+'\n') | |
682 | |
683 def spoolstop(self): | |
684 if self.spoolFile: | |
685 self.stdout = self.stdoutBeforeSpool | |
686 print 'Finished spooling to ', self.spoolFile.name | |
687 self.spoolFile.close() | |
688 self.spoolFile = None | |
689 | |
690 def do_spool(self, arg): | |
691 """spool [filename] - begins redirecting output to FILENAME.""" | |
692 self.spoolstop() | |
693 arg = arg.strip() | |
694 if not arg: | |
695 arg = 'output.lst' | |
696 if arg.lower() != 'off': | |
697 if '.' not in arg: | |
698 arg = '%s.lst' % arg | |
699 print 'Sending output to %s (until SPOOL OFF received)' % (arg) | |
700 self.spoolFile = open(arg, 'w') | |
701 self.stdout = self.spoolFile | |
702 | |
703 def do_write(self, args): | |
704 print 'Use (query) > outfilename instead.' | |
705 return | |
706 | |
707 def do_compare(self, args): | |
708 """COMPARE query1 TO query2 - uses external tool to display differences. | |
709 | |
710 Sorting is recommended to avoid false hits. | |
711 Will attempt to use a graphical diff/merge tool like kdiff3, meld, or Araxis Merge, | |
712 if they are installed.""" | |
193 | 713 #TODO: Update this to use pyparsing |
189 | 714 fnames = [] |
715 args2 = args.split(' to ') | |
716 if len(args2) < 2: | |
717 print self.do_compare.__doc__ | |
718 return | |
719 for n in range(len(args2)): | |
720 query = args2[n] | |
721 fnames.append('compare%s.txt' % n) | |
722 #TODO: update this terminator-stripping | |
723 if query.rstrip()[-1] != self.terminator: | |
724 query = '%s%s' % (query, self.terminator) | |
725 self.onecmd_plus_hooks('%s > %s' % (query, fnames[n])) | |
726 diffMergeSearcher.invoke(fnames[0], fnames[1]) | |
727 | |
728 bufferPosPattern = re.compile('\d+') | |
729 rangeIndicators = ('-',':') | |
730 | |
731 def do_psql(self, arg): | |
732 '''Shortcut commands emulating psql's backslash commands. | |
733 | |
734 \c connect | |
735 \d desc | |
736 \e edit | |
737 \g run | |
738 \h help | |
739 \i load | |
740 \o spool | |
741 \p list | |
742 \q quit | |
743 \w save | |
744 \db _dir_tablespaces | |
745 \dd comments | |
746 \dn _dir_schemas | |
747 \dt _dir_tables | |
748 \dv _dir_views | |
749 \di _dir_indexes | |
750 \? help psql''' | |
751 commands = {} | |
752 for c in self.do_psql.__doc__.splitlines()[2:]: | |
753 (abbrev, command) = c.split(None, 1) | |
754 commands[abbrev[1:]] = command | |
755 words = arg.split(None,1) | |
756 try: | |
757 abbrev = words[0] | |
758 except IndexError: | |
759 return | |
760 try: | |
761 args = words[1] | |
762 except IndexError: | |
763 args = '' | |
764 try: | |
765 return self.onecmd('%s %s' % (commands[abbrev], args)) | |
766 except KeyError: | |
767 print 'psql command \%s not yet supported.' % abbrev | |
768 | |
194 | 769 @options([all_users_option]) |
189 | 770 def do__dir_tables(self, arg, opts): |
194 | 771 sql = """SELECT table_name, 'TABLE' as type%s FROM %s_tables WHERE table_name LIKE '%%%s%%';""" % \ |
772 (opts.which_schemas[0], opts.which_schemas[1], arg.upper()) | |
773 self.do_select(self.parsed(sql, useTerminatorFrom=arg)) | |
774 | |
775 @options([all_users_option]) | |
189 | 776 def do__dir_views(self, arg, opts): |
194 | 777 sql = """SELECT view_name, 'VIEW' as type%s FROM %s_views WHERE view_name LIKE '%%%s%%';""" % \ |
778 (opts.which_schemas[0], opts.which_schemas[1], arg.upper()) | |
779 self.do_select(self.parsed(sql, useTerminatorFrom=arg)) | |
780 | |
781 @options([all_users_option]) | |
189 | 782 def do__dir_indexes(self, arg, opts): |
194 | 783 sql = """SELECT index_name, index_type%s FROM %s_indexes WHERE index_name LIKE '%%%s%%' OR table_name LIKE '%%%s%%';""" % \ |
784 (opts.which_schemas[0], opts.which_schemas[1], arg.upper(), arg.upper()) | |
785 self.do_select(self.parsed(sql, useTerminatorFrom=arg)) | |
189 | 786 |
787 def do__dir_tablespaces(self, arg): | |
194 | 788 sql = """SELECT tablespace_name, file_name from dba_data_files;""" |
789 self.do_select(self.parsed(sql, useTerminatorFrom=arg)) | |
189 | 790 |
791 def do__dir_schemas(self, arg): | |
194 | 792 sql = """SELECT owner, count(*) AS objects FROM all_objects GROUP BY owner ORDER BY owner;""" |
793 self.do_select(self.parsed(sql, useTerminatorFrom=arg)) | |
189 | 794 |
795 def do_head(self, arg): | |
194 | 796 sql = self.parsed('SELECT * FROM %s' % arg, useTerminatorFrom=arg) |
797 sql.parsed.suffix = sql.parsed.suffix or '10' | |
798 self.do_select(sql) | |
189 | 799 |
800 def do_print(self, arg): | |
801 'print VARNAME: Show current value of bind variable VARNAME.' | |
802 if arg: | |
803 if arg[0] == ':': | |
804 arg = arg[1:] | |
805 try: | |
806 self.stdout.write(str(self.binds[arg])+'\n') | |
807 except KeyError: | |
808 self.stdout.write('No bind variable %s\n' % arg) | |
809 else: | |
810 for (var, val) in self.binds.items(): | |
811 print ':%s = %s' % (var, val) | |
812 | |
813 assignmentScanner = Parser(pyparsing.Literal(':=') ^ '=') | |
814 def do_setbind(self, arg): | |
815 if not arg: | |
816 return self.do_print(arg) | |
817 arg = self.parsed(arg).unterminated | |
818 try: | |
819 assigner, startat, endat = self.assignmentScanner.scanner.scanString(arg).next() | |
820 except StopIteration: | |
821 self.do_print(arg) | |
822 return | |
823 var, val = arg[:startat].strip(), arg[endat:].strip() | |
824 if val[0] == val[-1] == "'" and len(val) > 1: | |
825 self.binds[var] = val[1:-1] | |
826 return | |
827 try: | |
828 self.binds[var] = int(val) | |
829 return | |
830 except ValueError: | |
831 try: | |
832 self.binds[var] = float(val) | |
833 return | |
834 except ValueError: | |
835 statekeeper = Statekeeper(self, ('autobind',)) | |
836 self.autobind = True | |
193 | 837 self.onecmd('SELECT %s AS %s FROM dual;' % (val, var)) |
189 | 838 statekeeper.restore() |
839 | |
840 def do_exec(self, arg): | |
841 if arg[0] == ':': | |
842 self.do_setbind(arg[1:]) | |
843 else: | |
844 arg = self.parsed(arg).unterminated | |
845 varsUsed = findBinds(arg, self.binds, {}) | |
846 try: | |
847 self.curs.execute('begin\n%s;end;' % arg, varsUsed) | |
848 except Exception, e: | |
849 print e | |
850 | |
851 ''' | |
852 Fails: | |
853 select n into :n from test;''' | |
854 | |
855 def anon_plsql(self, line1): | |
856 lines = [line1] | |
857 while True: | |
858 line = self.pseudo_raw_input(self.continuationPrompt) | |
859 if line.strip() == '/': | |
860 try: | |
861 self.curs.execute('\n'.join(lines)) | |
862 except Exception, e: | |
863 print e | |
864 return | |
865 lines.append(line) | |
866 | |
867 def do_begin(self, arg): | |
868 self.anon_plsql('begin ' + arg) | |
869 | |
870 def do_declare(self, arg): | |
871 self.anon_plsql('declare ' + arg) | |
872 | |
873 #def do_create(self, arg): | |
874 # self.anon_plsql('create ' + arg) | |
875 | |
876 @options([make_option('-l', '--long', action='store_true', help='long descriptions'), | |
877 make_option('-a', '--all', action='store_true', help="all schemas' objects")]) | |
878 def do_ls(self, arg, opts): | |
879 where = '' | |
880 if arg: | |
881 where = """\nWHERE object_type || '/' || object_name | |
882 LIKE '%%%s%%'""" % (arg.upper().replace('*','%')) | |
883 else: | |
884 where = '' | |
885 if opts.all: | |
886 whose = 'all' | |
887 objname = "owner || '.' || object_name" | |
888 else: | |
889 whose = 'user' | |
890 objname = 'object_name' | |
891 if opts.long: | |
892 extraInfo = ', status, last_ddl_time AS modified' | |
893 else: | |
894 extraInfo = '' | |
895 statement = '''SELECT object_type || '/' || %s AS name %s | |
896 FROM %s_objects %s | |
897 ORDER BY object_type, object_name;''' % (objname, extraInfo, whose, where) | |
194 | 898 self.do_select(self.parsed(statement, useTerminatorFrom=arg)) |
189 | 899 |
900 @options([make_option('-i', '--ignore-case', dest='ignorecase', action='store_true', help='Case-insensitive search')]) | |
901 def do_grep(self, arg, opts): | |
902 """grep PATTERN TABLE - search for term in any of TABLE's fields""" | |
903 | |
904 arg = self.parsed(arg) | |
905 targetnames = arg.unterminated.split() | |
906 pattern = targetnames.pop(0) | |
907 targets = [] | |
908 for target in targetnames: | |
909 if '*' in target: | |
910 self.curs.execute("SELECT owner, table_name FROM all_tables WHERE table_name LIKE '%s'%s" % | |
911 (target.upper().replace('*','%')), arg.terminator) | |
912 for row in self.curs: | |
913 targets.append('%s.%s' % row) | |
914 else: | |
915 targets.append(target) | |
916 for target in targets: | |
917 print target | |
918 target = target.rstrip(';') | |
919 sql = [] | |
920 try: | |
921 self.curs.execute('select * from %s where 1=0' % target) # just to fill description | |
922 if opts.ignorecase: | |
923 sql = ' or '.join("LOWER(%s) LIKE '%%%s%%'" % (d[0], pattern.lower()) for d in self.curs.description) | |
924 else: | |
925 sql = ' or '.join("%s LIKE '%%%s%%'" % (d[0], pattern) for d in self.curs.description) | |
926 sql = '* FROM %s WHERE %s' % (target, sql) | |
194 | 927 self.do_select(self.parsed(sql, useTerminatorFrom=arg)) |
189 | 928 except Exception, e: |
929 print e | |
930 import traceback | |
931 traceback.print_exc(file=sys.stdout) | |
932 | |
933 def do_refs(self, arg): | |
190 | 934 result = [] |
935 parsed = self.parsed(arg) | |
936 arg = parsed.unterminated.upper() | |
191 | 937 (type, owner, table_name) = self.resolve(arg) |
938 self.curs.execute("""SELECT constraint_name, r_owner, r_constraint_name | |
939 FROM all_constraints | |
940 WHERE constraint_type = 'R' | |
941 AND owner = :owner | |
942 AND table_name = :table_name""", | |
943 {"owner": owner, "table_name": table_name}) | |
944 for (constraint_name, remote_owner, remote_constraint_name) in self.curs.fetchall(): | |
945 result.append('%s on %s.%s:' % (constraint_name, owner, table_name)) | |
946 self.curs.execute("SELECT column_name FROM all_cons_columns WHERE owner = :owner AND constraint_name = :constraint_name ORDER BY position", | |
947 {'constraint_name': constraint_name, 'owner': owner}) | |
948 result.append(" (%s)" % (",".join(col[0] for col in self.curs.fetchall()))) | |
949 self.curs.execute("SELECT table_name FROM all_constraints WHERE owner = :remote_owner AND constraint_name = :remote_constraint_name", | |
950 {'remote_owner': remote_owner, 'remote_constraint_name': remote_constraint_name}) | |
951 remote_table_name = self.curs.fetchone()[0] | |
952 result.append("must be in %s:" % (remote_table_name)) | |
953 self.curs.execute("SELECT column_name FROM all_cons_columns WHERE owner = :remote_owner AND constraint_name = :remote_constraint_name ORDER BY position", | |
954 {'remote_constraint_name': remote_constraint_name, 'remote_owner': remote_owner}) | |
955 result.append(' (%s)\n' % (",".join(col[0] for col in self.curs.fetchall()))) | |
956 remote_table_name = table_name | |
957 remote_owner = owner | |
958 self.curs.execute("""SELECT owner, constraint_name, table_name, r_constraint_name | |
959 FROM all_constraints | |
960 WHERE (r_owner, r_constraint_name) IN | |
961 ( SELECT owner, constraint_name | |
962 FROM all_constraints | |
192
6bb8a112af6b
accept special terminators on most anything
catherine@dellzilla
parents:
191
diff
changeset
|
963 WHERE table_name = :remote_table_name |
191 | 964 AND owner = :remote_owner )""", |
965 {'remote_table_name': remote_table_name, 'remote_owner': remote_owner}) | |
966 for (owner, constraint_name, table_name, remote_constraint_name) in self.curs.fetchall(): | |
967 result.append('%s on %s.%s:' % (constraint_name, owner, table_name)) | |
968 self.curs.execute("SELECT column_name FROM all_cons_columns WHERE owner = :owner AND constraint_name = :constraint_name ORDER BY position", | |
969 {'constraint_name': constraint_name, 'owner': owner}) | |
970 result.append(" (%s)" % (",".join(col[0] for col in self.curs.fetchall()))) | |
971 self.curs.execute("SELECT table_name FROM all_constraints WHERE owner = :remote_owner AND constraint_name = :remote_constraint_name", | |
972 {'remote_owner': remote_owner, 'remote_constraint_name': remote_constraint_name}) | |
973 remote_table_name = self.curs.fetchone()[0] | |
974 result.append("must be in %s:" % (remote_table_name)) | |
975 self.curs.execute("SELECT column_name FROM all_cons_columns WHERE owner = :remote_owner AND constraint_name = :remote_constraint_name ORDER BY position", | |
976 {'remote_constraint_name': remote_constraint_name, 'remote_owner': remote_owner}) | |
977 result.append(' (%s)\n' % (",".join(col[0] for col in self.curs.fetchall()))) | |
978 self.stdout.write('\n'.join(result) + "\n") | |
190 | 979 |
189 | 980 def _test(): |
981 import doctest | |
982 doctest.testmod() | |
983 | |
984 if __name__ == "__main__": | |
985 "Silent return implies that all unit tests succeeded. Use -v to see details." | |
986 _test() |