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