Mercurial > sqlpython
annotate sqlpyPlus.py @ 3:cd23cd62de3c
history working pretty well
author | devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil |
---|---|
date | Mon, 03 Dec 2007 16:43:43 -0500 |
parents | 59903dcaf327 |
children | 23c3a58d7804 |
rev | line source |
---|---|
0 | 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 - Query result stored in special bind variable ":_" if one row, one item | |
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 | |
16 Use 'help' within sqlpython for details. | |
17 | |
18 Compatible with sqlpython v1.3 | |
19 | |
20 Set bind variables the hard (SQL*Plus) way | |
21 exec :b = 3 | |
22 or with a python-like shorthand | |
23 :b = 3 | |
24 | |
25 - catherinedevlin.blogspot.com May 31, 2006 | |
26 """ | |
27 # note in cmd.cmd about supporting emacs commands? | |
28 | |
29 queries = { | |
30 'resolve': """ | |
31 SELECT object_type, object_name, owner FROM ( | |
32 SELECT object_type, object_name, user owner, 1 priority | |
33 FROM user_objects | |
34 WHERE object_name = :objName | |
35 UNION ALL | |
36 SELECT ao.object_type, ao.object_name, ao.owner, 2 priority | |
37 FROM all_objects ao | |
38 JOIN user_synonyms us ON (us.table_owner = ao.owner AND us.table_name = ao.object_name) | |
39 WHERE us.synonym_name = :objName | |
40 AND ao.object_type != 'SYNONYM' | |
41 UNION ALL | |
42 SELECT ao.object_type, ao.object_name, ao.owner, 3 priority | |
43 FROM all_objects ao | |
44 JOIN all_synonyms asyn ON (asyn.table_owner = ao.owner AND asyn.table_name = ao.object_name) | |
45 WHERE asyn.synonym_name = :objName | |
46 AND ao.object_type != 'SYNONYM' | |
47 AND asyn.owner = 'PUBLIC' | |
48 ) ORDER BY priority ASC""", | |
49 'descTable': """ | |
50 atc.column_name, | |
51 CASE atc.nullable WHEN 'Y' THEN 'NULL' ELSE 'NOT NULL' END "Null?", | |
52 atc.data_type || | |
53 CASE atc.data_type WHEN 'DATE' THEN '' | |
54 ELSE '(' || | |
55 CASE atc.data_type WHEN 'NUMBER' THEN TO_CHAR(atc.data_precision) || | |
56 CASE atc.data_scale WHEN 0 THEN '' | |
57 ELSE ',' || TO_CHAR(atc.data_scale) END | |
58 ELSE TO_CHAR(atc.data_length) END | |
59 END || | |
60 CASE atc.data_type WHEN 'DATE' THEN '' ELSE ')' END | |
61 data_type | |
62 FROM all_tab_columns atc | |
63 WHERE atc.table_name = :object_name | |
64 AND atc.owner = :owner | |
65 ORDER BY atc.column_id;""", | |
66 'PackageObjects':""" | |
67 SELECT DISTINCT object_name | |
68 FROM all_arguments | |
69 WHERE package_name = :package_name | |
70 AND owner = :owner""", | |
71 'PackageObjArgs':""" | |
72 object_name, | |
73 argument_name, | |
74 data_type, | |
75 in_out, | |
76 default_value | |
77 FROM all_arguments | |
78 WHERE package_name = :package_name | |
79 AND object_name = :object_name | |
80 AND owner = :owner | |
81 AND argument_name IS NOT NULL | |
82 ORDER BY sequence""", | |
83 'descProcedure':""" | |
84 argument_name, | |
85 data_type, | |
86 in_out, | |
87 default_value | |
88 FROM all_arguments | |
89 WHERE object_name = :object_name | |
90 AND owner = :owner | |
91 AND package_name IS NULL | |
92 AND argument_name IS NOT NULL | |
93 ORDER BY sequence;""", | |
94 'tabComments': """ | |
95 SELECT comments | |
96 FROM all_tab_comments | |
97 WHERE owner = :owner | |
98 AND table_name = :table_name""", | |
99 'colComments': """ | |
100 atc.column_name, | |
101 acc.comments | |
102 FROM all_tab_columns atc | |
103 JOIN all_col_comments acc ON (atc.owner = acc.owner and atc.table_name = acc.table_name and atc.column_name = acc.column_name) | |
104 WHERE atc.table_name = :object_name | |
105 AND atc.owner = :owner | |
106 ORDER BY atc.column_id;""", | |
107 } | |
108 | |
109 import sys, os, re, sqlpython, cx_Oracle, pyparsing | |
110 | |
111 if float(sys.version[:3]) < 2.3: | |
112 def enumerate(lst): | |
113 return zip(range(len(lst)), lst) | |
114 | |
115 class SoftwareSearcher(object): | |
116 def __init__(self, softwareList, purpose): | |
117 self.softwareList = softwareList | |
118 self.purpose = purpose | |
119 self.software = None | |
120 def invoke(self, *args): | |
121 if not self.software: | |
122 (self.software, self.invokeString) = self.find() | |
123 argTuple = tuple([self.software] + list(args)) | |
124 os.system(self.invokeString % argTuple) | |
125 def find(self): | |
126 if self.purpose == 'text editor': | |
127 software = os.environ.get('EDITOR') | |
128 if software: | |
129 return (software, '%s %s') | |
130 for (n, (software, invokeString)) in enumerate(self.softwareList): | |
131 if os.path.exists(software): | |
132 if n > (len(self.softwareList) * 0.7): | |
133 print """ | |
134 | |
135 Using %s. Note that there are better options available for %s, | |
136 but %s couldn't find a better one in your PATH. | |
137 Feel free to open up %s | |
138 and customize it to find your favorite %s program. | |
139 | |
140 """ % (software, self.purpose, __file__, __file__, self.purpose) | |
141 return (software, invokeString) | |
142 stem = os.path.split(software)[1] | |
143 for p in os.environ['PATH'].split(os.pathsep): | |
144 if os.path.exists(os.sep.join([p, stem])): | |
145 return (stem, invokeString) | |
146 raise (OSError, """Could not find any %s programs. You will need to install one, | |
147 or customize %s to make it aware of yours. | |
148 Looked for these programs: | |
149 %s""" % (self.purpose, __file__, "\n".join([s[0] for s in self.softwareList]))) | |
150 #v2.4: %s""" % (self.purpose, __file__, "\n".join(s[0] for s in self.softwareList))) | |
151 | |
152 softwareLists = { | |
153 'diff/merge': [ | |
154 ('/usr/bin/meld',"%s %s %s"), | |
155 ('/usr/bin/kdiff3',"%s %s %s"), | |
156 (r'C:\Program Files\Araxis\Araxis Merge v6.5\Merge.exe','"%s" %s %s'), | |
157 (r'C:\Program Files\TortoiseSVN\bin\TortoiseMerge.exe', '"%s" /base:"%s" /mine:"%s"'), | |
158 ('FileMerge','%s %s %s'), | |
159 ('kompare','%s %s %s'), | |
160 ('WinMerge','%s %s %s'), | |
161 ('xxdiff','%s %s %s'), | |
162 ('fldiff','%s %s %s'), | |
163 ('gtkdiff','%s %s %s'), | |
164 ('tkdiff','%s %s %s'), | |
165 ('gvimdiff','%s %s %s'), | |
166 ('diff',"%s %s %s"), | |
167 (r'c:\windows\system32\comp.exe',"%s %s %s")], | |
168 'text editor': [ | |
169 ('gedit', '%s %s'), | |
170 ('textpad', '%s %s'), | |
171 ('notepad.exe', '%s %s'), | |
172 ('pico', '%s %s'), | |
173 ('emacs', '%s %s'), | |
174 ('vim', '%s %s'), | |
175 ('vi', '%s %s'), | |
176 ('ed', '%s %s'), | |
177 ('edlin', '%s %s') | |
178 ] | |
179 } | |
180 | |
181 diffMergeSearcher = SoftwareSearcher(softwareLists['diff/merge'],'diff/merge') | |
182 editSearcher = SoftwareSearcher(softwareLists['text editor'], 'text editor') | |
183 editor = os.environ.get('EDITOR') | |
184 if editor: | |
185 editSearcher.find = lambda: (editor, "%s %s") | |
186 | |
187 class CaselessDict(dict): | |
188 """dict with case-insensitive keys. | |
189 | |
190 Posted to ASPN Python Cookbook by Jeff Donner - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66315""" | |
191 def __init__(self, other=None): | |
192 if other: | |
193 # Doesn't do keyword args | |
194 if isinstance(other, dict): | |
195 for k,v in other.items(): | |
196 dict.__setitem__(self, k.lower(), v) | |
197 else: | |
198 for k,v in other: | |
199 dict.__setitem__(self, k.lower(), v) | |
200 def __getitem__(self, key): | |
201 return dict.__getitem__(self, key.lower()) | |
202 def __setitem__(self, key, value): | |
203 dict.__setitem__(self, key.lower(), value) | |
204 def __contains__(self, key): | |
205 return dict.__contains__(self, key.lower()) | |
206 def has_key(self, key): | |
207 return dict.has_key(self, key.lower()) | |
208 def get(self, key, def_val=None): | |
209 return dict.get(self, key.lower(), def_val) | |
210 def setdefault(self, key, def_val=None): | |
211 return dict.setdefault(self, key.lower(), def_val) | |
212 def update(self, other): | |
213 for k,v in other.items(): | |
214 dict.__setitem__(self, k.lower(), v) | |
215 def fromkeys(self, iterable, value=None): | |
216 d = CaselessDict() | |
217 for k in iterable: | |
218 dict.__setitem__(d, k.lower(), value) | |
219 return d | |
220 def pop(self, key, def_val=None): | |
221 return dict.pop(self, key.lower(), def_val) | |
222 | |
223 class NotSettableError(Exception): | |
224 None | |
225 | |
226 class Parser(object): | |
227 comment_def = "--" + pyparsing.ZeroOrMore(pyparsing.CharsNotIn("\n")) | |
228 def __init__(self, scanner, retainSeparator=True): | |
229 self.scanner = scanner | |
230 self.scanner.ignore(pyparsing.sglQuotedString) | |
231 self.scanner.ignore(pyparsing.dblQuotedString) | |
232 self.scanner.ignore(self.comment_def) | |
233 self.scanner.ignore(pyparsing.cStyleComment) | |
234 self.retainSeparator = retainSeparator | |
235 def separate(self, txt): | |
236 itms = [] | |
237 for (sqlcommand, start, end) in self.scanner.scanString(txt): | |
238 if sqlcommand: | |
239 if type(sqlcommand[0]) == pyparsing.ParseResults: | |
240 if self.retainSeparator: | |
241 itms.append("".join(sqlcommand[0])) | |
242 else: | |
243 itms.append(sqlcommand[0][0]) | |
244 else: | |
245 if sqlcommand[0]: | |
246 itms.append(sqlcommand[0]) | |
247 return itms | |
248 | |
249 pipeSeparator = Parser(pyparsing.SkipTo((pyparsing.Literal('|') ^ pyparsing.StringEnd()), include=True), retainSeparator=False) | |
250 bindScanner = Parser(pyparsing.Literal(':') + pyparsing.Word( pyparsing.alphanums + "_$#" )) | |
251 commandSeparator = Parser(pyparsing.SkipTo((pyparsing.Literal(';') ^ pyparsing.StringEnd()), include=True)) | |
252 | |
253 def findBinds(target, existingBinds, givenBindVars = {}): | |
254 result = givenBindVars | |
255 for finding, startat, endat in bindScanner.scanner.scanString(target): | |
256 varname = finding[1] | |
257 try: | |
258 result[varname] = existingBinds[varname] | |
259 except KeyError: | |
260 if not givenBindVars.has_key(varname): | |
261 print 'Bind variable %s not defined.' % (varname) | |
262 return result | |
263 | |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
264 class HistoryItem(str): |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
265 def __init__(self, instr): |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
266 str.__init__(self, instr) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
267 self.lowercase = self.lower() |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
268 self.idx = None |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
269 def pr(self): |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
270 print '-------------------------[%d]' % (self.idx) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
271 print self |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
272 |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
273 class History(list): |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
274 def append(self, new): |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
275 new = HistoryItem(new) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
276 list.append(self, new) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
277 new.idx = len(self) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
278 def extend(self, new): |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
279 for n in new: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
280 self.append(n) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
281 def get(self, getme): |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
282 try: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
283 idx = int(getme) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
284 try: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
285 return [self[idx-1]] |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
286 except IndexError: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
287 return [] |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
288 except ValueError: # search for a string |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
289 try: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
290 getme = getme.strip() |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
291 except: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
292 print "Don't know how to handle %s." % (str(getme)) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
293 return |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
294 if getme.startswith(r'/') and getme.endswith(r'/'): |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
295 finder = re.compile(getme[1:-1], re.DOTALL | re.MULTILINE | re.IGNORECASE) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
296 def isin(hi): |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
297 return finder.search(hi) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
298 else: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
299 def isin(hi): |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
300 return (getme.lower() in hi.lowercase) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
301 return [itm for itm in self[:-1] if isin(itm)] |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
302 |
0 | 303 class sqlpyPlus(sqlpython.sqlpython): |
304 def __init__(self): | |
305 sqlpython.sqlpython.__init__(self) | |
306 self.binds = CaselessDict() | |
307 self.sqlBuffer = [] | |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
308 self.history = History() |
0 | 309 self.settable = ['maxtselctrows', 'maxfetch', 'autobind', 'failover', 'timeout'] # settables must be lowercase |
310 self.stdoutBeforeSpool = sys.stdout | |
311 self.spoolFile = None | |
312 self.autobind = False | |
313 self.failover = False | |
2
59903dcaf327
working on history
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
1
diff
changeset
|
314 self.singleline = '''select insert update delete |
59903dcaf327
working on history
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
1
diff
changeset
|
315 create drop alter'''.split() |
0 | 316 |
317 def default(self, arg, do_everywhere=False): | |
318 sqlpython.sqlpython.default(self, arg, do_everywhere) | |
319 self.sqlBuffer.append(self.query) | |
320 | |
321 # overrides cmd's parseline | |
322 shortcuts = {'?': 'help', '@': 'getrun', '!': 'shell', ':': 'setbind', '\\': 'psql'} | |
323 def parseline(self, line): | |
324 """Parse the line into a command name and a string containing | |
325 the arguments. Returns a tuple containing (command, args, line). | |
326 'command' and 'args' may be None if the line couldn't be parsed. | |
327 Overrides cmd.cmd.parseline to accept variety of shortcuts..""" | |
328 line = line.strip() | |
329 if not line: | |
330 return None, None, line | |
331 shortcut = self.shortcuts.get(line[0]) | |
332 if shortcut: | |
333 cmd, arg = shortcut, line[1:].strip() | |
334 else: | |
335 i, n = 0, len(line) | |
336 while i < n and line[i] in self.identchars: i = i+1 | |
337 cmd, arg = line[:i], line[i:].strip() | |
338 if cmd.lower() in ('select', 'sleect', 'insert', 'update', 'delete', 'describe', | |
339 'desc', 'comments') \ | |
340 and not hasattr(self, 'curs'): | |
341 print 'Not connected.' | |
342 return '', '', '' | |
343 return cmd, arg, line | |
344 | |
345 def precmd(self, line): | |
346 """Hook method executed just before the command line is | |
347 interpreted, but after the input prompt is generated and issued. | |
348 Makes commands case-insensitive (but unfortunately does not alter command completion). | |
349 """ | |
1
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
350 ''' |
0 | 351 savestdout = sys.stdout |
352 pipefilename = 'sqlpython.pipeline.tmp' | |
353 pipedCommands = pipeSeparator.separate(line) | |
354 if len(pipedCommands) > 1: | |
355 f = open(pipefilename,'w') | |
356 sys.stdout = f | |
357 self.precmd(pipedCommands[0]) | |
358 self.onecmd(pipedCommands[0]) | |
359 self.postcmd(False, pipedCommands[0]) | |
360 f.close() | |
361 sys.stdout = savestdout | |
362 os.system('%s < %s' % (pipedCommands[1], pipefilename)) | |
1
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
363 ''' |
0 | 364 try: |
365 args = line.split(None,1) | |
366 args[0] = args[0].lower() | |
2
59903dcaf327
working on history
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
1
diff
changeset
|
367 statement = ' '.join(args) |
59903dcaf327
working on history
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
1
diff
changeset
|
368 if args[0] in self.singleline: |
59903dcaf327
working on history
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
1
diff
changeset
|
369 statement = sqlpython.finishStatement(statement) |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
370 self.history.append(statement) |
1
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
371 return statement |
0 | 372 except Exception: |
373 return line | |
1
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
374 |
0 | 375 def do_shortcuts(self,arg): |
376 """Lists available first-character shortcuts | |
377 (i.e. '!dir' is equivalent to 'shell dir')""" | |
378 for (scchar, scto) in self.shortcuts.items(): | |
379 print '%s: %s' % (scchar, scto) | |
380 | |
381 | |
382 def colnames(self): | |
383 return [d[0] for d in curs.description] | |
384 | |
385 def sql_format_itm(self, itm, needsquotes): | |
386 if itm is None: | |
387 return 'NULL' | |
388 if needsquotes: | |
389 return "'%s'" % str(itm) | |
390 return str(itm) | |
391 def output_as_insert_statements(self): | |
392 usequotes = [d[1] != cx_Oracle.NUMBER for d in self.curs.description] | |
393 def formatRow(row): | |
394 return ','.join(self.sql_format_itm(itm, useq) | |
395 for (itm, useq) in zip(row, usequotes)) | |
396 result = ['INSERT INTO %s (%s) VALUES (%s);' % | |
397 (self.tblname, ','.join(self.colnames), formatRow(row)) | |
398 for row in self.rows] | |
399 return '\n'.join(result) | |
400 | |
401 def output_row_as_xml(self, row): | |
402 result = [' <%s>\n %s\n </%s>' % | |
403 (colname.lower(), str('' if (itm is None) else itm), colname.lower()) | |
404 for (itm, colname) in zip(row, self.colnames)] | |
405 return '\n'.join(result) | |
406 def output_as_xml(self): | |
407 result = ['<%s>\n%s\n</%s>' % | |
408 (self.tblname, self.output_row_as_xml(row), self.tblname) | |
409 for row in self.rows] | |
410 return '\n'.join(result) | |
411 | |
412 def output_as_html_table(self): | |
413 result = ''.join('<th>%s</th>' % c for c in self.colnames) | |
414 result = [' <tr>\n %s\n </tr>' % result] | |
415 for row in self.rows: | |
416 result.append(' <tr>\n %s\n </tr>' % | |
417 (''.join('<td>%s</td>' % | |
418 str('' if (itm is None) else itm) | |
419 for itm in row))) | |
1
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
420 result = '''<table id="%s"> |
0 | 421 %s |
422 </table>''' % (self.tblname, '\n'.join(result)) | |
1
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
423 return result |
0 | 424 |
425 def output_as_list(self, align): | |
426 result = [] | |
427 colnamelen = max(len(colname) for colname in self.colnames) + 1 | |
428 for (idx, row) in enumerate(self.rows): | |
429 result.append('\n**** Row: %d' % (idx+1)) | |
430 for (itm, colname) in zip(row, self.colnames): | |
431 if align: | |
432 colname = colname.ljust(colnamelen) | |
433 result.append('%s: %s' % (colname, itm)) | |
434 return '\n'.join(result) | |
435 | |
436 tableNameFinder = re.compile(r'from\s+([\w$#_"]+)', re.IGNORECASE | re.MULTILINE | re.DOTALL) | |
437 def output(self, outformat, rowlimit): | |
438 self.tblname = self.tableNameFinder.search(self.curs.statement).group(1) | |
439 self.colnames = [d[0] for d in self.curs.description] | |
440 if outformat == '\\i': | |
441 result = self.output_as_insert_statements() | |
442 elif outformat == '\\x': | |
443 result = self.output_as_xml() | |
444 elif outformat == '\\g': | |
445 result = self.output_as_list(align=False) | |
446 elif outformat == '\\G': | |
447 result = self.output_as_list(align=True) | |
448 elif outformat in ('\\s', '\\S', '\\c', '\\C'): #csv | |
449 result = [] | |
450 if outformat in ('\\s', '\\c'): | |
451 result.append(','.join('"%s"' % colname for colname in self.colnames)) | |
452 for row in self.rows: | |
453 result.append(','.join('"%s"' % ('' if itm is None else itm) for itm in row)) | |
454 result = '\n'.join(result) | |
455 elif outformat == '\\h': | |
456 result = self.output_as_html_table() | |
457 else: | |
458 result = sqlpython.pmatrix(self.rows, self.curs.description, self.maxfetch) | |
459 return result | |
460 | |
461 def do_select(self, arg, bindVarsIn=None): | |
462 """Fetch rows from a table. | |
463 | |
464 Limit the number of rows retrieved by appending | |
465 an integer after the terminator | |
466 (example: SELECT * FROM mytable;10 ) | |
467 | |
468 Output may be formatted by choosing an alternative terminator | |
469 ("help terminators" for details) | |
470 """ | |
471 bindVarsIn = bindVarsIn or {} | |
1
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
472 self.query = 'select ' + arg |
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
473 (self.query, terminator, rowlimit) = sqlpython.findTerminator(self.query) |
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
474 rowlimit = int(rowlimit or 0) |
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
475 if terminator == '\\t': |
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
476 self.do_tselect(' '.join(self.query.split()[1:]) + ';', rowlimit) |
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
477 return |
0 | 478 else: |
479 try: | |
480 self.varsUsed = findBinds(self.query, self.binds, bindVarsIn) | |
481 self.curs.execute(self.query, self.varsUsed) | |
2
59903dcaf327
working on history
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
1
diff
changeset
|
482 self.rows = self.curs.fetchmany(min(self.maxfetch, (rowlimit or self.maxfetch))) |
0 | 483 self.desc = self.curs.description |
484 self.rc = self.curs.rowcount | |
485 if self.rc > 0: | |
2
59903dcaf327
working on history
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
1
diff
changeset
|
486 print '\n' + self.output(terminator, rowlimit) |
0 | 487 if self.rc == 0: |
488 print '\nNo rows Selected.\n' | |
489 elif self.rc == 1: | |
490 print '\n1 row selected.\n' | |
491 if self.autobind: | |
492 self.binds.update(dict(zip([d[0] for d in self.desc], self.rows[0]))) | |
493 elif self.rc < self.maxfetch: | |
494 print '\n%d rows selected.\n' % self.rc | |
495 else: | |
496 print '\nSelected Max Num rows (%d)' % self.rc | |
497 except Exception, e: | |
498 print e | |
499 import traceback | |
500 traceback.print_exc(file=sys.stdout) | |
501 self.sqlBuffer.append(self.query) | |
502 | |
503 def showParam(self, param): | |
504 param = param.strip().lower() | |
505 if param in self.settable: | |
506 val = getattr(self, param) | |
507 print '%s: %s' % (param, str(getattr(self, param))) | |
508 | |
509 def do_show(self, arg): | |
510 'Shows value of a (sqlpython, not ORACLE) parameter' | |
511 arg = arg.strip().lower() | |
512 if arg: | |
513 self.showParam(arg) | |
514 else: | |
515 for param in self.settable: | |
516 self.showParam(param) | |
517 | |
518 def cast(self, current, new): | |
519 typ = type(current) | |
520 if typ == bool: | |
521 new = new.lower() | |
522 try: | |
523 if (new=='on') or (new[0] in ('y','t')): | |
524 return True | |
525 return False | |
526 except TypeError: | |
527 None | |
528 try: | |
529 return typ(new) | |
530 except: | |
531 print "Problem setting parameter (now %s) to %s; incorrect type?" % (current, new) | |
532 return current | |
533 | |
534 def do_set(self, arg): | |
535 'Sets a (sqlpython, not ORACLE) parameter' | |
536 try: | |
537 paramName, val = arg.split(None, 1) | |
538 except Exception: | |
539 self.do_show(arg) | |
540 return | |
541 paramName = paramName.lower() | |
542 try: | |
543 current = getattr(self, paramName) | |
544 if callable(current): | |
545 raise NotSettableError | |
546 except (AttributeError, NotSettableError): | |
547 self.fail('set %s' % arg) | |
548 return | |
549 val = self.cast(current, val.strip(';')) | |
550 print paramName, ' - was: ', current | |
551 setattr(self, paramName.lower(), val) | |
552 print 'now: ', val | |
553 | |
554 def do_describe(self, arg): | |
555 "emulates SQL*Plus's DESCRIBE" | |
556 object_type, owner, object_name = self.resolve(arg.strip(self.terminator).upper()) | |
557 print "%s %s.%s" % (object_type, owner, object_name) | |
558 if object_type in ('TABLE','VIEW'): | |
559 self.do_select(queries['descTable'],{'object_name':object_name, 'owner':owner}) | |
560 elif object_type == 'PACKAGE': | |
561 self.curs.execute(queries['PackageObjects'], {'package_name':object_name, 'owner':owner}) | |
562 for (packageObj_name,) in self.curs: | |
563 print packageObj_name | |
564 self.do_select(queries['PackageObjArgs'],{'package_name':object_name, 'owner':owner, 'object_name':packageObj_name}) | |
565 else: | |
566 self.do_select(queries['descProcedure'],{'owner':owner, 'object_name':object_name}) | |
567 do_desc = do_describe | |
568 | |
569 def do_comments(self, arg): | |
570 'Prints comments on a table and its columns.' | |
571 object_type, owner, object_name = self.resolve(arg.strip(self.terminator).upper()) | |
572 if object_type: | |
573 self.curs.execute(queries['tabComments'],{'table_name':object_name, 'owner':owner}) | |
574 print "%s %s.%s: %s" % (object_type, owner, object_name, self.curs.fetchone()[0]) | |
575 self.do_select(queries['colComments'],{'owner':owner, 'object_name': object_name}) | |
576 | |
577 def resolve(self, identifier): | |
578 """Checks (my objects).name, (my synonyms).name, (public synonyms).name | |
579 to resolve a database object's name. """ | |
580 parts = identifier.split('.') | |
581 try: | |
582 if len(parts) == 2: | |
583 owner, object_name = parts | |
584 self.curs.execute('SELECT object_type FROM all_objects WHERE owner = :owner AND object_name = :object_name', | |
585 {'owner': owner, 'object_name': object_name}) | |
586 object_type = self.curs.fetchone()[0] | |
587 elif len(parts) == 1: | |
588 object_name = parts[0] | |
589 self.curs.execute(queries['resolve'], {'objName':object_name}) | |
590 object_type, object_name, owner = self.curs.fetchone() | |
591 except TypeError: | |
592 print 'Could not resolve object %s.' % identifier | |
593 object_type, owner, object_name = '', '', '' | |
594 return object_type, owner, object_name | |
595 | |
596 def do_shell(self, arg): | |
597 'execute a command as if at the OS prompt.' | |
598 os.system(arg) | |
599 | |
600 def spoolstop(self): | |
601 if self.spoolFile: | |
602 sys.stdout = self.stdoutBeforeSpool | |
603 print 'Finished spooling to ', self.spoolFile.name | |
604 self.spoolFile.close() | |
605 self.spoolFile = None | |
606 | |
607 def do_spool(self, arg): | |
608 """spool [filename] - begins redirecting output to FILENAME.""" | |
609 self.spoolstop() | |
610 arg = arg.strip() | |
611 if not arg: | |
612 arg = 'output.lst' | |
613 if arg.lower() != 'off': | |
614 if '.' not in arg: | |
615 arg = '%s.lst' % arg | |
616 print 'Sending output to %s (until SPOOL OFF received)' % (arg) | |
617 self.spoolFile = open(arg, 'w') | |
618 sys.stdout = self.spoolFile | |
619 | |
620 def write(self, arg, fname): | |
621 originalOut = sys.stdout | |
622 f = open(fname, 'w') | |
623 sys.stdout = f | |
624 self.onecmd(arg) | |
625 f.close() | |
626 sys.stdout = originalOut | |
627 | |
628 def do_write(self, args): | |
629 'write [filename.extension] query - writes result to a file' | |
630 words = args.split(None, 1) | |
631 if len(words) > 1 and '.' in words[0]: | |
632 fname, command = words | |
633 else: | |
634 fname, command = 'output.txt', args | |
635 self.write(command, fname) | |
636 print 'Results written to %s' % os.path.join(os.getcwd(), fname) | |
637 | |
638 def do_compare(self, args): | |
639 """COMPARE query1 TO query2 - uses external tool to display differences. | |
640 | |
641 Sorting is recommended to avoid false hits.""" | |
642 fnames = [] | |
643 args2 = args.split(' to ') | |
644 for n in range(len(args2)): | |
645 query = args2[n] | |
646 fnames.append('compare%s.txt' % n) | |
647 if query.rstrip()[-1] != self.terminator: | |
648 query = '%s%s' % (query, self.terminator) | |
649 self.write(query, fnames[n]) | |
650 diffMergeSearcher.invoke(fnames[0], fnames[1]) | |
651 | |
652 bufferPosPattern = re.compile('\d+') | |
653 rangeIndicators = ('-',':') | |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
654 |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
655 def last_matching_command(self, arg): |
0 | 656 if not arg: |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
657 return self.history[-2] |
0 | 658 else: |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
659 history = self.history.get(arg) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
660 if history: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
661 return history[-1] |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
662 return None |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
663 |
0 | 664 def do_run(self, arg): |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
665 """run [arg]: re-runs an earlier command |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
666 |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
667 no arg -> run most recent command |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
668 arg is integer -> run one history item, by index |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
669 arg is string -> run most recent command by string search |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
670 arg is /enclosed in forward-slashes/ -> run most recent by regex |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
671 """ |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
672 'run [N]: runs the SQL that was run N commands ago' |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
673 runme = self.last_matching_command(arg) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
674 print runme |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
675 self.onecmd(runme) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
676 do_r = do_run |
1
8fa146b9a2d7
reworking multiline
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
0
diff
changeset
|
677 def do_history(self, arg): |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
678 """history [arg]: lists past commands issued |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
679 |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
680 no arg -> list all |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
681 arg is integer -> list one history item, by index |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
682 arg is string -> string search |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
683 arg is /enclosed in forward-slashes/ -> regular expression search |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
684 """ |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
685 if arg: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
686 history = self.history.get(arg) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
687 else: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
688 history = self.history |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
689 for hi in history: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
690 hi.pr() |
0 | 691 def do_list(self, arg): |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
692 """list: lists single most recent command issued""" |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
693 self.last_matching_command(None).pr() |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
694 do_hi = do_history |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
695 do_l = do_list |
0 | 696 def load(self, fname): |
697 """Pulls command(s) into sql buffer. Returns number of commands loaded.""" | |
698 try: | |
699 f = open(fname, 'r') | |
700 except IOError, e: | |
701 try: | |
702 f = open('%s.sql' % fname, 'r') | |
703 except: | |
704 print 'Problem opening file %s: \n%s' % (fname, e) | |
705 return 0 | |
706 txt = f.read() | |
707 f.close() | |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
708 result = commandSeparator.separate(txt) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
709 self.history.extend(result) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
710 return len(result) |
0 | 711 def do_ed(self, arg): |
712 'ed [N]: brings up SQL from N commands ago in text editor, and puts result in SQL buffer.' | |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
713 fname = 'sqlpython_temp.sql' |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
714 buffer = self.last_matching_command(arg) |
0 | 715 f = open(fname, 'w') |
716 f.write(buffer) | |
717 f.close() | |
718 editSearcher.invoke(fname) | |
719 self.load(fname) | |
720 do_edit = do_ed | |
721 def do_get(self, fname): | |
722 'Brings SQL commands from a file to the in-memory SQL buffer.' | |
723 commandsLoaded = self.load(fname) | |
724 if commandsLoaded: | |
725 self.do_list('1-%d' % (commandsLoaded-1)) | |
726 def do_getrun(self, fname): | |
727 'Brings SQL commands from a file to the in-memory SQL buffer, and executes them.' | |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
728 newCommands = self.load(fname) * -1 |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
729 if newCommands: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
730 for command in self.history[newCommands:]: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
731 self.onecmd(command) |
0 | 732 def do_psql(self, arg): |
733 '''Shortcut commands emulating psql's backslash commands. | |
734 | |
735 \c connect | |
736 \d desc | |
737 \e edit | |
738 \g run | |
739 \h help | |
740 \i getrun | |
741 \o spool | |
742 \p list | |
743 \w save | |
744 \? help psql''' | |
745 commands = {} | |
746 for c in self.do_psql.__doc__.splitlines()[2:]: | |
747 (abbrev, command) = c.split(None, 1) | |
748 commands[abbrev[1:]] = command | |
749 words = arg.split(None,1) | |
750 abbrev = words[0] | |
751 try: | |
752 args = words[1] | |
753 except IndexError: | |
754 args = '' | |
755 try: | |
756 self.onecmd('%s %s' % (commands[abbrev], args)) | |
757 self.onecmd('q') | |
758 except KeyError: | |
759 print 'psql command \%s not yet supported.' % abbrev | |
760 def do_save(self, fname): | |
761 'save FILENAME: Saves most recent SQL command to disk.' | |
3
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
762 try: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
763 f = open(fname, 'w') |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
764 f.write(self.sqlBuffer[-1]) |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
765 f.close() |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
766 except Exception, e: |
cd23cd62de3c
history working pretty well
devlinjs@FA7CZA6N1254998.wrightpatterson.afmc.ds.af.mil
parents:
2
diff
changeset
|
767 print 'Error saving %s: %s' % (fname, str(e)) |
0 | 768 |
769 def do_print(self, arg): | |
770 'print VARNAME: Show current value of bind variable VARNAME.' | |
771 if arg: | |
772 if arg[0] == ':': | |
773 arg = arg[1:] | |
774 try: | |
775 print self.binds[arg] | |
776 except KeyError: | |
777 print 'No bind variable ', arg | |
778 else: | |
779 self.do_setbind('') | |
780 def do_setbind(self, arg): | |
781 args = arg.split(None, 2) | |
782 if len(args) == 0: | |
783 for (var, val) in self.binds.items(): | |
784 print ':%s = %s' % (var, val) | |
785 elif len(args) == 1: | |
786 try: | |
787 print ':%s = %s' % (args[0], self.binds[args[0]]) | |
788 except KeyError, e: | |
789 print noSuchBindMsg % args[0] | |
790 elif len(args) > 2 and args[1] in ('=',':='): | |
791 var, val = args[0], args[2] | |
792 if val[0] == val[-1] == "'" and len(val) > 1: | |
793 val = val[1:-1] | |
794 self.binds[var] = val | |
795 else: | |
796 print 'Could not parse ', args | |
797 def do_exec(self, arg): | |
798 if arg[0] == ':': | |
799 self.do_setbind(arg[1:]) | |
800 else: | |
801 self.default('exec %s' % arg) | |
802 | |
803 def _test(): | |
804 import doctest | |
805 doctest.testmod() | |
806 | |
807 if __name__ == "__main__": | |
808 "Silent return implies that all unit tests succeeded. Use -v to see details." | |
809 _test() |