changeset 351:cc67405f5455

gerald for grep
author catherine@cordelia
date Sat, 25 Apr 2009 06:08:49 -0400
parents e917403e6641
children 8e341308ea45
files sqlpython/sqlpyPlus.py sqlpython/sqlpython.py
diffstat 2 files changed, 30 insertions(+), 38 deletions(-) [+]
line wrap: on
line diff
--- a/sqlpython/sqlpyPlus.py	Fri Apr 24 16:04:57 2009 -0400
+++ b/sqlpython/sqlpyPlus.py	Sat Apr 25 06:08:49 2009 -0400
@@ -311,6 +311,7 @@
         self.substvars = {}
         self.result_history = []
         self.rows_remembered = 10000
+        self.rdbms = None
         self.pystate = {'r': [], 'binds': self.binds, 'substs': self.substvars}
         
     # overrides cmd's parseline
@@ -1389,18 +1390,23 @@
                 yield (descriptor, obj)
 
     @options([make_option('-l', '--long', action='store_true', help='long descriptions'),
-          make_option('-a', '--all', action='store_true', help="all schemas' objects"),
-          make_option('-t', '--timesort', action='store_true', help="Sort by last_ddl_time"),              
-          make_option('-r', '--reverse', action='store_true', help="Reverse order while sorting")])        
+          #make_option('-a', '--all', action='store_true', help="all schemas' objects"),
+          #make_option('-t', '--timesort', action='store_true', help="Sort by last_ddl_time"),              
+          make_option('-r', '--reverse', action='store_true', help="Reverse order while sorting")
+          ])        
     def do_ls(self, arg, opts):
         if False and self.rdbms == 'oracle':
             return self._do_ls_oracle(arg, opts)
         rows = []
         for (descriptor, obj) in sorted(self.gerald_resolve(arg)):
+            row = [descriptor]
             if opts.long:
-                rows.append((descriptor, table_type, tablespace_name, comments))
-            else:
-                rows.append((descriptor,))
+                for attr in ('table_type', 'tablespace_name', 'comments'):
+                    if hasattr(obj, attr):
+                        row.append(getattr(obj, attr))
+                    else:
+                        row.append(None)
+            rows.append(row)
         if opts.long:
             colnames = 'name type tablespace comments'
         else:
@@ -1414,38 +1420,24 @@
 
         targetnames = arg.split()
         pattern = targetnames.pop(0)
-        targets = [] 
-        for target in targetnames:
-            if '*' in target:
-                self._execute("""SELECT owner, object_name FROM all_objects 
-                                 WHERE object_type IN ('TABLE','VIEW')
-                                 AND object_name LIKE '%s'""" %
-                              target.upper().replace('*','%'))
-                for row in self.curs:
-                    targets.append('%s.%s' % row)
-            else:
-                targets.append(target)
-        for target in targets:
-            self.stdout.write('%s\n' % target)
-            target = target.rstrip(';')
-            try:
-                self._execute('select * from %s where 1=0' % target) # first pass fills description
-                if opts.ignorecase:
-                    colnames = ['LOWER(%s)' % self._cast(d[0], 'CHAR') for d in self.curs.description]
-                else:
-                    colnames = ['LOWER(%s)' % self._cast(d[0], 'CHAR') for d in self.curs.description]
-                sql = ' or '.join("%s LIKE '%%%s%%'" % (cn, pattern.lower()) for cn in colnames)
-                sql = self.parsed('SELECT * FROM %s WHERE %s;' % (target, sql), terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)
-                self.do_select(sql)
-            except Exception, e:
-                self.perror(e)
-                import traceback
-                traceback.print_exc(file=sys.stdout)                
+        for targetname in targetnames:
+            for (descrip, target) in self.gerald_resolve(targetname):
+                if hasattr(target, 'columns'):
+                    self.poutput(descrip)
+                    if opts.ignorecase:
+                        whereclause = ' or '.join("LOWER(%s) LIKE '%%%s%%'" % (self._cast(cn), pattern.lower()) for cn in target.columns)
+                    else:
+                        whereclause = ' or '.join("%s LIKE '%%%s%%'" % (self._cast(cn), pattern) for cn in target.columns)
+                    sql = self.parsed('SELECT * FROM %s WHERE %s;' % (target.name, whereclause), 
+                                      terminator=arg.parsed.terminator or ';', suffix=arg.parsed.suffix)
+                    self.do_select(sql)
 
-    def _cast(self, colname, typ='CHAR'):
+    casting_syntax = {'oracle': {'VARCHAR': 'TO_CHAR(%(colname)s)'}, 'postgres': {'VARCHAR': 'CAST (%(colname)s AS VARCHAR)'}}
+    casting_syntax['mysql'] = casting_syntax['postgres']
+    def _cast(self, colname, typ='VARCHAR'):
         'self._cast(colname, typ) => Returns the RDBMS-equivalent "CAST (colname AS typ) expression.' 
-        converter = {'oracle': 'TO_%(typ)s(%(colname)s)'}.get(self.rdbms, 'CAST(%(colname)s AS %(typ)s)')
-        return converter % {'colname': colname, 'typ': typ}
+        converter = self.casting_syntax[self.rdbms][typ]
+        return converter % {'colname': colname}
     
     def _execute(self, sql, bindvars={}):
         self.sqlfeedback(sql)
--- a/sqlpython/sqlpython.py	Fri Apr 24 16:04:57 2009 -0400
+++ b/sqlpython/sqlpython.py	Sat Apr 25 06:08:49 2009 -0400
@@ -114,9 +114,9 @@
         conn['gerald_result'] = conn['gerald']()        
         return conn
     
-    def refresh(self, arg):
+    def do_refresh(self, arg):
         "Refreshes sqlpython's cache of metadata; use after DDL changes structure of tables, views, etc."
-        conn['gerald_result'] = conn['gerald']()        
+        self.connections[self.connection_number]['gerald_result'] = self.connections[self.connection_number]['gerald']()        
         
     def ora_connect(self, arg):
         import cx_Oracle