annotate sqlpython/sqlpyPlus.py @ 400:8903d24575f0

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