Mercurial > sqlpython
annotate sqlpython/sqlpyPlus.py @ 450:abf71d72f467
make SHOW TABLES work
author | catherine@dellzilla |
---|---|
date | Thu, 11 Feb 2010 16:07:34 -0500 |
parents | 63b9db1814e0 |
children | fd86d22fe00d |
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 """ | |
415 | 26 import sys, os, re, sqlpython, pyparsing, re, completion |
396 | 27 import datetime, pickle, binascii, subprocess, time, itertools, hashlib |
400 | 28 import traceback, operator |
189 | 29 from cmd2 import Cmd, make_option, options, Statekeeper, Cmd2TestCase |
30 from output_templates import output_templates | |
317
f200a222a936
beginning to set up metadata.py
Catherine Devlin <catherine.devlin@gmail.com>
parents:
315
diff
changeset
|
31 from metadata import metaqueries |
189 | 32 from plothandler import Plot |
415 | 33 from sqlpython import Parser, cx_Oracle, psycopg2 |
364
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
34 import imagedetect |
359 | 35 import warnings |
36 warnings.filterwarnings('ignore', 'BaseException.message', DeprecationWarning) | |
189 | 37 try: |
38 import pylab | |
198
b2d8bf5f89db
merged with changes from work
catherine@Elli.myhome.westell.com
parents:
196
diff
changeset
|
39 except (RuntimeError, ImportError): |
189 | 40 pass |
41 | |
42 queries = { | |
43 'resolve': """ | |
44 SELECT object_type, object_name, owner FROM ( | |
335
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
45 SELECT object_type, object_name, user AS owner, 1 priority |
189 | 46 FROM user_objects |
47 WHERE object_name = :objName | |
48 UNION ALL | |
49 SELECT ao.object_type, ao.object_name, ao.owner, 2 priority | |
50 FROM all_objects ao | |
51 JOIN user_synonyms us ON (us.table_owner = ao.owner AND us.table_name = ao.object_name) | |
52 WHERE us.synonym_name = :objName | |
53 AND ao.object_type != 'SYNONYM' | |
54 UNION ALL | |
55 SELECT ao.object_type, ao.object_name, ao.owner, 3 priority | |
56 FROM all_objects ao | |
57 JOIN all_synonyms asyn ON (asyn.table_owner = ao.owner AND asyn.table_name = ao.object_name) | |
58 WHERE asyn.synonym_name = :objName | |
59 AND ao.object_type != 'SYNONYM' | |
60 AND asyn.owner = 'PUBLIC' | |
61 UNION ALL | |
62 SELECT 'DIRECTORY' object_type, dir.directory_name, dir.owner, 6 priority | |
63 FROM all_directories dir | |
64 WHERE dir.directory_name = :objName | |
65 UNION ALL | |
66 SELECT 'DATABASE LINK' object_type, db_link, owner, 7 priority | |
67 FROM all_db_links dbl | |
68 WHERE dbl.db_link = :objName | |
69 ) ORDER BY priority ASC, | |
70 length(object_type) ASC, | |
71 object_type DESC""", # preference: PACKAGE before PACKAGE BODY, TABLE before INDEX | |
72 'tabComments': """ | |
73 SELECT comments | |
74 FROM all_tab_comments | |
75 WHERE owner = :owner | |
76 AND table_name = :table_name""", | |
77 'colComments': """ | |
193 | 78 SELECT |
189 | 79 atc.column_name, |
80 acc.comments | |
81 FROM all_tab_columns atc | |
82 JOIN all_col_comments acc ON (atc.owner = acc.owner and atc.table_name = acc.table_name and atc.column_name = acc.column_name) | |
83 WHERE atc.table_name = :object_name | |
84 AND atc.owner = :owner | |
193 | 85 ORDER BY atc.column_id;""", |
189 | 86 'oneColComments': """ |
371 | 87 SELECT atc.column_name, |
189 | 88 acc.comments |
89 FROM all_tab_columns atc | |
90 JOIN all_col_comments acc ON (atc.owner = acc.owner and atc.table_name = acc.table_name and atc.column_name = acc.column_name) | |
91 WHERE atc.table_name = :object_name | |
92 AND atc.owner = :owner | |
93 AND acc.column_name = :column_name | |
193 | 94 ORDER BY atc.column_id;""", |
189 | 95 #thanks to Senora.pm for "refs" |
96 'refs': """ | |
97 NULL referenced_by, | |
98 c2.table_name references, | |
99 c1.constraint_name constraint | |
100 FROM | |
101 user_constraints c1, | |
102 user_constraints c2 | |
103 WHERE | |
104 c1.table_name = :object_name | |
105 and c1.constraint_type ='R' | |
106 and c1.r_constraint_name = c2.constraint_name | |
107 and c1.r_owner = c2.owner | |
108 and c1.owner = :owner | |
109 UNION | |
110 SELECT c1.table_name referenced_by, | |
111 NULL references, | |
112 c1.constraint_name constraint | |
113 FROM | |
114 user_constraints c1, | |
115 user_constraints c2 | |
116 WHERE | |
117 c2.table_name = :object_name | |
118 and c1.constraint_type ='R' | |
119 and c1.r_constraint_name = c2.constraint_name | |
120 and c1.r_owner = c2.owner | |
121 and c1.owner = :owner | |
122 """ | |
123 } | |
124 | |
125 class SoftwareSearcher(object): | |
126 def __init__(self, softwareList, purpose): | |
127 self.softwareList = softwareList | |
128 self.purpose = purpose | |
129 self.software = None | |
130 def invoke(self, *args): | |
131 if not self.software: | |
132 (self.software, self.invokeString) = self.find() | |
133 argTuple = tuple([self.software] + list(args)) | |
134 os.system(self.invokeString % argTuple) | |
135 def find(self): | |
136 if self.purpose == 'text editor': | |
137 software = os.environ.get('EDITOR') | |
138 if software: | |
139 return (software, '%s %s') | |
140 for (n, (software, invokeString)) in enumerate(self.softwareList): | |
141 if os.path.exists(software): | |
142 if n > (len(self.softwareList) * 0.7): | |
143 print """ | |
144 | |
145 Using %s. Note that there are better options available for %s, | |
146 but %s couldn't find a better one in your PATH. | |
147 Feel free to open up %s | |
148 and customize it to find your favorite %s program. | |
149 | |
150 """ % (software, self.purpose, __file__, __file__, self.purpose) | |
151 return (software, invokeString) | |
152 stem = os.path.split(software)[1] | |
153 for p in os.environ['PATH'].split(os.pathsep): | |
154 if os.path.exists(os.sep.join([p, stem])): | |
155 return (stem, invokeString) | |
156 raise (OSError, """Could not find any %s programs. You will need to install one, | |
157 or customize %s to make it aware of yours. | |
158 Looked for these programs: | |
159 %s""" % (self.purpose, __file__, "\n".join([s[0] for s in self.softwareList]))) | |
160 | |
161 softwareLists = { | |
162 'diff/merge': [ | |
163 ('/usr/bin/meld',"%s %s %s"), | |
164 ('/usr/bin/kdiff3',"%s %s %s"), | |
165 (r'C:\Program Files\Araxis\Araxis Merge v6.5\Merge.exe','"%s" %s %s'), | |
166 (r'C:\Program Files\TortoiseSVN\bin\TortoiseMerge.exe', '"%s" /base:"%s" /mine:"%s"'), | |
167 ('FileMerge','%s %s %s'), | |
168 ('kompare','%s %s %s'), | |
169 ('WinMerge','%s %s %s'), | |
170 ('xxdiff','%s %s %s'), | |
171 ('fldiff','%s %s %s'), | |
172 ('gtkdiff','%s %s %s'), | |
173 ('tkdiff','%s %s %s'), | |
174 ('gvimdiff','%s %s %s'), | |
175 ('diff',"%s %s %s"), | |
176 (r'c:\windows\system32\comp.exe',"%s %s %s")], | |
177 'text editor': [ | |
178 ('gedit', '%s %s'), | |
179 ('textpad', '%s %s'), | |
180 ('notepad.exe', '%s %s'), | |
181 ('pico', '%s %s'), | |
182 ('emacs', '%s %s'), | |
183 ('vim', '%s %s'), | |
184 ('vi', '%s %s'), | |
185 ('ed', '%s %s'), | |
186 ('edlin', '%s %s') | |
187 ] | |
188 } | |
189 | |
190 diffMergeSearcher = SoftwareSearcher(softwareLists['diff/merge'],'diff/merge') | |
191 editSearcher = SoftwareSearcher(softwareLists['text editor'], 'text editor') | |
192 editor = os.environ.get('EDITOR') | |
193 if editor: | |
194 editSearcher.find = lambda: (editor, "%s %s") | |
394
58e6d66794b0
refactoring _matching_database_objects to return MetaData
catherine@DellZilla
parents:
393
diff
changeset
|
195 |
58e6d66794b0
refactoring _matching_database_objects to return MetaData
catherine@DellZilla
parents:
393
diff
changeset
|
196 |
189 | 197 class CaselessDict(dict): |
198 """dict with case-insensitive keys. | |
199 | |
200 Posted to ASPN Python Cookbook by Jeff Donner - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66315""" | |
201 def __init__(self, other=None): | |
202 if other: | |
203 # Doesn't do keyword args | |
204 if isinstance(other, dict): | |
205 for k,v in other.items(): | |
206 dict.__setitem__(self, k.lower(), v) | |
207 else: | |
208 for k,v in other: | |
209 dict.__setitem__(self, k.lower(), v) | |
210 def __getitem__(self, key): | |
211 return dict.__getitem__(self, key.lower()) | |
212 def __setitem__(self, key, value): | |
273
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
213 try: |
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
214 key = key.lower() |
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
215 except AttributeError: |
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
216 pass |
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
217 dict.__setitem__(self, key, value) |
189 | 218 def __contains__(self, key): |
219 return dict.__contains__(self, key.lower()) | |
220 def has_key(self, key): | |
221 return dict.has_key(self, key.lower()) | |
222 def get(self, key, def_val=None): | |
223 return dict.get(self, key.lower(), def_val) | |
224 def setdefault(self, key, def_val=None): | |
225 return dict.setdefault(self, key.lower(), def_val) | |
226 def update(self, other): | |
227 for k,v in other.items(): | |
228 dict.__setitem__(self, k.lower(), v) | |
229 def fromkeys(self, iterable, value=None): | |
230 d = CaselessDict() | |
231 for k in iterable: | |
232 dict.__setitem__(d, k.lower(), value) | |
233 return d | |
234 def pop(self, key, def_val=None): | |
235 return dict.pop(self, key.lower(), def_val) | |
236 | |
271 | 237 class ResultSet(list): |
238 pass | |
239 | |
240 class Result(tuple): | |
241 def __str__(self): | |
272 | 242 return '\n'.join('%s: %s' % (colname, self[idx]) |
243 for (idx, colname) in enumerate(self.resultset.colnames)) | |
271 | 244 def __getattr__(self, attr): |
245 attr = attr.lower() | |
246 try: | |
247 return self[self.resultset.colnames.index(attr)] | |
248 except ValueError: | |
307 | 249 if attr in ('colnames', 'statement', 'bindvars', 'resultset'): |
271 | 250 return getattr(self.resultset, attr) |
251 else: | |
252 raise AttributeError, "available columns are: " + ", ".join(self.resultset.colnames) | |
273
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
253 def bind(self): |
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
254 for (idx, colname) in enumerate(self.resultset.colnames): |
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
255 self.resultset.pystate['binds'][colname] = self[idx] |
277 | 256 self.resultset.pystate['binds'][str(idx+1)] = self[idx] |
271 | 257 |
288 | 258 def centeredSlice(lst, center=0, width=1): |
259 width = max(width, -1) | |
260 if center < 0: | |
261 end = center + width + 1 | |
262 if end >= 0: | |
263 end = None | |
264 return lst[center-width:end] | |
265 else: | |
266 return lst[max(center-width,0):center+width+1] | |
267 | |
360 | 268 |
269 def offset_to_line(instring, offset): | |
270 r""" | |
271 >>> offset_to_line('abcdefghijkl', 5) | |
272 (0, 'abcdefghijkl', 5) | |
273 >>> offset_to_line('ab\ncd\nefg', 6) | |
274 (2, 'efg', 0) | |
275 >>> offset_to_line('ab\ncd\nefg', 5) | |
276 (1, 'cd\n', 2) | |
277 >>> offset_to_line('abcdefghi\njkl', 5) | |
278 (0, 'abcdefghi\n', 5) | |
279 >>> offset_to_line('abcdefghi\njkl', 700) | |
280 | |
281 """ | |
282 lineNum = 0 | |
283 for line in instring.splitlines(True): | |
284 if offset < len(line): | |
285 return lineNum, line, offset | |
286 lineNum += 1 | |
287 offset -= len(line) | |
364
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
288 |
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
289 class BlobDisplayer(object): |
366 | 290 folder_name = 'sqlpython_blob_store' |
367 | 291 imgwidth = 400 |
364
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
292 def folder_ok(self): |
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
293 if not os.access(self.folder_name, os.F_OK): |
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
294 try: |
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
295 os.mkdir(self.folder_name) |
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
296 readme = open(os.path.join(self.folder_name, 'README.txt'),'w') |
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
297 readme.write(''' |
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
298 Temporary files for display of BLOBs from within |
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
299 sqlpython. Delete when sqlpython is closed.''') |
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
300 readme.close() |
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
301 except: |
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
302 return False |
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
303 return True |
367 | 304 def __init__(self, blob, under_limit): |
364
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
305 self.url = '' |
367 | 306 if under_limit: |
307 self.blob = blob.read() | |
308 self.hashed = hashlib.md5(self.blob).hexdigest() | |
309 self.extension = imagedetect.extension_from_data(self.blob) | |
310 if self.folder_ok(): | |
311 self.file_name = '%s/%s%s' % ( | |
312 os.path.join(os.getcwd(), self.folder_name), | |
313 self.hashed, self.extension) | |
314 self.url = 'file://%s' % self.file_name | |
315 if not os.access(self.file_name, os.F_OK): | |
316 outfile = open(self.file_name, 'wb') | |
317 outfile.write(self.blob) | |
318 outfile.close() | |
364
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
319 def __str__(self): |
367 | 320 if self.url: |
321 return '(BLOB at %s)' % self.url | |
322 else: | |
323 return '(BLOB)' | |
364
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
324 def html(self): |
367 | 325 if self.url: |
326 return '<a href="%s"><img src="%s" width="%d" /></a>' % ( | |
327 self.url, self.url, self.imgwidth) | |
328 else: | |
329 return '(BLOB not saved, check bloblimit)' | |
360 | 330 |
407 | 331 class Abbreviatable_List(list): |
332 def match(self, target): | |
333 target = target.lower() | |
334 result = [i for i in self if i.startswith(target)] | |
335 if len(result) == 0: | |
336 raise ValueError, 'None of %s start with %s' % (str(self), target) | |
337 elif len(result) > 1: | |
338 raise ValueError, 'Too many matches: %s' % str(result) | |
339 return result[0] | |
340 | |
189 | 341 class sqlpyPlus(sqlpython.sqlpython): |
342 defaultExtension = 'sql' | |
289
3cade02da892
replacing manual abbreviations with abbrev param
catherine@Elli.myhome.westell.com
parents:
285
diff
changeset
|
343 abbrev = True |
189 | 344 sqlpython.sqlpython.shortcuts.update({':': 'setbind', |
345 '\\': 'psql', | |
286 | 346 '@': 'get'}) |
189 | 347 multilineCommands = '''select insert update delete tselect |
348 create drop alter _multiline_comment'''.split() | |
349 sqlpython.sqlpython.noSpecialParse.append('spool') | |
428 | 350 prefixParser = pyparsing.Optional(pyparsing.Word(pyparsing.nums)('instance_number') |
259
c0847a4c7f49
one-shot connection changes
catherine@Elli.myhome.westell.com
parents:
257
diff
changeset
|
351 + ':') |
309
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
352 reserved_words = [ |
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
353 'alter', 'begin', 'comment', 'create', 'delete', 'drop', 'end', 'for', 'grant', |
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
354 'insert', 'intersect', 'lock', 'minus', 'on', 'order', 'rename', |
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
355 'resource', 'revoke', 'select', 'share', 'start', 'union', 'update', |
0d16630d8e04
added table comment to desc -l
catherine@Elli.myhome.westell.com
parents:
308
diff
changeset
|
356 'where', 'with'] |
247 | 357 default_file_name = 'afiedt.buf' |
417 | 358 settable = sqlpython.sqlpython.settable + ''' |
359 autobind Always fill bind variables from final row | |
360 bloblimit Max # of BLOBs to copy to disk for each query | |
361 colors colorize query results (*nix only) | |
362 commit_on_exit automatically COMMIT when exiting program | |
363 default_rdbms | |
364 maxfetch limit # of rows fetched | |
365 maxtselctrows max # rows in transposed results | |
366 rows_remembered # rows stored in ``r`` for python access | |
367 scan interpolate substitution variables | |
368 serveroutput send dbms_output.put_line to screen (Oracle) | |
369 sql_echo echo SQL commands | |
416
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
370 timeout |
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
371 heading |
417 | 372 wildsql Accept wildcards, position #s in column names |
449 | 373 version''' |
417 | 374 |
189 | 375 def __init__(self): |
376 sqlpython.sqlpython.__init__(self) | |
377 self.binds = CaselessDict() | |
417 | 378 self.settable.pop('case_insensitive') |
189 | 379 self.stdoutBeforeSpool = sys.stdout |
249 | 380 self.sql_echo = False |
189 | 381 self.spoolFile = None |
382 self.autobind = False | |
229 | 383 self.heading = True |
240 | 384 self.wildsql = False |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
385 self.serveroutput = True |
271 | 386 self.scan = True |
387 self.substvars = {} | |
388 self.result_history = [] | |
330
8dd71d47f3cb
merged with rows_remembered
Catherine Devlin <catherine.devlin@gmail.com>
diff
changeset
|
389 self.rows_remembered = 10000 |
367 | 390 self.bloblimit = 5 |
407 | 391 self.default_rdbms = 'oracle' |
392 self.rdbms_supported = Abbreviatable_List('oracle postgres mysql'.split()) | |
370 | 393 self.version = 'SQLPython %s' % sqlpython.__version__ |
284 | 394 self.pystate = {'r': [], 'binds': self.binds, 'substs': self.substvars} |
438
39a664a87c51
excluded --options from --comments with .NotAny
catherine@bothari
parents:
437
diff
changeset
|
395 self.commentGrammars = pyparsing.Or([pyparsing.cStyleComment, self.doubleDashComment]) |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
396 |
189 | 397 # overrides cmd's parseline |
398 def parseline(self, line): | |
399 """Parse the line into a command name and a string containing | |
400 the arguments. Returns a tuple containing (command, args, line). | |
401 'command' and 'args' may be None if the line couldn't be parsed. | |
402 Overrides cmd.cmd.parseline to accept variety of shortcuts..""" | |
403 | |
404 cmd, arg, line = sqlpython.sqlpython.parseline(self, line) | |
405 if cmd in ('select', 'sleect', 'insert', 'update', 'delete', 'describe', | |
406 'desc', 'comments', 'pull', 'refs', 'desc', 'triggers', 'find') \ | |
407 and not hasattr(self, 'curs'): | |
333 | 408 self.perror('Not connected.') |
189 | 409 return '', '', '' |
410 return cmd, arg, line | |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
411 |
359 | 412 def perror(self, err, statement=None): |
396 | 413 if self.debug: |
414 traceback.print_exc() | |
359 | 415 try: |
360 | 416 linenum, line, offset = offset_to_line(statement.parsed.raw, err.message.offset) |
417 print line.strip() | |
418 print '%s*' % (' ' * offset) | |
419 print 'ERROR at line %d:' % (linenum + 1) | |
359 | 420 except AttributeError: |
396 | 421 pass |
359 | 422 print str(err) |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
423 def dbms_output(self): |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
424 "Dumps contents of Oracle's DBMS_OUTPUT buffer (where PUT_LINE goes)" |
261 | 425 try: |
415 | 426 line = self.curs.var(cx_Oracle.STRING) # TODO: would regular string and number work? |
261 | 427 status = self.curs.var(cx_Oracle.NUMBER) |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
428 self.curs.callproc('dbms_output.get_line', [line, status]) |
261 | 429 while not status.getvalue(): |
356
c86177642f75
replacing stdout with poutput; no bracketing partial pulls with remarks
catherine@cordelia
parents:
355
diff
changeset
|
430 self.poutput(line.getvalue()) |
c86177642f75
replacing stdout with poutput; no bracketing partial pulls with remarks
catherine@cordelia
parents:
355
diff
changeset
|
431 self.poutput('\n') |
261 | 432 self.curs.callproc('dbms_output.get_line', [line, status]) |
433 except AttributeError: | |
434 pass | |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
435 |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
436 def postcmd(self, stop, line): |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
437 """Hook method executed just after a command dispatch is finished.""" |
371 | 438 if ( hasattr(self, 'rdbms') |
439 and (self.rdbms == 'oracle') | |
440 and self.serveroutput): | |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
441 self.dbms_output() |
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
442 return stop |
241 | 443 |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
444 def do_remark(self, line): |
242 | 445 ''' |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
446 REMARK is one way to denote a comment in SQL*Plus. |
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
447 |
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
448 Wrapping a *single* SQL or PL/SQL statement in `REMARK BEGIN` and `REMARK END` |
241 | 449 tells sqlpython to submit the enclosed code directly to Oracle as a single |
242 | 450 unit of code. |
241 | 451 |
452 Without these markers, sqlpython fails to properly distinguish the beginning | |
453 and end of all but the simplest PL/SQL blocks, causing errors. sqlpython also | |
454 slows down when parsing long SQL statements as it tries to determine whether | |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
455 the statement has ended yet; `REMARK BEGIN` and `REMARK END` allow it to skip this |
241 | 456 parsing. |
457 | |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
458 Standard SQL*Plus interprets REMARK BEGIN and REMARK END as comments, so it is |
242 | 459 safe to include them in SQL*Plus scripts. |
241 | 460 ''' |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
461 if not line.lower().strip().startswith('begin'): |
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
462 return |
241 | 463 statement = [] |
247 | 464 next = self.pseudo_raw_input(self.continuation_prompt) |
245
05c90f80815c
trying REMARK BEGIN / REMARK END
catherine@Elli.myhome.westell.com
parents:
244
diff
changeset
|
465 while next.lower().split()[:2] != ['remark','end']: |
241 | 466 statement.append(next) |
247 | 467 next = self.pseudo_raw_input(self.continuation_prompt) |
242 | 468 return self.onecmd('\n'.join(statement)) |
272 | 469 |
292 | 470 def do_py(self, arg): |
272 | 471 ''' |
472 py <command>: Executes a Python command. | |
297 | 473 py: Enters interactive Python mode. |
474 End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, 'exit()`. | |
292 | 475 Past SELECT results are exposed as list `r`; |
275 | 476 most recent resultset is `r[-1]`. |
292 | 477 SQL bind, substitution variables are exposed as `binds`, `substs`. |
296 | 478 SQL and sqlpython commands can be issued with `sql("your command")`. |
272 | 479 ''' |
292 | 480 return Cmd.do_py(self, arg) |
284 | 481 |
482 def do_get(self, args): | |
483 """ | |
484 `get {script.sql}` or `@{script.sql}` runs the command(s) in {script.sql}. | |
485 If additional arguments are supplied, they are assigned to &1, &2, etc. | |
486 """ | |
487 fname, args = args.split()[0], args.split()[1:] | |
488 for (idx, arg) in enumerate(args): | |
489 self.substvars[str(idx+1)] = arg | |
490 return Cmd.do__load(self, fname) | |
491 | |
189 | 492 def onecmd_plus_hooks(self, line): |
493 line = self.precmd(line) | |
494 stop = self.onecmd(line) | |
495 stop = self.postcmd(stop, line) | |
496 | |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
497 def _onchange_serveroutput(self, old, new): |
317
f200a222a936
beginning to set up metadata.py
Catherine Devlin <catherine.devlin@gmail.com>
parents:
315
diff
changeset
|
498 if (self.rdbms == 'oracle'): |
315 | 499 if new: |
500 self.curs.callproc('dbms_output.enable', []) | |
501 else: | |
502 self.curs.callproc('dbms_output.disable', []) | |
257
6d4d90fb2082
dbms_output.put_line working
catherine@Elli.myhome.westell.com
parents:
254
diff
changeset
|
503 |
189 | 504 def do_shortcuts(self,arg): |
505 """Lists available first-character shortcuts | |
506 (i.e. '!dir' is equivalent to 'shell dir')""" | |
335
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
507 for (scchar, scto) in self.shortcuts: |
333 | 508 self.poutput('%s: %s' % (scchar, scto)) |
189 | 509 |
254
b61e21386383
oops, restore lines of code after sql_format_item
catherine@Elli.myhome.westell.com
parents:
253
diff
changeset
|
510 tableNameFinder = re.compile(r'from\s+([\w$#_"]+)', re.IGNORECASE | re.MULTILINE | re.DOTALL) |
322
d791333902f7
handle NULLs and apostrophes in \i inserts
Catherine Devlin <catherine.devlin@gmail.com>
parents:
318
diff
changeset
|
511 def formattedForSql(self, datum): |
d791333902f7
handle NULLs and apostrophes in \i inserts
Catherine Devlin <catherine.devlin@gmail.com>
parents:
318
diff
changeset
|
512 if datum is None: |
d791333902f7
handle NULLs and apostrophes in \i inserts
Catherine Devlin <catherine.devlin@gmail.com>
parents:
318
diff
changeset
|
513 return 'NULL' |
d791333902f7
handle NULLs and apostrophes in \i inserts
Catherine Devlin <catherine.devlin@gmail.com>
parents:
318
diff
changeset
|
514 elif isinstance(datum, basestring): |
334
1e199ea5b846
fixed single-quote inclusion
Catherine Devlin <catherine.devlin@gmail.com>
parents:
332
diff
changeset
|
515 return "'%s'" % datum.replace("'","''") |
322
d791333902f7
handle NULLs and apostrophes in \i inserts
Catherine Devlin <catherine.devlin@gmail.com>
parents:
318
diff
changeset
|
516 try: |
d791333902f7
handle NULLs and apostrophes in \i inserts
Catherine Devlin <catherine.devlin@gmail.com>
parents:
318
diff
changeset
|
517 return datum.strftime("TO_DATE('%Y-%m-%d %H:%M:%S', 'YYYY-MM-DD HH24:MI:SS')") |
d791333902f7
handle NULLs and apostrophes in \i inserts
Catherine Devlin <catherine.devlin@gmail.com>
parents:
318
diff
changeset
|
518 except AttributeError: |
334
1e199ea5b846
fixed single-quote inclusion
Catherine Devlin <catherine.devlin@gmail.com>
parents:
332
diff
changeset
|
519 return str(datum) |
322
d791333902f7
handle NULLs and apostrophes in \i inserts
Catherine Devlin <catherine.devlin@gmail.com>
parents:
318
diff
changeset
|
520 |
401 | 521 def tabular_output(self, outformat, tblname=None): |
400 | 522 if tblname: |
523 self.tblname = tblname | |
524 else: | |
525 try: | |
526 self.tblname = self.tableNameFinder.search(self.querytext).group(1) | |
527 except AttributeError: | |
528 self.tblname = '' | |
189 | 529 if outformat in output_templates: |
530 self.colnamelen = max(len(colname) for colname in self.colnames) | |
322
d791333902f7
handle NULLs and apostrophes in \i inserts
Catherine Devlin <catherine.devlin@gmail.com>
parents:
318
diff
changeset
|
531 result = output_templates[outformat].generate(formattedForSql=self.formattedForSql, **self.__dict__) |
189 | 532 elif outformat == '\\t': # transposed |
533 rows = [self.colnames] | |
534 rows.extend(list(self.rows)) | |
535 transpr = [[rows[y][x] for y in range(len(rows))]for x in range(len(rows[0]))] # matrix transpose | |
536 newdesc = [['ROW N.'+str(y),10] for y in range(len(rows))] | |
399 | 537 for x in range(len(self.coltypes)): |
538 if str(self.coltypes[x]) == "<type 'cx_Oracle.BINARY'>": # handles RAW columns | |
189 | 539 rname = transpr[x][0] |
540 transpr[x] = map(binascii.b2a_hex, transpr[x]) | |
541 transpr[x][0] = rname | |
401 | 542 self.colnames = ['ROW N.%d' % y for y in range(len(rows))] |
543 self.colnames[0] = 'COLUMN NAME' | |
544 self.coltypes = [str] * len(self.colnames) | |
545 result = '\n' + self.pmatrix(transpr) | |
189 | 546 elif outformat in ('\\l', '\\L', '\\p', '\\b'): |
547 plot = Plot() | |
548 plot.build(self, outformat) | |
549 plot.shelve() | |
550 plot.draw() | |
551 return '' | |
552 else: | |
400 | 553 result = self.pmatrix(self.rows, |
337 | 554 self.maxfetch, heading=self.heading, |
555 restructuredtext = (outformat == '\\r')) | |
189 | 556 return result |
557 | |
558 legalOracle = re.compile('[a-zA-Z_$#]') | |
559 | |
560 def select_scalar_list(self, sql, binds={}): | |
249 | 561 self._execute(sql, binds) |
189 | 562 return [r[0] for r in self.curs.fetchall()] |
563 | |
564 columnNameRegex = re.compile( | |
565 r'select\s+(.*)from', | |
566 re.IGNORECASE | re.DOTALL | re.MULTILINE) | |
567 def completedefault(self, text, line, begidx, endidx): | |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
568 (username, gerald_schema) = self.metadata() |
419 | 569 segment = completion.whichSegment(line) |
189 | 570 text = text.upper() |
406 | 571 if segment in ('select', 'where', 'having', 'set', 'order by', 'group by'): |
405 | 572 completions = [c for c in schemas[username].column_names if c.startswith(text)] \ |
573 or [c for c in schemas.qual_column_names if c.startswith(text)] | |
574 # TODO: the latter not working | |
406 | 575 elif segment in ('from', 'update', 'insert into'): |
419 | 576 # print schemas[username].table_names |
577 # TODO: from postgres, these table names are jrrt.fishies, etc. | |
405 | 578 completions = [t for t in schemas[username].table_names if t.startswith(text)] |
406 | 579 elif segment == 'beginning': |
580 completions = [n for n in self.get_names() if n.startswith('do_')] + [ | |
581 'insert', 'update', 'delete', 'drop', 'alter', 'begin', 'declare', 'create'] | |
582 completions = [c for c in completions if c.startswith(text)] | |
407 | 583 elif segment: |
584 completions = [t for t in schemas[username].table_names if t.startswith(text)] | |
406 | 585 else: |
586 completions = [r for r in completion.reserved if r.startswith(text)] | |
189 | 587 return completions |
406 | 588 |
234
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
589 columnlistPattern = pyparsing.SkipTo(pyparsing.CaselessKeyword('from'))('columns') + \ |
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
590 pyparsing.SkipTo(pyparsing.stringEnd)('remainder') |
233 | 591 |
236 | 592 negator = pyparsing.Literal('!')('exclude') |
242 | 593 colNumber = pyparsing.Optional(negator) + pyparsing.Literal('#') + pyparsing.Word('-' + pyparsing.nums, pyparsing.nums)('column_number') |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
594 colName = negator + pyparsing.Word('$_#' + pyparsing.alphas, '$_#' + pyparsing.alphanums)('column_name') |
241 | 595 wildColName = pyparsing.Optional(negator) + pyparsing.Word('?*%$_#' + pyparsing.alphas, '?*%$_#' + pyparsing.alphanums, min=2)('column_name') |
242 | 596 colNumber.ignore(pyparsing.cStyleComment).ignore(Parser.comment_def). \ |
597 ignore(pyparsing.sglQuotedString).ignore(pyparsing.dblQuotedString) | |
235 | 598 wildSqlParser = colNumber ^ colName ^ wildColName |
599 wildSqlParser.ignore(pyparsing.cStyleComment).ignore(Parser.comment_def). \ | |
236 | 600 ignore(pyparsing.sglQuotedString).ignore(pyparsing.dblQuotedString) |
601 emptyCommaRegex = re.compile(',\s*,', re.DOTALL) | |
602 deadStarterCommaRegex = re.compile('^\s*,', re.DOTALL) | |
603 deadEnderCommaRegex = re.compile(',\s*$', re.DOTALL) | |
233 | 604 def expandWildSql(self, arg): |
605 try: | |
234
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
606 columnlist = self.columnlistPattern.parseString(arg) |
233 | 607 except pyparsing.ParseException: |
608 return arg | |
236 | 609 parseresults = list(self.wildSqlParser.scanString(columnlist.columns)) |
239
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
610 # I would rather exclude non-wild column names in the grammar, |
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
611 # but can't figure out how |
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
612 parseresults = [p for p in parseresults if |
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
613 p[0].column_number or |
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
614 '*' in p[0].column_name or |
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
615 '%' in p[0].column_name or |
241 | 616 '?' in p[0].column_name or |
239
4c563c2218e6
catching standard names caught
catherine@Elli.myhome.westell.com
parents:
238
diff
changeset
|
617 p[0].exclude] |
236 | 618 if not parseresults: |
619 return arg | |
234
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
620 self.curs.execute('select * ' + columnlist.remainder, self.varsUsed) |
236 | 621 columns_available = [d[0] for d in self.curs.description] |
234
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
622 replacers = {} |
236 | 623 included = set() |
624 excluded = set() | |
625 for (col, startpos, endpos) in parseresults: | |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
626 replacers[arg[startpos:endpos]] = [] |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
627 if col.column_name: |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
628 finder = col.column_name.replace('*','.*') |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
629 finder = finder.replace('%','.*') |
241 | 630 finder = finder.replace('?','.') |
631 colnames = [c for c in columns_available if re.match(finder + '$', c, re.IGNORECASE)] | |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
632 elif col.column_number: |
236 | 633 idx = int(col.column_number) |
634 if idx > 0: | |
635 idx -= 1 | |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
636 colnames = [columns_available[idx]] |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
637 if not colnames: |
333 | 638 self.pfeedback('No columns found matching criteria.') |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
639 return 'null from dual' |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
640 for colname in colnames: |
236 | 641 if col.exclude: |
642 included.discard(colname) | |
643 include_here = columns_available[:] | |
644 include_here.remove(colname) | |
240 | 645 replacers[arg[startpos:endpos]].extend(i for i in include_here if i not in replacers[arg[startpos:endpos]]) |
236 | 646 excluded.add(colname) |
647 else: | |
648 excluded.discard(colname) | |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
649 replacers[arg[startpos:endpos]].append(colname) |
236 | 650 |
234
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
651 replacers = sorted(replacers.items(), key=len, reverse=True) |
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
652 result = columnlist.columns |
236 | 653 for (target, replacement) in replacers: |
242 | 654 cols = [r for r in replacement if r not in excluded and r not in included] |
238
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
655 replacement = ', '.join(cols) |
254fb9d3f4c3
must fix catching regular cols as wilds, repeating on eqdbw/mtndew@orcl
catherine@Elli.myhome.westell.com
parents:
237
diff
changeset
|
656 included.update(cols) |
236 | 657 result = result.replace(target, replacement) |
242 | 658 # some column names could get wiped out completely, so we fix their dangling commas |
236 | 659 result = self.emptyCommaRegex.sub(',', result) |
660 result = self.deadStarterCommaRegex.sub('', result) | |
661 result = self.deadEnderCommaRegex.sub('', result) | |
242 | 662 if not result.strip(): |
333 | 663 self.pfeedback('No columns found matching criteria.') |
242 | 664 return 'null from dual' |
237 | 665 return result + ' ' + columnlist.remainder |
284 | 666 |
333 | 667 do_prompt = Cmd.poutput |
233 | 668 |
284 | 669 def do_accept(self, args): |
670 try: | |
671 prompt = args[args.lower().index('prompt ')+7:] | |
672 except ValueError: | |
673 prompt = '' | |
674 varname = args.lower().split()[0] | |
675 self.substvars[varname] = self.pseudo_raw_input(prompt) | |
416
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
676 |
281 | 677 def ampersand_substitution(self, raw, regexpr, isglobal): |
271 | 678 subst = regexpr.search(raw) |
679 while subst: | |
680 fullexpr, var = subst.group(1), subst.group(2) | |
333 | 681 self.pfeedback('Substitution variable %s found in:' % fullexpr) |
682 self.pfeedback(raw[max(subst.start()-20, 0):subst.end()+20]) | |
284 | 683 if var in self.substvars: |
271 | 684 val = self.substvars[var] |
685 else: | |
686 val = raw_input('Substitution for %s (SET SCAN OFF to halt substitution): ' % fullexpr) | |
687 if val.lower().split() == ['set','scan','off']: | |
688 self.scan = False | |
689 return raw | |
690 if isglobal: | |
691 self.substvars[var] = val | |
692 raw = raw.replace(fullexpr, val) | |
333 | 693 self.pfeedback('Substituted %s for %s' % (val, fullexpr)) |
271 | 694 subst = regexpr.search(raw) # do not FINDALL b/c we don't want to ask twice |
695 return raw | |
284 | 696 |
419 | 697 doublenumericampre = re.compile('(&&(\d+))') |
698 numericampre = re.compile('(&(\d+))') | |
284 | 699 doubleampre = re.compile('(&&([a-zA-Z\d_$#]+))', re.IGNORECASE) |
700 singleampre = re.compile( '(&([a-zA-Z\d_$#]+))', re.IGNORECASE) | |
271 | 701 def preparse(self, raw, **kwargs): |
702 if self.scan: | |
419 | 703 raw = self.ampersand_substitution(raw, regexpr=self.doublenumericampre, isglobal=True) |
704 if self.scan: | |
284 | 705 raw = self.ampersand_substitution(raw, regexpr=self.numericampre, isglobal=False) |
706 if self.scan: | |
281 | 707 raw = self.ampersand_substitution(raw, regexpr=self.doubleampre, isglobal=True) |
271 | 708 if self.scan: |
281 | 709 raw = self.ampersand_substitution(raw, regexpr=self.singleampre, isglobal=False) |
271 | 710 return raw |
711 | |
189 | 712 rowlimitPattern = pyparsing.Word(pyparsing.nums)('rowlimit') |
308 | 713 terminators = '; \\C \\t \\i \\p \\l \\L \\b \\r'.split() + output_templates.keys() |
199
09592342a33d
ugh - parsing stripping command causes real trouble
catherine@dellzilla
parents:
198
diff
changeset
|
714 |
281 | 715 @options([make_option('-r', '--row', type="int", default=-1, |
716 help='Bind row #ROW instead of final row (zero-based)')]) | |
314 | 717 def do_bind(self, arg, opts): |
281 | 718 ''' |
416
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
719 Inserts the results from the final row in the last completed |
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
720 SELECT statement into bind variables with names corresponding |
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
721 to the column names. When the optional `autobind` setting is |
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
722 on, this will be issued automatically after every query that |
281 | 723 returns exactly one row. |
724 ''' | |
725 try: | |
726 self.pystate['r'][-1][opts.row].bind() | |
727 except IndexError: | |
333 | 728 self.poutput(self.do_bind.__doc__) |
271 | 729 |
327
7cc5cc19891f
added rows_remembered
Catherine Devlin <catherine.devlin@gmail.com>
parents:
326
diff
changeset
|
730 def age_out_resultsets(self): |
7cc5cc19891f
added rows_remembered
Catherine Devlin <catherine.devlin@gmail.com>
parents:
326
diff
changeset
|
731 total_len = sum(len(rs) for rs in self.pystate['r']) |
328
b2fbb9de8845
avoid infinite loop when r[-1] > rows_remembered
Catherine Devlin <catherine.devlin@gmail.com>
parents:
327
diff
changeset
|
732 for (i, rset) in enumerate(self.pystate['r'][:-1]): |
b2fbb9de8845
avoid infinite loop when r[-1] > rows_remembered
Catherine Devlin <catherine.devlin@gmail.com>
parents:
327
diff
changeset
|
733 if total_len <= self.rows_remembered: |
b2fbb9de8845
avoid infinite loop when r[-1] > rows_remembered
Catherine Devlin <catherine.devlin@gmail.com>
parents:
327
diff
changeset
|
734 return |
b2fbb9de8845
avoid infinite loop when r[-1] > rows_remembered
Catherine Devlin <catherine.devlin@gmail.com>
parents:
327
diff
changeset
|
735 total_len -= len(rset) |
b2fbb9de8845
avoid infinite loop when r[-1] > rows_remembered
Catherine Devlin <catherine.devlin@gmail.com>
parents:
327
diff
changeset
|
736 self.pystate['r'][i] = [] |
364
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
737 |
399 | 738 def rowlimit(self, arg): |
739 try: | |
401 | 740 rowlimit = int(arg.parsed.suffix) |
741 except (TypeError, ValueError): | |
742 rowlimit = None | |
399 | 743 if arg.parsed.terminator == '\\t': |
744 rowlimit = rowlimit or self.maxtselctrows | |
745 return rowlimit | |
746 | |
192
6bb8a112af6b
accept special terminators on most anything
catherine@dellzilla
parents:
191
diff
changeset
|
747 def do_select(self, arg, bindVarsIn=None, terminator=None): |
189 | 748 """Fetch rows from a table. |
749 | |
750 Limit the number of rows retrieved by appending | |
751 an integer after the terminator | |
752 (example: SELECT * FROM mytable;10 ) | |
753 | |
754 Output may be formatted by choosing an alternative terminator | |
755 ("help terminators" for details) | |
756 """ | |
757 bindVarsIn = bindVarsIn or {} | |
399 | 758 rowlimit = self.rowlimit(arg) |
340
001d01eeac90
bind vars for postgres
Catherine Devlin <catherine.devlin@gmail.com>
parents:
339
diff
changeset
|
759 self.varsUsed = self.findBinds(arg, bindVarsIn) |
233 | 760 if self.wildsql: |
234
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
761 selecttext = self.expandWildSql(arg) |
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
762 else: |
a86efbca3da9
ha ha ha - wildcards in selects working now
catherine@dellzilla
parents:
233
diff
changeset
|
763 selecttext = arg |
315 | 764 self.querytext = 'select ' + selecttext |
335
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
765 if self.varsUsed: |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
766 self.curs.execute(self.querytext, self.varsUsed) |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
767 else: # this is an ugly workaround for the evil paramstyle curse upon DB-API2 |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
768 self.curs.execute(self.querytext) |
194 | 769 self.rows = self.curs.fetchmany(min(self.maxfetch, (rowlimit or self.maxfetch))) |
399 | 770 self.colnames = [d[0] for d in self.curs.description] |
364
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
771 self.coltypes = [d[1] for d in self.curs.description] |
415 | 772 #TODO: Other databases can have BLOBs, too |
773 if cx_Oracle and (cx_Oracle.BLOB in self.coltypes): | |
364
ea6d35cb6c73
images work, except brackets get escaped
catherine@cordelia
parents:
361
diff
changeset
|
774 self.rows = [ |
367 | 775 [( (coltype == cx_Oracle.BLOB) |
776 and BlobDisplayer(datum, (rownum < self.bloblimit))) | |
777 or datum | |
778 for (datum, coltype) in zip(row, self.coltypes)] | |
779 for (rownum, row) in enumerate(self.rows)] | |
326
82937b8dcbfe
very basic multi-RDBMS ls in place
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
780 self.rc = len(self.rows) |
315 | 781 if self.rc != 0: |
271 | 782 resultset = ResultSet() |
783 resultset.colnames = [d[0].lower() for d in self.curs.description] | |
281 | 784 resultset.pystate = self.pystate |
271 | 785 resultset.statement = 'select ' + selecttext |
273
9d67065ea030
data into/out of py via binds
catherine@Elli.myhome.westell.com
parents:
272
diff
changeset
|
786 resultset.varsUsed = self.varsUsed |
271 | 787 resultset.extend([Result(r) for r in self.rows]) |
788 for row in resultset: | |
789 row.resultset = resultset | |
281 | 790 self.pystate['r'].append(resultset) |
399 | 791 self.age_out_resultsets() |
401 | 792 self.poutput('\n%s\n' % (self.tabular_output(arg.parsed.terminator))) |
189 | 793 if self.rc == 0: |
333 | 794 self.pfeedback('\nNo rows Selected.\n') |
189 | 795 elif self.rc == 1: |
333 | 796 self.pfeedback('\n1 row selected.\n') |
189 | 797 if self.autobind: |
314 | 798 self.do_bind('') |
315 | 799 elif (self.rc < self.maxfetch and self.rc > 0): |
333 | 800 self.pfeedback('\n%d rows selected.\n' % self.rc) |
189 | 801 else: |
333 | 802 self.pfeedback('\nSelected Max Num rows (%d)' % self.rc) |
193 | 803 |
804 def do_cat(self, arg): | |
361 | 805 '''Shortcut for SELECT * FROM |
200 | 806 return self.do_select(self.parsed('SELECT * FROM %s;' % arg, |
807 terminator = arg.parsed.terminator or ';', | |
361 | 808 suffix = arg.parsed.suffix))''' |
809 return self.onecmd('SELECT * FROM %s%s%s' % (arg, arg.parsed.terminator or ';', | |
810 arg.parsed.suffix or '')) | |
220 | 811 |
396 | 812 @options([make_option('-d', '--dump', action='store_true', help='dump results to files'), |
813 make_option('-f', '--full', action='store_true', help='get dependent objects as well'), | |
814 make_option('-l', '--lines', action='store_true', help='print line numbers'), | |
815 make_option('-n', '--num', type='int', help='only code near line #num'), | |
816 make_option('-w', '--width', type='int', default=5, | |
817 help='# of lines before and after --lineNo'), | |
818 make_option('-a', '--all', action='store_true', help="all schemas' objects"), | |
819 #make_option('-x', '--exact', action='store_true', help="match object name exactly") | |
397 | 820 ]) |
821 def do_pull(self, arg, opts): | |
220 | 822 """Displays source code.""" |
397 | 823 self._pull(arg, opts) |
824 | |
825 def _pull(self, arg, opts, vc=None): | |
396 | 826 opts.exact = True |
827 statekeeper = Statekeeper(opts.dump and self, ('stdout',)) | |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
828 (username, gerald_schema) = self.metadata() |
220 | 829 try: |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
830 for description in self._matching_database_objects(arg, opts): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
831 self.poutput(description.path) |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
832 txt = description.dbobj.get_ddl() |
396 | 833 if opts.get('lines'): |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
834 txt = self._with_line_numbers(txt) |
396 | 835 if opts.dump: |
442 | 836 owner = description.owner or self.current_instance.username |
837 path = os.path.join(owner.lower(), description.type.lower()) \ | |
396 | 838 .replace(' ', '_') |
839 try: | |
840 os.makedirs(path) | |
841 except OSError: | |
842 pass | |
442 | 843 filename = os.path.join(path, '%s.sql' % description.unqualified_name.lower()) |
396 | 844 self.stdout = open(filename, 'w') |
845 if opts.get('num') is not None: | |
397 | 846 txt = txt.splitlines() |
396 | 847 txt = centeredSlice(txt, center=opts.num+1, width=opts.width) |
848 txt = '\n'.join(txt) | |
849 else: | |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
850 txt = 'REMARK BEGIN %s\n%s\nREMARK END\n' % (description.path, txt) |
396 | 851 |
852 self.poutput(txt) | |
853 if opts.full: | |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
854 for dependent_type in ('constraints', 'triggers', 'indexes'): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
855 if hasattr(description.dbobj, dependent_type): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
856 for (depname, depobj) in getattr(description.dbobj, dependent_type).items(): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
857 self.poutput('REMARK BEGIN\n%s\nREMARK END\n\n' % depobj.get_ddl()) |
396 | 858 if opts.dump: |
859 self.stdout.close() | |
860 if vc: | |
861 subprocess.call(vc + [filename]) | |
220 | 862 except: |
396 | 863 statekeeper.restore() |
220 | 864 raise |
396 | 865 statekeeper.restore() |
393
9bbca36ec371
not functioning - midway through expanding pull
catherine@cordelia
parents:
392
diff
changeset
|
866 |
396 | 867 def _with_line_numbers(self, txt): |
868 txt = txt.splitlines() | |
869 template = "%%-%dd:%%s" % len(str(len(txt))) | |
870 txt = '\n'.join(template % (n+1, line) for (n, line) in | |
871 enumerate(txt)) | |
872 return txt | |
873 | |
335
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
874 def _show_shortcut(self, shortcut, argpieces): |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
875 try: |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
876 newarg = argpieces[1] |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
877 if newarg == 'on': |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
878 try: |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
879 newarg = argpieces[2] |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
880 except IndexError: |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
881 pass |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
882 except IndexError: |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
883 newarg = '' |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
884 return self.onecmd(shortcut + ' ' + newarg) |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
885 |
221 | 886 def do_show(self, arg): |
887 ''' | |
888 show - display value of all sqlpython parameters | |
889 show (parameter name) - display value of a sqlpython parameter | |
890 show parameter (parameter name) - display value of an ORACLE parameter | |
265
041c656dc8e5
show err working nicely now
catherine@Elli.myhome.westell.com
parents:
264
diff
changeset
|
891 show err (object type/name) - errors from latest PL/SQL object compilation. |
041c656dc8e5
show err working nicely now
catherine@Elli.myhome.westell.com
parents:
264
diff
changeset
|
892 show all err (type/name) - all compilation errors from the user's PL/SQL objects. |
356
c86177642f75
replacing stdout with poutput; no bracketing partial pulls with remarks
catherine@cordelia
parents:
355
diff
changeset
|
893 show (index/schema/tablespace/trigger/view/constraint/comment) on (table) |
221 | 894 ''' |
418 | 895 if arg.startswith('param') and self.rdbms == 'oracle': |
221 | 896 try: |
897 paramname = arg.split()[1].lower() | |
898 except IndexError: | |
899 paramname = '' | |
900 self.onecmd("""SELECT name, | |
901 CASE type WHEN 1 THEN 'BOOLEAN' | |
902 WHEN 2 THEN 'STRING' | |
903 WHEN 3 THEN 'INTEGER' | |
904 WHEN 4 THEN 'PARAMETER FILE' | |
905 WHEN 5 THEN 'RESERVED' | |
906 WHEN 6 THEN 'BIG INTEGER' END type, | |
907 value FROM v$parameter WHERE name LIKE '%%%s%%';""" % paramname) | |
908 else: | |
264
a8deaa38f11e
show errors works. limiting ls
catherine@Elli.myhome.westell.com
parents:
261
diff
changeset
|
909 argpieces = arg.lower().split() |
370 | 910 argpieces = [a for a in argpieces if not a.startswith('-')] |
264
a8deaa38f11e
show errors works. limiting ls
catherine@Elli.myhome.westell.com
parents:
261
diff
changeset
|
911 try: |
370 | 912 for (kwd, shortcut) in ( |
913 ('ind', '\\di'), ('schema', '\\dn'), | |
404 | 914 ('tablesp', '\\db'), ('trig', '\\dg'), |
370 | 915 ('view', '\\dv'), ('cons', '\\dc'), |
916 ('comm', '\\dd'), ('ref', 'ref')): | |
917 if argpieces[0].lower().startswith(kwd): | |
918 return self._show_shortcut(shortcut, argpieces) | |
264
a8deaa38f11e
show errors works. limiting ls
catherine@Elli.myhome.westell.com
parents:
261
diff
changeset
|
919 if argpieces[0][:3] == 'err': |
265
041c656dc8e5
show err working nicely now
catherine@Elli.myhome.westell.com
parents:
264
diff
changeset
|
920 return self._show_errors(all_users=False, limit=1, targets=argpieces[1:]) |
450 | 921 elif argpieces[0][:3] == 'tab': |
922 return self.do_ls('table/*') | |
264
a8deaa38f11e
show errors works. limiting ls
catherine@Elli.myhome.westell.com
parents:
261
diff
changeset
|
923 elif (argpieces[0], argpieces[1][:3]) == ('all','err'): |
265
041c656dc8e5
show err working nicely now
catherine@Elli.myhome.westell.com
parents:
264
diff
changeset
|
924 return self._show_errors(all_users=False, limit=None, targets=argpieces[2:]) |
264
a8deaa38f11e
show errors works. limiting ls
catherine@Elli.myhome.westell.com
parents:
261
diff
changeset
|
925 except IndexError: |
a8deaa38f11e
show errors works. limiting ls
catherine@Elli.myhome.westell.com
parents:
261
diff
changeset
|
926 pass |
221 | 927 return Cmd.do_show(self, arg) |
928 | |
224 | 929 def _vc(self, arg, opts, program): |
248 | 930 if not os.path.exists('.%s' % program): |
931 create = raw_input('%s repository not yet in current directory (%s). Create (y/N)? ' % | |
932 (program, os.getcwd())) | |
933 if not create.strip().lower().startswith('y'): | |
934 return | |
416
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
935 try: |
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
936 subprocess.call([program, 'init']) |
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
937 except OSError: |
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
938 self.perror('Call to %s failed; is it installed and in PATH?' % program) |
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
939 return |
220 | 940 opts.dump = True |
397 | 941 self._pull(arg, opts, vc=[program, 'add']) |
220 | 942 subprocess.call([program, 'commit', '-m', '"%s"' % opts.message or 'committed from sqlpython']) |
943 | |
944 @options([ | |
945 make_option('-f', '--full', action='store_true', help='get dependent objects as well'), | |
946 make_option('-a', '--all', action='store_true', help="all schemas' objects"), | |
947 make_option('-x', '--exact', action='store_true', help="match object name exactly"), | |
948 make_option('-m', '--message', action='store', type='string', dest='message', help="message to save to hg log during commit")]) | |
949 def do_hg(self, arg, opts): | |
950 '''hg (opts) (objects): | |
226 | 951 Stores DDL on disk and puts files under Mercurial version control. |
952 Args specify which objects to store, same format as `ls`.''' | |
224 | 953 self._vc(arg, opts, 'hg') |
189 | 954 |
220 | 955 @options([ |
956 make_option('-f', '--full', action='store_true', help='get dependent objects as well'), | |
957 make_option('-a', '--all', action='store_true', help="all schemas' objects"), | |
958 make_option('-x', '--exact', action='store_true', help="match object name exactly"), | |
959 make_option('-m', '--message', action='store', type='string', dest='message', help="message to save to hg log during commit")]) | |
960 def do_bzr(self, arg, opts): | |
961 '''bzr (opts) (objects): | |
226 | 962 Stores DDL on disk and puts files under Bazaar version control. |
963 Args specify which objects to store, same format as `ls`.''' | |
224 | 964 self._vc(arg, opts, 'bzr') |
220 | 965 |
966 @options([ | |
967 make_option('-f', '--full', action='store_true', help='get dependent objects as well'), | |
968 make_option('-a', '--all', action='store_true', help="all schemas' objects"), | |
969 make_option('-x', '--exact', action='store_true', help="match object name exactly"), | |
970 make_option('-m', '--message', action='store', type='string', dest='message', help="message to save to hg log during commit")]) | |
224 | 971 def do_git(self, arg, opts): |
972 '''git (opts) (objects): | |
226 | 973 Stores DDL on disk and puts files under git version control. |
974 Args specify which objects to store, same format as `ls`.''' | |
224 | 975 self._vc(arg, opts, 'git') |
220 | 976 |
433 | 977 all_users_option = make_option('-a', '--all', action='store_const', dest="scope", |
222 | 978 default={'col':'', 'view':'user', 'schemas':'user', 'firstcol': ''}, |
979 const={'col':', owner', 'view':'all', 'schemas':'all', 'firstcol': 'owner, '}, | |
433 | 980 ) |
981 all_users_option = make_option('-a', '--all', action='store_true', help='Describe all objects (not just my own)') | |
194 | 982 @options([all_users_option, |
189 | 983 make_option('-c', '--col', action='store_true', help='find column'), |
398 | 984 ]) |
189 | 985 def do_find(self, arg, opts): |
986 """Finds argument in source code or (with -c) in column definitions.""" | |
398 | 987 |
435 | 988 seek = re.compile(self._regex_form_of_search_pattern(arg, exact=opts.col), |
989 re.IGNORECASE) | |
398 | 990 qualified = opts.get('all') |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
991 for descrip in self._matching_database_objects('*', opts): |
398 | 992 if opts.col: |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
993 if hasattr(descrip.dbobj, 'columns'): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
994 for col in descrip.dbobj.columns: |
398 | 995 if seek.search(col): |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
996 self.poutput('%s.%s' % (m.fullname, col)) |
398 | 997 else: |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
998 if hasattr(descrip.dbobj, 'source'): |
398 | 999 name_printed = False |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1000 for (line_num, line) in descrip.dbobj.source: |
398 | 1001 if seek.search(line): |
1002 if not name_printed: | |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1003 self.poutput(descrip.fullname) |
398 | 1004 name_printed = True |
1005 self.poutput('%d: %s' % (line_num, line)) | |
286 | 1006 |
400 | 1007 def _col_type_descriptor(self, col): |
415 | 1008 #if col['type'] in ('integer',): |
1009 # return col['type'] | |
1010 if ('length' in col) and (col['length'] is not None): | |
1011 if ('precision' in col) and (col['precision'] is not None): | |
1012 return '%s(%d,%d)' % (col['type'], col['length'], col['precision']) | |
1013 else: | |
1014 return '%s(%d)' % (col['type'], col['length']) | |
400 | 1015 else: |
1016 return col['type'] | |
1017 | |
1018 def _key_columns(self, tbl, type): | |
1019 columns = [c['columns'] for c in tbl.constraints.values() if c['type'] == type] | |
1020 if columns: | |
1021 return reduce(list.extend, columns) | |
415 | 1022 #TODO: in postgres, _key_columns returns 'fishies_pkey' instead of 'n' |
401 | 1023 else: |
1024 return [] | |
400 | 1025 |
286 | 1026 @options([all_users_option, |
400 | 1027 make_option('-l', '--long', action='store_true', help='include column #, comments'), |
1028 make_option('-A', '--alpha', action='store_true', help='List columns alphabetically')]) | |
189 | 1029 def do_describe(self, arg, opts): |
399 | 1030 opts.exact = True |
401 | 1031 rowlimit = self.rowlimit(arg) |
400 | 1032 if opts.alpha: |
1033 sortkey = operator.itemgetter('name') | |
1034 else: | |
1035 sortkey = operator.itemgetter('sequence') | |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1036 for descrip in self._matching_database_objects(arg, opts): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1037 self.tblname = descrip.fullname |
399 | 1038 self.pfeedback(self.tblname) |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1039 if opts.long and hasattr(descrip.dbobj, 'comments'): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1040 if descrip.dbobj.comments: |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1041 self.poutput(descrip.dbobj.comments) |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1042 if hasattr(descrip.dbobj, 'columns'): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1043 cols = sorted(descrip.dbobj.columns.values(), key=sortkey)[:rowlimit] |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1044 if opts.long and hasattr(descrip.dbobj, 'constraints'): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1045 primary_key_columns = self._key_columns(descrip.dbobj, 'Primary') |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1046 unique_key_columns = self._key_columns(descrip.dbobj, 'Unique') |
402 | 1047 self.colnames = 'N Name Nullable Type Key Default Comments'.split() |
400 | 1048 self.rows = [(col['sequence'], col['name'], (col['nullable'] and 'NULL') or 'NOT NULL', |
1049 self._col_type_descriptor(col), | |
1050 ((col['name'] in primary_key_columns) and 'P') or | |
1051 ((col['name'] in unique_key_columns) and 'U') or '', | |
401 | 1052 col.get('default') or '', col.get('comment') or '') |
399 | 1053 for col in cols] |
1054 else: | |
400 | 1055 self.colnames = 'Name Nullable Type'.split() |
1056 self.rows = [(col['name'], (col['nullable'] and 'NULL') or 'NOT NULL', self._col_type_descriptor(col)) | |
399 | 1057 for col in cols] |
1058 self.coltypes = [str] * len(self.colnames) | |
433 | 1059 self.poutput('%s\n\n' % self.tabular_output(arg.parsed.terminator, self.tblname)) |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1060 elif hasattr(descrip.dbobj, 'increment_by'): |
400 | 1061 self.colnames = 'name min_value max_value increment_by'.split() |
1062 self.coltypes = [str, int, int, int] | |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1063 self.rows = [(getattr(descrip.dbobj, p) for p in self.colnames)] |
433 | 1064 self.poutput('%s\n\n' % self.tabular_output(arg.parsed.terminator, self.tblname)) |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1065 elif hasattr(descrip.dbobj, 'source'): |
400 | 1066 end_heading = re.compile(r'\bDECLARE|BEGIN\b', re.IGNORECASE) |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1067 for (index, (ln, line)) in enumerate(descrip.dbobj.source): |
400 | 1068 if end_heading.search(line): |
1069 break | |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1070 self.poutput(''.join(l for (ln, l) in descrip.dbobj.source[:index])) |
400 | 1071 |
416
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
1072 @options([all_users_option]) |
e7769bc81960
several changes to settables - incomplete
catherine@bothari
parents:
415
diff
changeset
|
1073 def do_deps(self, arg, opts): |
286 | 1074 '''Lists all objects that are dependent upon the object.''' |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1075 #TODO: doesn't account for views; don't know about primary keys |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1076 for descrip in self._matching_database_objects(arg, opts): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1077 for deptype in ('indexes', 'constraints', 'triggers'): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1078 if hasattr(descrip.dbobj, deptype): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1079 for (depname, depobj) in getattr(descrip.dbobj, deptype).items(): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1080 self.poutput('%s %s' % (deptype, depname)) |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1081 |
401 | 1082 @options([all_users_option]) |
1083 def do_comments(self, arg, opts): | |
189 | 1084 'Prints comments on a table and its columns.' |
401 | 1085 qualified = opts.get('all') |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1086 for descrip in self._matching_database_objects(arg, opts): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1087 if hasattr(descrip.dbobj, 'comments'): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1088 self.poutput(descrip.fullname) |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1089 self.poutput(descrip.dbobj.comments) |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1090 if hasattr(descrip.dbobj, 'columns'): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1091 columns = descrip.dbobj.columns.values() |
401 | 1092 columns.sort(key=operator.itemgetter('sequence')) |
1093 for col in columns: | |
1094 comment = col.get('comment') | |
1095 if comment: | |
1096 self.poutput('%s: %s' % (col['name'], comment)) | |
1097 else: | |
1098 self.poutput(col['name']) | |
189 | 1099 |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1100 def _resolve(self, identifier): |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1101 parts = identifier.split('.') |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1102 if len(parts) == 2: |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1103 owner, object_name = parts |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1104 object_type = self.select_scalar_list('SELECT object_type FROM all_objects WHERE owner = :owner AND object_name = :object_name', |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1105 {'owner': owner, 'object_name': object_name.upper()} |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1106 )[0] |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1107 elif len(parts) == 1: |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1108 object_name = parts[0] |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1109 self._execute(queries['resolve'], {'objName':object_name.upper()}) |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1110 object_type, object_name, owner = self.curs.fetchone() |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1111 return object_type, owner, object_name |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1112 |
189 | 1113 def resolve(self, identifier): |
1114 """Checks (my objects).name, (my synonyms).name, (public synonyms).name | |
1115 to resolve a database object's name. """ | |
1116 try: | |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1117 return self._resolve(identifier) |
189 | 1118 except (TypeError, IndexError): |
333 | 1119 self.pfeedback('Could not resolve object %s.' % identifier) |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1120 return '', '', '' |
189 | 1121 |
1122 def spoolstop(self): | |
1123 if self.spoolFile: | |
1124 self.stdout = self.stdoutBeforeSpool | |
333 | 1125 self.pfeedback('Finished spooling to ', self.spoolFile.name) |
189 | 1126 self.spoolFile.close() |
1127 self.spoolFile = None | |
1128 | |
1129 def do_spool(self, arg): | |
1130 """spool [filename] - begins redirecting output to FILENAME.""" | |
1131 self.spoolstop() | |
1132 arg = arg.strip() | |
1133 if not arg: | |
1134 arg = 'output.lst' | |
1135 if arg.lower() != 'off': | |
1136 if '.' not in arg: | |
1137 arg = '%s.lst' % arg | |
333 | 1138 self.pfeedback('Sending output to %s (until SPOOL OFF received)' % (arg)) |
189 | 1139 self.spoolFile = open(arg, 'w') |
1140 self.stdout = self.spoolFile | |
1141 | |
333 | 1142 def sqlfeedback(self, arg): |
1143 if self.sql_echo: | |
1144 self.pfeedback(arg) | |
1145 | |
189 | 1146 def do_write(self, args): |
281 | 1147 'Obsolete command. Use (query) > outfilename instead.' |
333 | 1148 self.poutput(self.do_write.__doc__) |
189 | 1149 return |
1150 | |
1151 def do_compare(self, args): | |
1152 """COMPARE query1 TO query2 - uses external tool to display differences. | |
1153 | |
1154 Sorting is recommended to avoid false hits. | |
1155 Will attempt to use a graphical diff/merge tool like kdiff3, meld, or Araxis Merge, | |
1156 if they are installed.""" | |
193 | 1157 #TODO: Update this to use pyparsing |
189 | 1158 fnames = [] |
1159 args2 = args.split(' to ') | |
1160 if len(args2) < 2: | |
333 | 1161 self.pfeedback(self.do_compare.__doc__) |
189 | 1162 return |
1163 for n in range(len(args2)): | |
1164 query = args2[n] | |
1165 fnames.append('compare%s.txt' % n) | |
1166 #TODO: update this terminator-stripping | |
1167 if query.rstrip()[-1] != self.terminator: | |
1168 query = '%s%s' % (query, self.terminator) | |
1169 self.onecmd_plus_hooks('%s > %s' % (query, fnames[n])) | |
1170 diffMergeSearcher.invoke(fnames[0], fnames[1]) | |
1171 | |
1172 bufferPosPattern = re.compile('\d+') | |
1173 rangeIndicators = ('-',':') | |
1174 | |
1175 def do_psql(self, arg): | |
1176 '''Shortcut commands emulating psql's backslash commands. | |
1177 | |
1178 \c connect | |
1179 \d desc | |
1180 \e edit | |
1181 \g run | |
1182 \h help | |
1183 \i load | |
1184 \o spool | |
1185 \p list | |
1186 \q quit | |
1187 \w save | |
1188 \db _dir_tablespaces | |
403
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1189 \dc _dir_constraints |
189 | 1190 \dd comments |
404 | 1191 \dg _dir_triggers |
189 | 1192 \dn _dir_schemas |
1193 \dt _dir_tables | |
1194 \dv _dir_views | |
1195 \di _dir_indexes | |
1196 \? help psql''' | |
1197 commands = {} | |
1198 for c in self.do_psql.__doc__.splitlines()[2:]: | |
1199 (abbrev, command) = c.split(None, 1) | |
411 | 1200 commands[abbrev] = command |
1201 parts = arg.parsed.raw.split(None,1) | |
1202 abbrev = parts[0] | |
189 | 1203 try: |
411 | 1204 remainder = parts[1] |
189 | 1205 except IndexError: |
411 | 1206 remainder = '' |
1207 if abbrev in commands: | |
1208 newcommand = '%s %s' % (commands[abbrev], remainder) | |
1209 return self.onecmd(newcommand) | |
1210 else: | |
1211 self.perror('No abbreviated command for %s' % abbrev) | |
1212 self.perror(self.do_psql.__doc__) | |
1213 | |
402 | 1214 def _do_dir(self, type, arg, opts): |
1215 self.do_ls("%s/%s%s%s" % (type, str(arg), arg.parsed.terminator, arg.parsed.suffix), opts) | |
1216 | |
1217 standard_options = [ | |
433 | 1218 all_users_option, |
402 | 1219 make_option('-l', '--long', action='store_true', help='long descriptions'), |
1220 make_option('-r', '--reverse', action='store_true', help="Reverse order while sorting")] | |
1221 | |
1222 @options(standard_options) | |
189 | 1223 def do__dir_tables(self, arg, opts): |
402 | 1224 'Shortcut for ``ls table/``' |
1225 self._do_dir('table', arg, opts) | |
1226 | |
1227 @options(standard_options) | |
189 | 1228 def do__dir_views(self, arg, opts): |
402 | 1229 'Shortcut for ``ls table/``' |
1230 self._do_dir('view', arg, opts) | |
1231 | |
1232 @options(standard_options) | |
1233 def do__dir_(self, arg, opts): | |
1234 'Shortcut for ``ls table/``' | |
1235 self._do_dir('', arg, opts) | |
1236 | |
1237 @options(standard_options) | |
1238 def do__dir_(self, arg, opts): | |
1239 'Shortcut for ``ls table/``' | |
1240 self._do_dir('', arg, opts) | |
194 | 1241 |
403
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1242 def _str_index(self, idx, long=False): |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1243 return '%s (%s) %s %s' % (idx['name'], ','.join(idx['columns']), |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1244 idx['type'], (idx['unique'] and 'unique') or '') |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1245 |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1246 def _str_constraint(self, cons, long=False): |
421 | 1247 #TODO: this is way too unclear right now |
403
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1248 if 'condition' in cons: |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1249 details = '(%s)' % cons['condition'] |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1250 elif 'reftable' in cons: |
425 | 1251 details = 'columns (%s) in table "%s"' % (','.join(cons['columns']), cons['reftable']) |
403
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1252 elif 'columns' in cons: |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1253 details = '(%s)' % ','.join(cons['columns']) |
404 | 1254 else: |
1255 details = '' | |
425 | 1256 return '%7s key "%s": %s %s' % (cons['type'], cons['name'], details, |
404 | 1257 ((not cons['enabled']) and 'DISABLED') or '') |
1258 | |
403
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1259 |
404 | 1260 def _str_trigger(self, trig, long=False): |
1261 result = 'Trigger %s %s %s for each %s' % (trig.name, trig.scope, ','.join(trig.events), trig.level) | |
1262 if long: | |
1263 result = '%s\n\n%s\n\n' % (result, trig.sql) | |
1264 return result | |
1265 | |
1266 def do__dir_(self, arg, opts, plural_name, str_function): | |
403
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1267 long = opts.get('long') |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1268 reverse = opts.get('reverse') or False |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1269 for descrip in self._matching_database_objects(arg, opts): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1270 if hasattr(descrip.dbobj, plural_name): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1271 self.pfeedback('%s on %s' % (plural_name.title(), descrip.fullname)) |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1272 result = [str_function(depobj, long) for depobj in getattr(descrip.dbobj, plural_name).values()] |
403
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1273 result.sort(reverse=opts.get('reverse') or False) |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1274 self.poutput('\n'.join(result)) |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1275 |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1276 @options(standard_options) |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1277 def do__dir_indexes(self, arg, opts): |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1278 ''' |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1279 Called with an exact table name, lists the indexes of that table. |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1280 Otherwise, acts as shortcut for `ls index/*(arg)*` |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1281 ''' |
404 | 1282 self.do__dir_(arg, opts, 'indexes', self._str_index) |
189 | 1283 |
403
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1284 @options(standard_options) |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1285 def do__dir_constraints(self, arg, opts): |
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1286 ''' |
415 | 1287 Lists constaints of a table. |
403
dff2ac907331
genericizing _dir_indexes, _dir_constraints'
catherine@DellZilla
parents:
402
diff
changeset
|
1288 ''' |
404 | 1289 self.do__dir_(arg, opts, 'constraints', self._str_constraint) |
1290 | |
1291 @options(standard_options) | |
1292 def do__dir_triggers(self, arg, opts): | |
1293 ''' | |
1294 Called with an exact table name, lists the indexes of that table. | |
1295 Otherwise, acts as shortcut for `ls index/*(arg)*` | |
1296 ''' | |
1297 self.do__dir_(arg, opts, 'triggers', self._str_trigger) | |
1298 | |
189 | 1299 def do__dir_tablespaces(self, arg): |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1300 ''' |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1301 Lists all tablespaces. |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1302 ''' |
194 | 1303 sql = """SELECT tablespace_name, file_name from dba_data_files;""" |
333 | 1304 self.sqlfeedback(sql) |
200 | 1305 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
189 | 1306 |
1307 def do__dir_schemas(self, arg): | |
251
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1308 ''' |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1309 Lists all object owners, together with the number of objects they own. |
aa33f495a289
reworked \di - not truly better?
catherine@Elli.myhome.westell.com
parents:
250
diff
changeset
|
1310 ''' |
194 | 1311 sql = """SELECT owner, count(*) AS objects FROM all_objects GROUP BY owner ORDER BY owner;""" |
333 | 1312 self.sqlfeedback(sql) |
200 | 1313 self.do_select(self.parsed(sql, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)) |
189 | 1314 |
1315 def do_head(self, arg): | |
226 | 1316 '''Shortcut for SELECT * FROM <arg>;10 |
1317 The terminator (\\t, \\g, \\x, etc.) and number of rows can | |
1318 be changed as for any other SELECT statement.''' | |
200 | 1319 sql = self.parsed('SELECT * FROM %s;' % arg, terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix) |
195 | 1320 sql.parsed['suffix'] = sql.parsed.suffix or '10' |
196 | 1321 self.do_select(self.parsed(sql)) |
189 | 1322 |
1323 def do_print(self, arg): | |
1324 'print VARNAME: Show current value of bind variable VARNAME.' | |
1325 if arg: | |
1326 if arg[0] == ':': | |
1327 arg = arg[1:] | |
1328 try: | |
356
c86177642f75
replacing stdout with poutput; no bracketing partial pulls with remarks
catherine@cordelia
parents:
355
diff
changeset
|
1329 self.poutput(str(self.binds[arg])+'\n') |
189 | 1330 except KeyError: |
356
c86177642f75
replacing stdout with poutput; no bracketing partial pulls with remarks
catherine@cordelia
parents:
355
diff
changeset
|
1331 self.poutput('No bind variable %s\n' % arg) |
189 | 1332 else: |
250 | 1333 for (var, val) in sorted(self.binds.items()): |
333 | 1334 self.poutput(':%s = %s' % (var, val)) |
189 | 1335 |
285 | 1336 def split_on_parser(self, parser, arg): |
1337 try: | |
1338 assigner, startat, endat = parser.scanner.scanString(arg).next() | |
1339 return (arg[:startat].strip(), arg[endat:].strip()) | |
1340 except StopIteration: | |
1341 return ''.join(arg.split()[:1]), '' | |
1342 | |
355 | 1343 assignmentSplitter = re.compile(':?=') |
285 | 1344 def interpret_variable_assignment(self, arg): |
1345 ''' | |
374 | 1346 Accepts strings like `foo = 'bar'` or `baz := 22`, |
1347 returns (assigned? (T/F), variable, new-value) | |
1348 | |
1349 >>> s = sqlpyPlus() | |
1350 >>> s.interpret_variable_assignment(s.parsed("foo = 'bar'")) | |
1351 (True, 'foo', 'bar') | |
1352 >>> s.interpret_variable_assignment(s.parsed("baz := 22")) | |
1353 (True, 'baz', 22) | |
1354 >>> s.interpret_variable_assignment(s.parsed("foo")) | |
425 | 1355 (False, 'foo', None) |
285 | 1356 ''' |
374 | 1357 arg = self.parsed(arg) |
445
b34ea206c7d1
debug bind var dependence on arg.parsed.expanded
catherine@Drou
parents:
442
diff
changeset
|
1358 import pdb; pdb.set_trace() |
329
3efffbf7481f
fixed bug in assigning 0, null to bind vars
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1359 try: |
446 | 1360 var, val = self.assignmentSplitter.split(arg, maxsplit=1) |
355 | 1361 except ValueError: |
446 | 1362 return False, str(arg).split()[-1] or None, None |
355 | 1363 var = var.split()[-1] |
374 | 1364 val = val.strip() |
285 | 1365 if (len(val) > 1) and ((val[0] == val[-1] == "'") or (val[0] == val[-1] == '"')): |
329
3efffbf7481f
fixed bug in assigning 0, null to bind vars
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1366 return True, var, val[1:-1] |
285 | 1367 try: |
329
3efffbf7481f
fixed bug in assigning 0, null to bind vars
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1368 return True, var, int(val) |
285 | 1369 except ValueError: |
1370 try: | |
329
3efffbf7481f
fixed bug in assigning 0, null to bind vars
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1371 return True, var, float(val) |
285 | 1372 except ValueError: |
1373 # use the conversions implicit in cx_Oracle's select to | |
1374 # cast the value into an appropriate type (dates, for instance) | |
1375 try: | |
355 | 1376 if self.rdbms == 'oracle': |
1377 sql = 'SELECT %s FROM dual' | |
1378 else: | |
1379 sql = 'SELECT %s' | |
1380 self.curs.execute(sql % val) | |
329
3efffbf7481f
fixed bug in assigning 0, null to bind vars
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1381 return True, var, self.curs.fetchone()[0] |
415 | 1382 except: # TODO: should not be bare - should catch cx_Oracle.DatabaseError, etc. |
329
3efffbf7481f
fixed bug in assigning 0, null to bind vars
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1383 return True, var, val # we give up and assume it's a string |
285 | 1384 |
189 | 1385 def do_setbind(self, arg): |
285 | 1386 '''Sets or shows values of bind (`:`) variables.''' |
189 | 1387 if not arg: |
1388 return self.do_print(arg) | |
329
3efffbf7481f
fixed bug in assigning 0, null to bind vars
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1389 assigned, var, val = self.interpret_variable_assignment(arg) |
3efffbf7481f
fixed bug in assigning 0, null to bind vars
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1390 if not assigned: |
3efffbf7481f
fixed bug in assigning 0, null to bind vars
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1391 return self.do_print(var) |
3efffbf7481f
fixed bug in assigning 0, null to bind vars
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1392 else: |
285 | 1393 self.binds[var] = val |
189 | 1394 |
285 | 1395 def do_define(self, arg): |
1396 '''Sets or shows values of substitution (`&`) variables.''' | |
1397 if not arg: | |
1398 for (substvar, val) in sorted(self.substvars.items()): | |
333 | 1399 self.poutput('DEFINE %s = "%s" (%s)' % (substvar, val, type(val))) |
329
3efffbf7481f
fixed bug in assigning 0, null to bind vars
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1400 assigned, var, val = self.interpret_variable_assignment(arg) |
3efffbf7481f
fixed bug in assigning 0, null to bind vars
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1401 if assigned: |
285 | 1402 self.substvars[var] = val |
1403 else: | |
1404 if var in self.substvars: | |
333 | 1405 self.poutput('DEFINE %s = "%s" (%s)' % (var, self.substvars[var], type(self.substvars[var]))) |
285 | 1406 |
189 | 1407 def do_exec(self, arg): |
213 | 1408 if arg.startswith(':'): |
374 | 1409 self.do_setbind(arg.parsed.expanded.split(':',1)[1]) |
189 | 1410 else: |
340
001d01eeac90
bind vars for postgres
Catherine Devlin <catherine.devlin@gmail.com>
parents:
339
diff
changeset
|
1411 varsUsed = self.findBinds(arg, {}) |
189 | 1412 try: |
1413 self.curs.execute('begin\n%s;end;' % arg, varsUsed) | |
1414 except Exception, e: | |
333 | 1415 self.perror(e) |
189 | 1416 |
1417 ''' | |
1418 Fails: | |
1419 select n into :n from test;''' | |
1420 | |
1421 def anon_plsql(self, line1): | |
1422 lines = [line1] | |
1423 while True: | |
247 | 1424 line = self.pseudo_raw_input(self.continuation_prompt) |
311 | 1425 self.history[-1] = '%s\n%s' % (self.history[-1], line) |
241 | 1426 if line == 'EOF': |
1427 return | |
189 | 1428 if line.strip() == '/': |
1429 try: | |
1430 self.curs.execute('\n'.join(lines)) | |
1431 except Exception, e: | |
333 | 1432 self.perror(e) |
189 | 1433 return |
1434 lines.append(line) | |
1435 | |
1436 def do_begin(self, arg): | |
281 | 1437 ''' |
1438 PL/SQL blocks can be used normally in sqlpython, though enclosing statements in | |
1439 REMARK BEGIN... REMARK END statements can help with parsing speed.''' | |
189 | 1440 self.anon_plsql('begin ' + arg) |
1441 | |
1442 def do_declare(self, arg): | |
1443 self.anon_plsql('declare ' + arg) | |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1444 |
326
82937b8dcbfe
very basic multi-RDBMS ls in place
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1445 def ls_where_clause(self, arg, opts): |
82937b8dcbfe
very basic multi-RDBMS ls in place
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1446 where = ['WHERE (1=1) '] |
189 | 1447 if arg: |
280
8ea39093ddf2
struggling with catching terminator after /*
catherine@dellzilla
parents:
277
diff
changeset
|
1448 target = arg.upper().replace('*','%') |
313
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1449 if target in self.object_types: |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1450 target += '/%' |
326
82937b8dcbfe
very basic multi-RDBMS ls in place
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1451 where.append(""" |
335
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
1452 AND( UPPER(object_type) || '/' || UPPER(object_name) LIKE '%s' |
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
1453 OR UPPER(object_name) LIKE '%s')""" % (target, target)) |
326
82937b8dcbfe
very basic multi-RDBMS ls in place
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1454 if not opts.all: |
335
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
1455 where.append("AND owner = my_own") |
326
82937b8dcbfe
very basic multi-RDBMS ls in place
Catherine Devlin <catherine.devlin@gmail.com>
parents:
322
diff
changeset
|
1456 return '\n'.join(where) |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1457 |
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1458 def resolve_many(self, arg, opts): |
331
a6cbcf24f148
oops, needed to fix resolve_many
Catherine Devlin <catherine.devlin@gmail.com>
parents:
330
diff
changeset
|
1459 statement = """SELECT owner, object_name, object_type FROM (%s) |
a6cbcf24f148
oops, needed to fix resolve_many
Catherine Devlin <catherine.devlin@gmail.com>
parents:
330
diff
changeset
|
1460 %s""" % (metaqueries['ls'][self.rdbms], self.ls_where_clause(arg, opts)) |
249 | 1461 self._execute(statement) |
216
c5a49947eedc
going to try multiple pull
catherine@Elli.myhome.westell.com
parents:
213
diff
changeset
|
1462 return self.curs.fetchall() |
313
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1463 |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1464 object_types = ( |
335
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
1465 'BASE TABLE', |
313
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1466 'CLUSTER', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1467 'CONSUMER GROUP', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1468 'CONTEXT', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1469 'DIRECTORY', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1470 'EDITION', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1471 'EVALUATION CONTEXT', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1472 'FUNCTION', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1473 'INDEX', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1474 'INDEX PARTITION', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1475 'INDEXTYPE', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1476 'JAVA CLASS', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1477 'JAVA DATA', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1478 'JAVA RESOURCE', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1479 'JOB', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1480 'JOB CLASS', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1481 'LIBRARY', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1482 'MATERIALIZED VIEW', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1483 'OPERATOR', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1484 'PACKAGE', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1485 'PACKAGE BODY', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1486 'PROCEDURE', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1487 'PROGRAM', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1488 'RULE', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1489 'RULE SET', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1490 'SCHEDULE', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1491 'SEQUENCE', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1492 'SYNONYM', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1493 'TABLE', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1494 'TABLE PARTITION', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1495 'TRIGGER', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1496 'TYPE', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1497 'TYPE BODY', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1498 'VIEW', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1499 'WINDOW', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1500 'WINDOW GROUP', |
22fc9a350eaa
finally, ls working right
catherine@Elli.myhome.westell.com
parents:
311
diff
changeset
|
1501 'XML SCHEMA') |
377 | 1502 |
391 | 1503 def metadata(self): |
429 | 1504 username = self.current_instance.username |
415 | 1505 if self.rdbms == 'oracle': |
1506 username = username.upper() | |
1507 elif self.rdbms == 'postgres': | |
1508 username = username.lower() | |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1509 return (username, self.current_instance.gerald) |
391 | 1510 |
1511 def _to_sql_wildcards(self, original): | |
1512 return original.replace('*','%').replace('?','_') | |
1513 #hmm... but these should be escape-able? | |
1514 | |
1515 def _to_re_wildcards(self, original): | |
1516 result = re.escape(original) | |
1517 return result.replace('\\*','.*').replace('\\?','.') | |
1518 | |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1519 def _regex_form_of_search_pattern(self, s, exact=False): |
433 | 1520 if not s: |
435 | 1521 return '^[^\.]*$' |
1522 if '.' in s: | |
1523 seekpatt = r'[/\\]?%s[/\\]?' % ( | |
1524 s.replace('*', '.*').replace('?','.').replace('%', '.*')) | |
1525 else: | |
1526 seekpatt = r'[/\\]?%s[/\\]?' % ( | |
1527 s.replace('*', '[^\.]*').replace('?','[^\.]').replace('%', '[^\.]*')) | |
398 | 1528 if exact: |
1529 seekpatt = '^%s$' % seekpatt | |
435 | 1530 return seekpatt |
405 | 1531 |
433 | 1532 def do_refresh(self, arg): |
405 | 1533 '''Refreshes metadata for the specified schema; only required |
433 | 1534 if table structures, etc. have changed.''' |
1535 if self.current_instance.gerald.complete and self.current_instance.gerald.current: | |
1536 self.current_instance.discover_metadata() | |
405 | 1537 else: |
433 | 1538 self.pfeedback('Metadata discovery is already underway.') |
405 | 1539 |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1540 def _print_gerald_status_warning(self, gerald_schema): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1541 if not gerald_schema.complete: |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1542 self.pfeedback('Metadata is not available yet - still gathering') |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1543 elif not gerald_schema.current: |
436 | 1544 self.pfeedback('Metadata is stale - requested refresh still underway') |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1545 |
391 | 1546 def _matching_database_objects(self, arg, opts): |
392 | 1547 # doesn't get java$options |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1548 |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1549 (username, gerald_schema) = self.metadata() |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1550 self._print_gerald_status_warning(gerald_schema) |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1551 if not gerald_schema.complete: |
396 | 1552 raise StopIteration |
394
58e6d66794b0
refactoring _matching_database_objects to return MetaData
catherine@DellZilla
parents:
393
diff
changeset
|
1553 |
435 | 1554 seek = str(arg) and self._regex_form_of_search_pattern(arg, opts.get('exact')) |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1555 for (name, descrip) in gerald_schema.descriptions.items(): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1556 if descrip.match_pattern(seek, specific_owner = ((not opts.all) and username)): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1557 yield descrip |
402 | 1558 |
1559 @options(standard_options) | |
391 | 1560 def do_ls(self, arg, opts): |
1561 ''' | |
1562 Lists objects as through they were in an {object_type}/{object_name} UNIX | |
1563 directory structure. `*` and `%` may be used as wildcards. | |
1564 ''' | |
396 | 1565 opts.exact = True |
391 | 1566 (username, schemas) = self.metadata() |
433 | 1567 result = [descrip.path for descrip in self._matching_database_objects(arg, opts)] |
387 | 1568 if result: |
1569 result.sort(reverse=bool(opts.reverse)) | |
1570 self.poutput('\n'.join(result)) | |
189 | 1571 |
391 | 1572 @options([make_option('-i', '--ignore-case', dest='ignorecase', action='store_true', help='Case-insensitive search'), |
1573 make_option('-a', '--all', action='store_true', help="all schemas' objects")]) | |
1574 | |
189 | 1575 def do_grep(self, arg, opts): |
314 | 1576 """grep {target} {table} [{table2,...}] |
1577 search for {target} in any of {table}'s fields""" | |
391 | 1578 arg = self.parsed(arg) |
396 | 1579 opts.exact = True |
391 | 1580 args = arg.split() |
1581 if len(args) < 2: | |
1582 self.perror(self.do_grep.__doc__) | |
1583 return | |
1584 pattern, targets = args[0], args[1:] | |
1585 if opts.ignorecase: | |
1586 pattern = pattern.lower() | |
417 | 1587 comparitor = "OR LOWER(%s) LIKE '%%%%%%s%%%%'" % self._cast_as_char() |
391 | 1588 else: |
417 | 1589 comparitor = "OR %s LIKE '%%%%%%s%%%%'" % self._cast_as_char() |
391 | 1590 sql_pattern = self._to_sql_wildcards(pattern) |
1591 re_pattern = re.compile(self._to_re_wildcards(pattern), | |
1592 (opts.ignorecase and re.IGNORECASE) or 0) | |
189 | 1593 for target in targets: |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1594 for descrip in self._matching_database_objects(target, opts): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1595 self.pfeedback(descrip.fullname) |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1596 if hasattr(descrip.dbobj, 'columns'): |
391 | 1597 clauses = [] |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1598 for col in descrip.dbobj.columns: |
391 | 1599 clauses.append(comparitor % (col, sql_pattern)) |
437
6ba7087f1a34
allow qualified or unqualified object names in gerald
catherine@dellzilla
parents:
436
diff
changeset
|
1600 sql = "SELECT * FROM %s WHERE 1=0\n%s;" % (descrip.fullname, ' '.join(clauses)) |
6ba7087f1a34
allow qualified or unqualified object names in gerald
catherine@dellzilla
parents:
436
diff
changeset
|
1601 sql = self.parsed(sql, terminator=arg.parsed.terminator or ';', |
6ba7087f1a34
allow qualified or unqualified object names in gerald
catherine@dellzilla
parents:
436
diff
changeset
|
1602 suffix=arg.parsed.suffix) |
391 | 1603 self.do_select(sql) |
432
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1604 elif hasattr(descrip.dbobj, 'source'): |
26b09e1481e7
beginning to reimplement threaded metadata discovery
catherine@dellzilla
parents:
429
diff
changeset
|
1605 for (line_num, line) in descrip.dbobj.source: |
391 | 1606 if re_pattern.search(line): |
1607 self.poutput('%4d: %s' % (line_num, line)) | |
1608 | |
189 | 1609 |
417 | 1610 def _cast_as_char(self): |
1611 'self._cast_as_char() => Returns the RDBMS-equivalent "CAST(%s AS VARCHAR) expression.' | |
1612 converter = {'oracle': 'TO_CHAR(%s)'}.get(self.rdbms, 'CAST(%s AS VARCHAR)') | |
1613 return converter | |
335
00b183a103b3
bare prefix switches connection
Catherine Devlin <catherine.devlin@gmail.com>
parents:
334
diff
changeset
|
1614 |
249 | 1615 def _execute(self, sql, bindvars={}): |
333 | 1616 self.sqlfeedback(sql) |
249 | 1617 self.curs.execute(sql, bindvars) |
1618 | |
286 | 1619 #@options([make_option('-l', '--long', action='store_true', |
1620 # help='Wordy, easy-to-understand form'),]) | |
189 | 1621 def do_refs(self, arg): |
286 | 1622 '''Lists referential integrity (foreign key constraints) on an object or referring to it.''' |
211 | 1623 |
421 | 1624 # TODO: needs much polish |
1625 return self.do__dir_constraints(arg) | |
1626 | |
189 | 1627 def _test(): |
1628 import doctest | |
1629 doctest.testmod() | |
1630 | |
1631 if __name__ == "__main__": | |
1632 "Silent return implies that all unit tests succeeded. Use -v to see details." | |
1633 _test() |