Mercurial > sqlpython
annotate sqlpython/sqlpyPlus.py @ 223:6d7eee8ad690
more work on svn
author | catherine@dellzilla |
---|---|
date | Tue, 03 Feb 2009 16:43:29 -0500 |
parents | d8674ac61977 |
children | 582c84365f6a |
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 = { | |
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 | |
192
6bb8a112af6b
accept special terminators on most anything
catherine@dellzilla
parents:
191
diff
changeset
|
353 |
189 | 354 class sqlpyPlus(sqlpython.sqlpython): |
355 defaultExtension = 'sql' | |
356 sqlpython.sqlpython.shortcuts.update({':': 'setbind', | |
357 '\\': 'psql', | |
358 '@': '_load'}) | |
359 multilineCommands = '''select insert update delete tselect | |
360 create drop alter _multiline_comment'''.split() | |
361 sqlpython.sqlpython.noSpecialParse.append('spool') | |
362 commentGrammars = pyparsing.Or([pyparsing.Literal('--') + pyparsing.restOfLine, pyparsing.cStyleComment]) | |
363 defaultFileName = 'afiedt.buf' | |
364 def __init__(self): | |
365 sqlpython.sqlpython.__init__(self) | |
366 self.binds = CaselessDict() | |
367 self.settable = 'autobind commit_on_exit echo maxfetch maxtselctrows timeout'.split() | |
368 # settables must be lowercase | |
369 self.stdoutBeforeSpool = sys.stdout | |
370 self.spoolFile = None | |
371 self.autobind = False | |
195 | 372 #def default(self, arg): |
373 # sqlpython.sqlpython.default(self, arg) | |
189 | 374 |
375 # overrides cmd's parseline | |
376 def parseline(self, line): | |
377 """Parse the line into a command name and a string containing | |
378 the arguments. Returns a tuple containing (command, args, line). | |
379 'command' and 'args' may be None if the line couldn't be parsed. | |
380 Overrides cmd.cmd.parseline to accept variety of shortcuts..""" | |
381 | |
382 cmd, arg, line = sqlpython.sqlpython.parseline(self, line) | |
383 if cmd in ('select', 'sleect', 'insert', 'update', 'delete', 'describe', | |
384 'desc', 'comments', 'pull', 'refs', 'desc', 'triggers', 'find') \ | |
385 and not hasattr(self, 'curs'): | |
386 print 'Not connected.' | |
387 return '', '', '' | |
388 return cmd, arg, line | |
389 | |
390 do__load = Cmd.do_load | |
391 | |
392 def onecmd_plus_hooks(self, line): | |
393 line = self.precmd(line) | |
394 stop = self.onecmd(line) | |
395 stop = self.postcmd(stop, line) | |
396 | |
397 def do_shortcuts(self,arg): | |
398 """Lists available first-character shortcuts | |
399 (i.e. '!dir' is equivalent to 'shell dir')""" | |
400 for (scchar, scto) in self.shortcuts.items(): | |
401 print '%s: %s' % (scchar, scto) | |
402 | |
403 def colnames(self): | |
404 return [d[0] for d in curs.description] | |
405 | |
406 def sql_format_itm(self, itm, needsquotes): | |
407 if itm is None: | |
408 return 'NULL' | |
409 if needsquotes: | |
410 return "'%s'" % str(itm) | |
411 return str(itm) | |
412 tableNameFinder = re.compile(r'from\s+([\w$#_"]+)', re.IGNORECASE | re.MULTILINE | re.DOTALL) | |
413 inputStatementFormatters = { | |
414 cx_Oracle.STRING: "'%s'", | |
415 cx_Oracle.DATETIME: "TO_DATE('%s', 'YYYY-MM-DD HH24:MI:SS')"} | |
416 inputStatementFormatters[cx_Oracle.CLOB] = inputStatementFormatters[cx_Oracle.STRING] | |
417 inputStatementFormatters[cx_Oracle.TIMESTAMP] = inputStatementFormatters[cx_Oracle.DATETIME] | |
418 def output(self, outformat, rowlimit): | |
419 self.tblname = self.tableNameFinder.search(self.curs.statement).group(1) | |
420 self.colnames = [d[0] for d in self.curs.description] | |
421 if outformat in output_templates: | |
422 self.colnamelen = max(len(colname) for colname in self.colnames) | |
423 self.coltypes = [d[1] for d in self.curs.description] | |
424 self.formatters = [self.inputStatementFormatters.get(typ, '%s') for typ in self.coltypes] | |
425 result = output_templates[outformat].generate(**self.__dict__) | |
426 elif outformat == '\\t': # transposed | |
427 rows = [self.colnames] | |
428 rows.extend(list(self.rows)) | |
429 transpr = [[rows[y][x] for y in range(len(rows))]for x in range(len(rows[0]))] # matrix transpose | |
430 newdesc = [['ROW N.'+str(y),10] for y in range(len(rows))] | |
431 for x in range(len(self.curs.description)): | |
432 if str(self.curs.description[x][1]) == "<type 'cx_Oracle.BINARY'>": # handles RAW columns | |
433 rname = transpr[x][0] | |
434 transpr[x] = map(binascii.b2a_hex, transpr[x]) | |
435 transpr[x][0] = rname | |
436 newdesc[0][0] = 'COLUMN NAME' | |
437 result = '\n' + sqlpython.pmatrix(transpr,newdesc) | |
438 elif outformat in ('\\l', '\\L', '\\p', '\\b'): | |
439 plot = Plot() | |
440 plot.build(self, outformat) | |
441 plot.shelve() | |
442 plot.draw() | |
443 return '' | |
444 else: | |
445 result = sqlpython.pmatrix(self.rows, self.curs.description, self.maxfetch) | |
446 return result | |
447 | |
448 legalOracle = re.compile('[a-zA-Z_$#]') | |
449 | |
450 def select_scalar_list(self, sql, binds={}): | |
451 self.curs.execute(sql, binds) | |
452 return [r[0] for r in self.curs.fetchall()] | |
453 | |
454 columnNameRegex = re.compile( | |
455 r'select\s+(.*)from', | |
456 re.IGNORECASE | re.DOTALL | re.MULTILINE) | |
457 def completedefault(self, text, line, begidx, endidx): | |
458 segment = completion.whichSegment(line) | |
459 text = text.upper() | |
460 completions = [] | |
461 if segment == 'select': | |
462 stmt = "SELECT column_name FROM user_tab_columns WHERE column_name LIKE '%s%%'" | |
463 completions = self.select_scalar_list(stmt % (text)) | |
464 if not completions: | |
465 stmt = "SELECT column_name FROM all_tab_columns WHERE column_name LIKE '%s%%'" | |
466 completions = self.select_scalar_list(stmt % (text)) | |
467 if segment == 'from': | |
468 columnNames = self.columnNameRegex.search(line) | |
469 if columnNames: | |
470 columnNames = columnNames.group(1) | |
471 columnNames = [c.strip().upper() for c in columnNames.split(',')] | |
472 stmt1 = "SELECT table_name FROM all_tab_columns WHERE column_name = '%s' AND table_name LIKE '%s%%'" | |
473 for columnName in columnNames: | |
474 # and if columnName is * ? | |
475 completions.extend(self.select_scalar_list(stmt1 % (columnName, text))) | |
476 if segment in ('from', 'update', 'insert into') and (not completions): | |
477 stmt = "SELECT table_name FROM user_tables WHERE table_name LIKE '%s%%'" | |
478 completions = self.select_scalar_list(stmt % (text)) | |
479 if not completions: | |
480 stmt = """SELECT table_name FROM user_tables WHERE table_name LIKE '%s%%' | |
481 UNION | |
482 SELECT DISTINCT owner FROM all_tables WHERE owner LIKE '%%%s'""" | |
483 completions = self.select_scalar_list(stmt % (text, text)) | |
484 if segment in ('where', 'group by', 'order by', 'having', 'set'): | |
485 tableNames = completion.tableNamesFromFromClause(line) | |
486 if tableNames: | |
487 stmt = """SELECT column_name FROM all_tab_columns | |
488 WHERE table_name IN (%s)""" % \ | |
489 (','.join("'%s'" % (t) for t in tableNames)) | |
490 stmt = "%s AND column_name LIKE '%s%%'" % (stmt, text) | |
491 completions = self.select_scalar_list(stmt) | |
492 if not segment: | |
493 stmt = "SELECT object_name FROM all_objects WHERE object_name LIKE '%s%%'" | |
494 completions = self.select_scalar_list(stmt % (text)) | |
495 return completions | |
496 | |
497 rowlimitPattern = pyparsing.Word(pyparsing.nums)('rowlimit') | |
204 | 498 terminators = '; \\C \\t \\i \\p \\l \\L \\b '.split() + output_templates.keys() |
199
09592342a33d
ugh - parsing stripping command causes real trouble
catherine@dellzilla
parents:
198
diff
changeset
|
499 |
192
6bb8a112af6b
accept special terminators on most anything
catherine@dellzilla
parents:
191
diff
changeset
|
500 def do_select(self, arg, bindVarsIn=None, terminator=None): |
189 | 501 """Fetch rows from a table. |
502 | |
503 Limit the number of rows retrieved by appending | |
504 an integer after the terminator | |
505 (example: SELECT * FROM mytable;10 ) | |
506 | |
507 Output may be formatted by choosing an alternative terminator | |
508 ("help terminators" for details) | |
509 """ | |
510 bindVarsIn = bindVarsIn or {} | |
196 | 511 try: |
512 rowlimit = int(arg.parsed.suffix or 0) | |
513 except ValueError: | |
514 rowlimit = 0 | |
206 | 515 print "Specify desired number of rows after terminator (not '%s')" % arg.parsed.suffix |
194 | 516 self.varsUsed = findBinds(arg, self.binds, bindVarsIn) |
193 | 517 self.curs.execute('select ' + arg, self.varsUsed) |
194 | 518 self.rows = self.curs.fetchmany(min(self.maxfetch, (rowlimit or self.maxfetch))) |
189 | 519 self.rc = self.curs.rowcount |
520 if self.rc > 0: | |
194 | 521 self.stdout.write('\n%s\n' % (self.output(arg.parsed.terminator, rowlimit))) |
189 | 522 if self.rc == 0: |
523 print '\nNo rows Selected.\n' | |
524 elif self.rc == 1: | |
525 print '\n1 row selected.\n' | |
526 if self.autobind: | |
527 self.binds.update(dict(zip([''.join(l for l in d[0] if l.isalnum()) for d in self.curs.description], self.rows[0]))) | |
528 for (i, val) in enumerate(self.rows[0]): | |
529 varname = ''.join(letter for letter in self.curs.description[i][0] if letter.isalnum() or letter == '_') | |
530 self.binds[varname] = val | |
531 self.binds[str(i+1)] = val | |
532 elif self.rc < self.maxfetch: | |
533 print '\n%d rows selected.\n' % self.rc | |
534 else: | |
535 print '\nSelected Max Num rows (%d)' % self.rc | |
193 | 536 |
537 def do_cat(self, arg): | |
200 | 538 return self.do_select(self.parsed('SELECT * FROM %s;' % arg, |
539 terminator = arg.parsed.terminator or ';', | |
540 suffix = arg.parsed.suffix)) | |
220 | 541 |
542 def _pull(self, arg, opts, vc=None): | |
543 """Displays source code.""" | |
544 if opts.dump: | |
545 statekeeper = Statekeeper(self, ('stdout',)) | |
546 try: | |
547 for (owner, object_type, object_name) in self.resolve_many(arg, opts): | |
548 if object_type in self.supported_ddl_types: | |
549 object_type = {'DATABASE LINK': 'DB_LINK', 'JAVA CLASS': 'JAVA_SOURCE' | |
550 }.get(object_type) or object_type | |
551 object_type = object_type.replace(' ', '_') | |
552 if opts.dump: | |
553 try: | |
554 os.makedirs(os.path.join(owner.lower(), object_type.lower())) | |
555 except OSError: | |
556 pass | |
557 filename = os.path.join(owner.lower(), object_type.lower(), '%s.sql' % object_name.lower()) | |
558 self.stdout = open(filename, 'w') | |
559 if vc: | |
560 subprocess.call(vc + [filename]) | |
561 try: | |
562 if object_type in ['CONTEXT', 'DIRECTORY', 'JOB']: | |
563 ddlargs = [object_type, object_name] | |
564 else: | |
565 ddlargs = [object_type, object_name, owner] | |
566 self.stdout.write(str(self.curs.callfunc('DBMS_METADATA.GET_DDL', cx_Oracle.CLOB, ddlargs))) | |
567 except cx_Oracle.DatabaseError: | |
568 if object_type == 'JOB': | |
569 print '%s: DBMS_METADATA.GET_DDL does not support JOBs (MetaLink DocID 567504.1)' % object_name | |
570 continue | |
571 raise | |
572 if opts.full: | |
573 for dependent_type in ('OBJECT_GRANT', 'CONSTRAINT', 'TRIGGER'): | |
574 try: | |
575 self.stdout.write(str(self.curs.callfunc('DBMS_METADATA.GET_DEPENDENT_DDL', cx_Oracle.CLOB, | |
576 [dependent_type, object_name, owner]))) | |
577 except cx_Oracle.DatabaseError: | |
578 pass | |
579 if opts.dump: | |
580 self.stdout.close() | |
581 except: | |
582 if opts.dump: | |
583 statekeeper.restore() | |
584 raise | |
585 if opts.dump: | |
586 statekeeper.restore() | |
587 | |
221 | 588 def do_show(self, arg): |
589 ''' | |
590 show - display value of all sqlpython parameters | |
591 show (parameter name) - display value of a sqlpython parameter | |
592 show parameter (parameter name) - display value of an ORACLE parameter | |
593 ''' | |
594 if arg.startswith('param'): | |
595 try: | |
596 paramname = arg.split()[1].lower() | |
597 except IndexError: | |
598 paramname = '' | |
599 self.onecmd("""SELECT name, | |
600 CASE type WHEN 1 THEN 'BOOLEAN' | |
601 WHEN 2 THEN 'STRING' | |
602 WHEN 3 THEN 'INTEGER' | |
603 WHEN 4 THEN 'PARAMETER FILE' | |
604 WHEN 5 THEN 'RESERVED' | |
605 WHEN 6 THEN 'BIG INTEGER' END type, | |
606 value FROM v$parameter WHERE name LIKE '%%%s%%';""" % paramname) | |
607 else: | |
608 return Cmd.do_show(self, arg) | |
609 | |
218
397979c7f6d6
dumping working but not for wildcards
catherine@Elli.myhome.westell.com
parents:
217
diff
changeset
|
610 @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
|
611 make_option('-f', '--full', action='store_true', help='get dependent objects as well'), |
217
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
612 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
|
613 make_option('-x', '--exact', action='store_true', help="match object name exactly")]) |
189 | 614 def do_pull(self, arg, opts): |
615 """Displays source code.""" | |
220 | 616 self._pull(arg, opts) |
617 | |
618 supported_ddl_types = 'CLUSTER, CONTEXT, DATABASE LINK, DIRECTORY, FUNCTION, INDEX, JOB, LIBRARY, MATERIALIZED VIEW, PACKAGE, PACKAGE BODY, OPERATOR, PACKAGE, PROCEDURE, SEQUENCE, SYNONYM, TABLE, TRIGGER, VIEW, TYPE, TYPE BODY, XML SCHEMA' | |
619 do_pull.__doc__ += '\n\nSupported DDL types: ' + supported_ddl_types | |
620 supported_ddl_types = supported_ddl_types.split(', ') | |
189 | 621 |
223 | 622 def _vc(self, arg, opts, program, initializer): |
623 subprocess.call(initializer) | |
624 os.chdir(initializer[2]) | |
220 | 625 opts.dump = True |
626 self._pull(arg, opts, vc=[program, 'add']) | |
627 subprocess.call([program, 'commit', '-m', '"%s"' % opts.message or 'committed from sqlpython']) | |
223 | 628 os.chdir('..') |
220 | 629 |
630 @options([ | |
631 make_option('-f', '--full', action='store_true', help='get dependent objects as well'), | |
632 make_option('-a', '--all', action='store_true', help="all schemas' objects"), | |
633 make_option('-x', '--exact', action='store_true', help="match object name exactly"), | |
634 make_option('-m', '--message', action='store', type='string', dest='message', help="message to save to hg log during commit")]) | |
635 def do_hg(self, arg, opts): | |
636 '''hg (opts) (objects): | |
637 Stores DDL on disk and puts files under Mercurial version control.''' | |
223 | 638 self._vc(arg, opts, 'hg', ['hg', 'init', self.sid]) |
189 | 639 |
220 | 640 @options([ |
641 make_option('-f', '--full', action='store_true', help='get dependent objects as well'), | |
642 make_option('-a', '--all', action='store_true', help="all schemas' objects"), | |
643 make_option('-x', '--exact', action='store_true', help="match object name exactly"), | |
644 make_option('-m', '--message', action='store', type='string', dest='message', help="message to save to hg log during commit")]) | |
645 def do_bzr(self, arg, opts): | |
646 '''bzr (opts) (objects): | |
647 Stores DDL on disk and puts files under Bazaar version control.''' | |
223 | 648 self._vc(arg, opts, 'bzr', ['bzr', 'init', self.sid]) |
220 | 649 |
650 @options([ | |
651 make_option('-f', '--full', action='store_true', help='get dependent objects as well'), | |
652 make_option('-a', '--all', action='store_true', help="all schemas' objects"), | |
653 make_option('-x', '--exact', action='store_true', help="match object name exactly"), | |
654 make_option('-m', '--message', action='store', type='string', dest='message', help="message to save to hg log during commit")]) | |
655 def do_svn(self, arg, opts): | |
656 '''svn (opts) (objects): | |
657 Stores DDL to disk and commits a change to SVN.''' | |
223 | 658 self._vc(arg, opts, 'svn', ['svnadmin', 'init', self.sid]) |
659 | |
220 | 660 subprocess.call(['svn', 'commit', '-m', '"%s"' % opts.message or 'committed from sqlpython']) |
661 | |
196 | 662 all_users_option = make_option('-a', action='store_const', dest="scope", |
222 | 663 default={'col':'', 'view':'user', 'schemas':'user', 'firstcol': ''}, |
664 const={'col':', owner', 'view':'all', 'schemas':'all', 'firstcol': 'owner, '}, | |
194 | 665 help='Describe all objects (not just my own)') |
666 @options([all_users_option, | |
189 | 667 make_option('-c', '--col', action='store_true', help='find column'), |
668 make_option('-t', '--table', action='store_true', help='find table')]) | |
669 def do_find(self, arg, opts): | |
670 """Finds argument in source code or (with -c) in column definitions.""" | |
193 | 671 |
672 capArg = arg.upper() | |
189 | 673 |
674 if opts.col: | |
222 | 675 sql = "SELECT table_name, column_name %s FROM %s_tab_columns where column_name like '%%%s%%' ORDER BY %s table_name, column_name;" \ |
676 % (opts.scope['col'], opts.scope['view'], capArg, opts.scope['firstcol']) | |
189 | 677 elif opts.table: |
222 | 678 sql = "SELECT table_name %s from %s_tables where table_name like '%%%s%%' ORDER BY %s table_name;" \ |
679 % (opts.scope['col'], opts.scope['view'], capArg, opts.scope['firstcol']) | |
189 | 680 else: |
196 | 681 sql = "SELECT * from %s_source where UPPER(text) like '%%%s%%';" % (opts.scope['view'], capArg) |
200 | 682 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
193 | 683 |
194 | 684 @options([all_users_option]) |
189 | 685 def do_describe(self, arg, opts): |
686 "emulates SQL*Plus's DESCRIBE" | |
193 | 687 target = arg.upper() |
688 if not target: | |
194 | 689 return self.do_select(self.parsed("""SELECT object_name, object_type%s |
690 FROM %s_objects | |
691 WHERE object_type IN ('TABLE','VIEW','INDEX') | |
196 | 692 ORDER BY object_name;""" % (opts.scope['col'], opts.scope['view']), |
200 | 693 terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
193 | 694 object_type, owner, object_name = self.resolve(target) |
189 | 695 if not object_type: |
194 | 696 return self.do_select(self.parsed("""SELECT object_name, object_type%s FROM %s_objects |
697 WHERE object_type IN ('TABLE','VIEW','INDEX') | |
698 AND object_name LIKE '%%%s%%' | |
699 ORDER BY object_name;""" % | |
200 | 700 (opts.scope['col'], opts.scope['view'], target), |
701 terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) | |
189 | 702 self.stdout.write("%s %s.%s\n" % (object_type, owner, object_name)) |
703 descQ = descQueries.get(object_type) | |
704 if descQ: | |
705 for q in descQ: | |
204 | 706 self.do_select(self.parsed(q, terminator=arg.parsed.terminator or ';' , suffix=arg.parsed.suffix), |
200 | 707 bindVarsIn={'object_name':object_name, 'owner':owner}) |
189 | 708 elif object_type == 'PACKAGE': |
709 packageContents = self.select_scalar_list(descQueries['PackageObjects'][0], {'package_name':object_name, 'owner':owner}) | |
710 for packageObj_name in packageContents: | |
711 self.stdout.write('Arguments to %s\n' % (packageObj_name)) | |
200 | 712 sql = self.parsed(descQueries['PackageObjArgs'][0], terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix) |
194 | 713 self.do_select(sql, bindVarsIn={'package_name':object_name, 'owner':owner, 'object_name':packageObj_name}) |
189 | 714 do_desc = do_describe |
715 | |
716 def do_deps(self, arg): | |
193 | 717 target = arg.upper() |
718 object_type, owner, object_name = self.resolve(target) | |
189 | 719 if object_type == 'PACKAGE BODY': |
720 q = "and (type != 'PACKAGE BODY' or name != :object_name)'" | |
721 object_type = 'PACKAGE' | |
722 else: | |
723 q = "" | |
193 | 724 q = """SELECT name, |
189 | 725 type |
726 from user_dependencies | |
727 where | |
728 referenced_name like :object_name | |
729 and referenced_type like :object_type | |
730 and referenced_owner like :owner | |
193 | 731 %s;""" % (q) |
200 | 732 self.do_select(self.parsed(q, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix), |
733 bindVarsIn={'object_name':object_name, 'object_type':object_type, 'owner':owner}) | |
189 | 734 |
735 def do_comments(self, arg): | |
736 'Prints comments on a table and its columns.' | |
193 | 737 target = arg.upper() |
738 object_type, owner, object_name, colName = self.resolve_with_column(target) | |
189 | 739 if object_type: |
193 | 740 self.curs.execute(queries['tabComments'], {'table_name':object_name, 'owner':owner}) |
189 | 741 self.stdout.write("%s %s.%s: %s\n" % (object_type, owner, object_name, self.curs.fetchone()[0])) |
742 if colName: | |
194 | 743 sql = queries['oneColComments'] |
744 bindVarsIn={'owner':owner, 'object_name': object_name, 'column_name': colName} | |
189 | 745 else: |
194 | 746 sql = queries['colComments'] |
747 bindVarsIn={'owner':owner, 'object_name': object_name} | |
200 | 748 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix), |
749 bindVarsIn=bindVarsIn) | |
189 | 750 |
751 def resolve(self, identifier): | |
752 """Checks (my objects).name, (my synonyms).name, (public synonyms).name | |
753 to resolve a database object's name. """ | |
754 parts = identifier.split('.') | |
755 try: | |
756 if len(parts) == 2: | |
757 owner, object_name = parts | |
758 object_type = self.select_scalar_list('SELECT object_type FROM all_objects WHERE owner = :owner AND object_name = :object_name', | |
205 | 759 {'owner': owner, 'object_name': object_name.upper()} |
189 | 760 )[0] |
761 elif len(parts) == 1: | |
762 object_name = parts[0] | |
205 | 763 self.curs.execute(queries['resolve'], {'objName':object_name.upper()}) |
189 | 764 object_type, object_name, owner = self.curs.fetchone() |
765 except (TypeError, IndexError): | |
766 print 'Could not resolve object %s.' % identifier | |
767 object_type, owner, object_name = '', '', '' | |
768 return object_type, owner, object_name | |
769 | |
770 def resolve_with_column(self, identifier): | |
771 colName = None | |
772 object_type, owner, object_name = self.resolve(identifier) | |
773 if not object_type: | |
774 parts = identifier.split('.') | |
775 if len(parts) > 1: | |
776 colName = parts[-1] | |
777 identifier = '.'.join(parts[:-1]) | |
778 object_type, owner, object_name = self.resolve(identifier) | |
779 return object_type, owner, object_name, colName | |
780 | |
781 def do_resolve(self, arg): | |
195 | 782 target = arg.upper() |
783 self.stdout.write(','.join(self.resolve(target))+'\n') | |
189 | 784 |
785 def spoolstop(self): | |
786 if self.spoolFile: | |
787 self.stdout = self.stdoutBeforeSpool | |
788 print 'Finished spooling to ', self.spoolFile.name | |
789 self.spoolFile.close() | |
790 self.spoolFile = None | |
791 | |
792 def do_spool(self, arg): | |
793 """spool [filename] - begins redirecting output to FILENAME.""" | |
794 self.spoolstop() | |
795 arg = arg.strip() | |
796 if not arg: | |
797 arg = 'output.lst' | |
798 if arg.lower() != 'off': | |
799 if '.' not in arg: | |
800 arg = '%s.lst' % arg | |
801 print 'Sending output to %s (until SPOOL OFF received)' % (arg) | |
802 self.spoolFile = open(arg, 'w') | |
803 self.stdout = self.spoolFile | |
804 | |
805 def do_write(self, args): | |
806 print 'Use (query) > outfilename instead.' | |
807 return | |
808 | |
809 def do_compare(self, args): | |
810 """COMPARE query1 TO query2 - uses external tool to display differences. | |
811 | |
812 Sorting is recommended to avoid false hits. | |
813 Will attempt to use a graphical diff/merge tool like kdiff3, meld, or Araxis Merge, | |
814 if they are installed.""" | |
193 | 815 #TODO: Update this to use pyparsing |
189 | 816 fnames = [] |
817 args2 = args.split(' to ') | |
818 if len(args2) < 2: | |
819 print self.do_compare.__doc__ | |
820 return | |
821 for n in range(len(args2)): | |
822 query = args2[n] | |
823 fnames.append('compare%s.txt' % n) | |
824 #TODO: update this terminator-stripping | |
825 if query.rstrip()[-1] != self.terminator: | |
826 query = '%s%s' % (query, self.terminator) | |
827 self.onecmd_plus_hooks('%s > %s' % (query, fnames[n])) | |
828 diffMergeSearcher.invoke(fnames[0], fnames[1]) | |
829 | |
830 bufferPosPattern = re.compile('\d+') | |
831 rangeIndicators = ('-',':') | |
832 | |
833 def do_psql(self, arg): | |
834 '''Shortcut commands emulating psql's backslash commands. | |
835 | |
836 \c connect | |
837 \d desc | |
838 \e edit | |
839 \g run | |
840 \h help | |
841 \i load | |
842 \o spool | |
843 \p list | |
844 \q quit | |
845 \w save | |
846 \db _dir_tablespaces | |
847 \dd comments | |
848 \dn _dir_schemas | |
849 \dt _dir_tables | |
850 \dv _dir_views | |
851 \di _dir_indexes | |
852 \? help psql''' | |
853 commands = {} | |
854 for c in self.do_psql.__doc__.splitlines()[2:]: | |
855 (abbrev, command) = c.split(None, 1) | |
856 commands[abbrev[1:]] = command | |
857 words = arg.split(None,1) | |
858 try: | |
859 abbrev = words[0] | |
860 except IndexError: | |
861 return | |
862 try: | |
863 args = words[1] | |
864 except IndexError: | |
865 args = '' | |
866 try: | |
200 | 867 return self.onecmd('%s %s%s%s' % (commands[abbrev], args, arg.parsed.terminator, arg.parsed.suffix)) |
189 | 868 except KeyError: |
869 print 'psql command \%s not yet supported.' % abbrev | |
870 | |
194 | 871 @options([all_users_option]) |
189 | 872 def do__dir_tables(self, arg, opts): |
194 | 873 sql = """SELECT table_name, 'TABLE' as type%s FROM %s_tables WHERE table_name LIKE '%%%s%%';""" % \ |
196 | 874 (opts.scope['col'], opts.scope['view'], arg.upper()) |
200 | 875 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
194 | 876 |
877 @options([all_users_option]) | |
189 | 878 def do__dir_views(self, arg, opts): |
194 | 879 sql = """SELECT view_name, 'VIEW' as type%s FROM %s_views WHERE view_name LIKE '%%%s%%';""" % \ |
196 | 880 (opts.scope['col'], opts.scope['view'], arg.upper()) |
200 | 881 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
194 | 882 |
883 @options([all_users_option]) | |
189 | 884 def do__dir_indexes(self, arg, opts): |
194 | 885 sql = """SELECT index_name, index_type%s FROM %s_indexes WHERE index_name LIKE '%%%s%%' OR table_name LIKE '%%%s%%';""" % \ |
196 | 886 (opts.scope['col'], opts.scope['view'], arg.upper(), arg.upper()) |
200 | 887 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
189 | 888 |
889 def do__dir_tablespaces(self, arg): | |
194 | 890 sql = """SELECT tablespace_name, file_name from dba_data_files;""" |
200 | 891 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
189 | 892 |
893 def do__dir_schemas(self, arg): | |
194 | 894 sql = """SELECT owner, count(*) AS objects FROM all_objects GROUP BY owner ORDER BY owner;""" |
200 | 895 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
189 | 896 |
897 def do_head(self, arg): | |
200 | 898 sql = self.parsed('SELECT * FROM %s;' % arg, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix) |
195 | 899 sql.parsed['suffix'] = sql.parsed.suffix or '10' |
196 | 900 self.do_select(self.parsed(sql)) |
189 | 901 |
902 def do_print(self, arg): | |
903 'print VARNAME: Show current value of bind variable VARNAME.' | |
904 if arg: | |
905 if arg[0] == ':': | |
906 arg = arg[1:] | |
907 try: | |
908 self.stdout.write(str(self.binds[arg])+'\n') | |
909 except KeyError: | |
910 self.stdout.write('No bind variable %s\n' % arg) | |
911 else: | |
912 for (var, val) in self.binds.items(): | |
913 print ':%s = %s' % (var, val) | |
914 | |
915 assignmentScanner = Parser(pyparsing.Literal(':=') ^ '=') | |
916 def do_setbind(self, arg): | |
917 if not arg: | |
918 return self.do_print(arg) | |
919 try: | |
920 assigner, startat, endat = self.assignmentScanner.scanner.scanString(arg).next() | |
921 except StopIteration: | |
922 self.do_print(arg) | |
923 return | |
924 var, val = arg[:startat].strip(), arg[endat:].strip() | |
925 if val[0] == val[-1] == "'" and len(val) > 1: | |
926 self.binds[var] = val[1:-1] | |
927 return | |
928 try: | |
929 self.binds[var] = int(val) | |
930 return | |
931 except ValueError: | |
932 try: | |
933 self.binds[var] = float(val) | |
934 return | |
935 except ValueError: | |
936 statekeeper = Statekeeper(self, ('autobind',)) | |
937 self.autobind = True | |
193 | 938 self.onecmd('SELECT %s AS %s FROM dual;' % (val, var)) |
189 | 939 statekeeper.restore() |
940 | |
941 def do_exec(self, arg): | |
213 | 942 if arg.startswith(':'): |
189 | 943 self.do_setbind(arg[1:]) |
944 else: | |
945 varsUsed = findBinds(arg, self.binds, {}) | |
946 try: | |
947 self.curs.execute('begin\n%s;end;' % arg, varsUsed) | |
948 except Exception, e: | |
949 print e | |
950 | |
951 ''' | |
952 Fails: | |
953 select n into :n from test;''' | |
954 | |
955 def anon_plsql(self, line1): | |
956 lines = [line1] | |
957 while True: | |
958 line = self.pseudo_raw_input(self.continuationPrompt) | |
959 if line.strip() == '/': | |
960 try: | |
961 self.curs.execute('\n'.join(lines)) | |
962 except Exception, e: | |
963 print e | |
964 return | |
965 lines.append(line) | |
966 | |
967 def do_begin(self, arg): | |
968 self.anon_plsql('begin ' + arg) | |
969 | |
970 def do_declare(self, arg): | |
971 self.anon_plsql('declare ' + arg) | |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
972 |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
973 def _ls_statement(self, arg, opts): |
189 | 974 if arg: |
217
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
975 target = arg.upper() |
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
976 if opts.exact: |
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
977 where = """\nWHERE object_name = '%s' |
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
978 OR object_type || '/' || object_name = '%s'""" % \ |
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
979 (target, target) |
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
980 else: |
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
981 where = "\nWHERE object_type || '/' || object_name LIKE '%%%s%%'" % (arg.upper().replace('*','%')) |
189 | 982 else: |
983 where = '' | |
984 if opts.all: | |
985 whose = 'all' | |
986 objname = "owner || '.' || object_name" | |
987 else: | |
988 whose = 'user' | |
989 objname = 'object_name' | |
990 if opts.long: | |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
991 moreColumns = ', status, last_ddl_time AS modified' |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
992 else: |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
993 moreColumns = '' |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
994 return {'objname': objname, 'moreColumns': moreColumns, |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
995 'whose': whose, 'where': where} |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
996 |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
997 def resolve_many(self, arg, opts): |
217
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
998 opts.long = False |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
999 clauses = self._ls_statement(arg, opts) |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1000 if opts.all: |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1001 clauses['owner'] = 'owner' |
189 | 1002 else: |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1003 clauses['owner'] = 'user' |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1004 statement = '''SELECT %(owner)s, object_type, object_name |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1005 FROM %(whose)s_objects %(where)s |
217
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
1006 ORDER BY object_type, object_name''' % clauses |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1007 self.curs.execute(statement) |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1008 return self.curs.fetchall() |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1009 |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1010 @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
|
1011 make_option('-a', '--all', action='store_true', help="all schemas' objects"), |
a65b98938596
multi-pull working pretty well
catherine@Elli.myhome.westell.com
parents:
216
diff
changeset
|
1012 make_option('-x', '--exact', action='store_true', default=False, help="match name exactly")]) |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1013 def do_ls(self, arg, opts): |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1014 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
|
1015 FROM %(whose)s_objects %(where)s |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1016 ORDER BY object_type, object_name;''' % self._ls_statement(arg, opts) |
200 | 1017 self.do_select(self.parsed(statement, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
189 | 1018 |
1019 @options([make_option('-i', '--ignore-case', dest='ignorecase', action='store_true', help='Case-insensitive search')]) | |
1020 def do_grep(self, arg, opts): | |
1021 """grep PATTERN TABLE - search for term in any of TABLE's fields""" | |
1022 | |
195 | 1023 targetnames = arg.split() |
189 | 1024 pattern = targetnames.pop(0) |
1025 targets = [] | |
1026 for target in targetnames: | |
1027 if '*' in target: | |
1028 self.curs.execute("SELECT owner, table_name FROM all_tables WHERE table_name LIKE '%s'%s" % | |
1029 (target.upper().replace('*','%')), arg.terminator) | |
1030 for row in self.curs: | |
1031 targets.append('%s.%s' % row) | |
1032 else: | |
1033 targets.append(target) | |
1034 for target in targets: | |
1035 print target | |
1036 target = target.rstrip(';') | |
1037 try: | |
1038 self.curs.execute('select * from %s where 1=0' % target) # just to fill description | |
1039 if opts.ignorecase: | |
1040 sql = ' or '.join("LOWER(%s) LIKE '%%%s%%'" % (d[0], pattern.lower()) for d in self.curs.description) | |
1041 else: | |
1042 sql = ' or '.join("%s LIKE '%%%s%%'" % (d[0], pattern) for d in self.curs.description) | |
200 | 1043 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
|
1044 self.do_select(sql) |
189 | 1045 except Exception, e: |
1046 print e | |
1047 import traceback | |
1048 traceback.print_exc(file=sys.stdout) | |
1049 | |
1050 def do_refs(self, arg): | |
211 | 1051 '''Lists referential integrity (foreign key constraints) on an object.''' |
1052 | |
1053 if not arg.strip(): | |
1054 print 'Usage: refs (table name)' | |
190 | 1055 result = [] |
205 | 1056 (type, owner, table_name) = self.resolve(arg.upper()) |
191 | 1057 self.curs.execute("""SELECT constraint_name, r_owner, r_constraint_name |
1058 FROM all_constraints | |
1059 WHERE constraint_type = 'R' | |
1060 AND owner = :owner | |
1061 AND table_name = :table_name""", | |
1062 {"owner": owner, "table_name": table_name}) | |
1063 for (constraint_name, remote_owner, remote_constraint_name) in self.curs.fetchall(): | |
1064 result.append('%s on %s.%s:' % (constraint_name, owner, table_name)) | |
1065 self.curs.execute("SELECT column_name FROM all_cons_columns WHERE owner = :owner AND constraint_name = :constraint_name ORDER BY position", | |
1066 {'constraint_name': constraint_name, 'owner': owner}) | |
1067 result.append(" (%s)" % (",".join(col[0] for col in self.curs.fetchall()))) | |
1068 self.curs.execute("SELECT table_name FROM all_constraints WHERE owner = :remote_owner AND constraint_name = :remote_constraint_name", | |
1069 {'remote_owner': remote_owner, 'remote_constraint_name': remote_constraint_name}) | |
1070 remote_table_name = self.curs.fetchone()[0] | |
1071 result.append("must be in %s:" % (remote_table_name)) | |
1072 self.curs.execute("SELECT column_name FROM all_cons_columns WHERE owner = :remote_owner AND constraint_name = :remote_constraint_name ORDER BY position", | |
1073 {'remote_constraint_name': remote_constraint_name, 'remote_owner': remote_owner}) | |
1074 result.append(' (%s)\n' % (",".join(col[0] for col in self.curs.fetchall()))) | |
1075 remote_table_name = table_name | |
1076 remote_owner = owner | |
1077 self.curs.execute("""SELECT owner, constraint_name, table_name, r_constraint_name | |
1078 FROM all_constraints | |
1079 WHERE (r_owner, r_constraint_name) IN | |
1080 ( SELECT owner, constraint_name | |
1081 FROM all_constraints | |
192
6bb8a112af6b
accept special terminators on most anything
catherine@dellzilla
parents:
191
diff
changeset
|
1082 WHERE table_name = :remote_table_name |
191 | 1083 AND owner = :remote_owner )""", |
1084 {'remote_table_name': remote_table_name, 'remote_owner': remote_owner}) | |
1085 for (owner, constraint_name, table_name, remote_constraint_name) in self.curs.fetchall(): | |
1086 result.append('%s on %s.%s:' % (constraint_name, owner, table_name)) | |
1087 self.curs.execute("SELECT column_name FROM all_cons_columns WHERE owner = :owner AND constraint_name = :constraint_name ORDER BY position", | |
1088 {'constraint_name': constraint_name, 'owner': owner}) | |
1089 result.append(" (%s)" % (",".join(col[0] for col in self.curs.fetchall()))) | |
1090 self.curs.execute("SELECT table_name FROM all_constraints WHERE owner = :remote_owner AND constraint_name = :remote_constraint_name", | |
1091 {'remote_owner': remote_owner, 'remote_constraint_name': remote_constraint_name}) | |
1092 remote_table_name = self.curs.fetchone()[0] | |
1093 result.append("must be in %s:" % (remote_table_name)) | |
1094 self.curs.execute("SELECT column_name FROM all_cons_columns WHERE owner = :remote_owner AND constraint_name = :remote_constraint_name ORDER BY position", | |
1095 {'remote_constraint_name': remote_constraint_name, 'remote_owner': remote_owner}) | |
1096 result.append(' (%s)\n' % (",".join(col[0] for col in self.curs.fetchall()))) | |
1097 self.stdout.write('\n'.join(result) + "\n") | |
190 | 1098 |
189 | 1099 def _test(): |
1100 import doctest | |
1101 doctest.testmod() | |
1102 | |
1103 if __name__ == "__main__": | |
1104 "Silent return implies that all unit tests succeeded. Use -v to see details." | |
1105 _test() | |
198
b2d8bf5f89db
merged with changes from work
catherine@Elli.myhome.westell.com
parents:
196
diff
changeset
|
1106 if __name__ == "__main__": |
b2d8bf5f89db
merged with changes from work
catherine@Elli.myhome.westell.com
parents:
196
diff
changeset
|
1107 "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
|
1108 _test() |