diff sqlpython/sqlpyPlus.py @ 347:1c6e5410619e

pull, vc beginning to work
author Catherine Devlin <catherine.devlin@gmail.com>
date Thu, 23 Apr 2009 19:10:05 -0400
parents 747b325eb98d
children c652478be4fd
line wrap: on
line diff
--- a/sqlpython/sqlpyPlus.py	Thu Apr 23 18:05:04 2009 -0400
+++ b/sqlpython/sqlpyPlus.py	Thu Apr 23 19:10:05 2009 -0400
@@ -695,66 +695,6 @@
                                           terminator = arg.parsed.terminator or ';', 
                                           suffix = arg.parsed.suffix))
 
-    def _pull(self, arg, opts, vc=None):
-        """Displays source code."""
-        if opts.dump:
-            statekeeper = Statekeeper(self, ('stdout',))                        
-        try:
-            for (owner, object_name, object_type) in self.resolve_many(arg, opts):  
-                if object_type in self.supported_ddl_types:
-                    object_type = {'DATABASE LINK': 'DB_LINK', 'JAVA CLASS': 'JAVA_SOURCE'
-                                   }.get(object_type) or object_type
-                    object_type = object_type.replace(' ', '_')
-                    if opts.dump:
-                        try:
-                            os.makedirs(os.path.join(owner.lower(), object_type.lower()))
-                        except OSError:
-                            pass
-                        filename = os.path.join(owner.lower(), object_type.lower(), '%s.sql' % object_name.lower())
-                        self.stdout = open(filename, 'w')
-                        if vc:
-                            subprocess.call(vc + [filename])
-                    if object_type == 'PACKAGE':
-                        ddl = [['PACKAGE_SPEC', object_name, owner],['PACKAGE_BODY', object_name, owner]]                            
-                    elif object_type in ['CONTEXT', 'DIRECTORY', 'JOB']:
-                        ddl = [[object_type, object_name]]
-                    else:
-                        ddl = [[object_type, object_name, owner]]
-                    for ddlargs in ddl:
-                        try:
-                            code = str(self.curs.callfunc('DBMS_METADATA.GET_DDL', cx_Oracle.CLOB, ddlargs))
-                            if hasattr(opts, 'lines') and opts.lines:
-                                code = code.splitlines()
-                                template = "%%-%dd:%%s" % len(str(len(code)))
-                                code = '\n'.join(template % (n+1, line) for (n, line) in enumerate(code))
-                            if hasattr(opts, 'num') and (opts.num is not None):
-                                code = code.splitlines()
-                                code = centeredSlice(code, center=opts.num+1, width=opts.width)
-                                code = '\n'.join(code)
-                            self.stdout.write('REMARK BEGIN %s\n%s\nREMARK END\n\n' % (object_name, code))
-                        except cx_Oracle.DatabaseError, errmsg:
-                            if object_type == 'JOB':
-                                self.pfeedback('%s: DBMS_METADATA.GET_DDL does not support JOBs (MetaLink DocID 567504.1)' % object_name)
-                            elif 'ORA-31603' in str(errmsg): # not found, as in package w/o package body
-                                pass
-                            else:
-                                raise
-                    if opts.full:
-                        for dependent_type in ('OBJECT_GRANT', 'CONSTRAINT', 'TRIGGER'):        
-                            try:
-                                self.stdout.write('REMARK BEGIN\n%s\nREMARK END\n\n' % str(self.curs.callfunc('DBMS_METADATA.GET_DEPENDENT_DDL', cx_Oracle.CLOB,
-                                                                         [dependent_type, object_name, owner])))
-                            except cx_Oracle.DatabaseError:
-                                pass
-                    if opts.dump:
-                        self.stdout.close()
-        except:
-            if opts.dump:
-                statekeeper.restore()
-            raise
-        if opts.dump:
-            statekeeper.restore()    
-
     def _show_shortcut(self, shortcut, argpieces):
         try:
             newarg = argpieces[1]
@@ -812,12 +752,28 @@
                           help='# of lines before and after --lineNo'),              
               make_option('-a', '--all', action='store_true', help="all schemas' objects"),
               make_option('-x', '--exact', action='store_true', help="match object name exactly")])
-    def do_pull(self, arg, opts):
+    def do_pull(self, arg, opts, vc=None):
         """Displays source code."""
-        self._pull(arg, opts)
+        return self._pull(arg, opts, vc=None)
+    
+    def _pull(self, arg, opts, vc=None):
+        for (descrip, objtype, obj) in self.gerald_resolve(arg):
+            txt = obj.get_ddl()
+            if vc or opts.dump:
+                try:
+                    os.mkdir(objtype)
+                except OSError:
+                    pass
+                fname = descrip + '.sql'
+                f = open(fname, 'w')
+                f.write(txt)
+                f.close()
+                if vc:
+                    subprocess.call(vc + [fname])                        
+            else:
+                self.poutput(txt)           
             
     supported_ddl_types = 'CLUSTER, CONTEXT, DATABASE LINK, DIRECTORY, FUNCTION, INDEX, JOB, LIBRARY, MATERIALIZED VIEW, PACKAGE, PACKAGE BODY, PACKAGE SPEC, OPERATOR, PACKAGE, PROCEDURE, SEQUENCE, SYNONYM, TABLE, TRIGGER, VIEW, TYPE, TYPE BODY, XML SCHEMA'
-    do_pull.__doc__ += '\n\nSupported DDL types: ' + supported_ddl_types
     supported_ddl_types = supported_ddl_types.split(', ')    
 
     def _vc(self, arg, opts, program):
@@ -828,7 +784,7 @@
                 return
         subprocess.call([program, 'init'])
         opts.dump = True
-        self._pull(arg, opts, vc=[program, 'add'])
+        self._pull(arg, opts, [program, 'add'])
         subprocess.call([program, 'commit', '-m', '"%s"' % opts.message or 'committed from sqlpython'])        
     
     @options([
@@ -948,13 +904,13 @@
             return self._do_describe_oracle ()       
         if opts.refresh:
             self.connections[self.connection_number]['gerald_result'] = self.connections[self.connection_number]['gerald']()
-        for (descriptor, obj) in self.gerald_resolve(arg):
+        for (descriptor, objtype, obj) in self.gerald_resolve(arg):
             self.poutput(descriptor)
             if hasattr(obj, 'columns'):
                 self.tblname = obj.name
                 columns = obj.columns.values()
                 columns.sort()
-                self.pseudo_query(arg=arg, colnames = 'position name type nullable default', 
+                self.pseudo_query(arg=arg, colnames = 'pos name type null default', 
                                   rows=[(c[0], c[1], self._str_datatype_(c[2], c[3], c[4], c[5]), c[6], c[7]) 
                                         for c in columns])
         
@@ -1394,9 +1350,10 @@
         target = target.lower().strip()
         schema = self.connections[self.connection_number]['gerald_result'].schema
         for (objname, obj) in schema.items():
-            descriptor = '%s/%s' % (str(type(obj)).split('.')[-1].rstrip("'>"), objname)
+            objtype = str(type(obj)).split('.')[-1].rstrip("'>")
+            descriptor = os.path.join(objtype, objname)
             if (not target) or (objname == target) or (descriptor == target):
-                yield (descriptor, obj)
+                yield (descriptor, objtype, obj)
 
     @options([make_option('-l', '--long', action='store_true', help='long descriptions'),
           make_option('-a', '--all', action='store_true', help="all schemas' objects"),
@@ -1406,7 +1363,7 @@
         if self.rdbms == 'oracle':
             return self._do_ls_oracle(arg, opts)
         rows = []
-        for (descriptor, obj) in self.gerald_resolve(arg):
+        for (descriptor, objtype, obj) in self.gerald_resolve(arg):
             if opts.long:
                 rows.append((descriptor,))
             else: