commit-gnue
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

r6670 - in trunk/gnue-common/src/datasources/drivers: DBSIG2 sapdb sapdb


From: johannes
Subject: r6670 - in trunk/gnue-common/src/datasources/drivers: DBSIG2 sapdb sapdb/Schema/Creation sapdb/Schema/Discovery sapdb/sapdb
Date: Thu, 11 Nov 2004 05:15:40 -0600 (CST)

Author: johannes
Date: 2004-11-11 05:15:39 -0600 (Thu, 11 Nov 2004)
New Revision: 6670

Added:
   trunk/gnue-common/src/datasources/drivers/sapdb/Schema/Creation/Creation.py
Removed:
   trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/RecordSet.py
   trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/ResultSet.py
Modified:
   trunk/gnue-common/src/datasources/drivers/DBSIG2/Connection.py
   trunk/gnue-common/src/datasources/drivers/sapdb/Info.py
   
trunk/gnue-common/src/datasources/drivers/sapdb/Schema/Discovery/Introspection.py
   trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/Connection.py
   trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/DataObject.py
   trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/Info.py
Log:
Brought MaxDB/SAP-DB driver back to life :)


Modified: trunk/gnue-common/src/datasources/drivers/DBSIG2/Connection.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/DBSIG2/Connection.py      
2004-11-10 11:27:51 UTC (rev 6669)
+++ trunk/gnue-common/src/datasources/drivers/DBSIG2/Connection.py      
2004-11-11 11:15:39 UTC (rev 6670)
@@ -59,6 +59,8 @@
   @param _boolean_true: Value to post to the database for boolean TRUE
       (defaults to '1')
   @param _numbers_as_string: Flags wether to convert numbers to strings or not
+  @param _named_as_sequence: If paramstyle = 'named' pass parameters as
+      sequence (True) or as mapping (False)
   """
   _driver = None                        # DBSIG2 compatible driver module
   _boolean_false = '0'                  # value to pass for boolean FALSE
@@ -66,6 +68,7 @@
   _broken_fetchmany = False             # Does fetchmany () raise an exception
                                         # when no records are left?
   _numbers_as_string = True             # Convert numbers into strings
+  _named_as_sequence = False            # Pass 'named' parameters as sequence
 
   # This should be over-ridden only if driver needs more than user/pass
   def getLoginFields(self):
@@ -205,6 +208,7 @@
 
   def __param_named (self, statement, parameters):
     s = statement
+    values = []
     while True:
       start = string.find (s, '%(')
       if start == -1:
@@ -214,8 +218,11 @@
         break
       key = s [start+2:end]
       s = s [:start] + (':%s' % key) + s [end+2:]
-    return (s, parameters)
+      values.append (parameters [key])
 
+    return (s, self._named_as_sequence and values or parameters)
+
+
   def __param_format (self, statement, parameters):
     s = statement
     l = []

Modified: trunk/gnue-common/src/datasources/drivers/sapdb/Info.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/sapdb/Info.py     2004-11-10 
11:27:51 UTC (rev 6669)
+++ trunk/gnue-common/src/datasources/drivers/sapdb/Info.py     2004-11-11 
11:15:39 UTC (rev 6670)
@@ -1,10 +1,13 @@
+# GNU Enterprise Common - Database Drivers - MaxDB/SAP-DB
 #
-# This file is part of GNU Enterprise.
+# Copyright 2001-2004 Free Software Foundation
 #
+# This file is part of GNU Enterprise
+#
 # GNU Enterprise is free software; you can redistribute it
 # and/or modify it under the terms of the GNU General Public
 # License as published by the Free Software Foundation; either
-# version 2, or(at your option) any later version.
+# version 2, or (at your option) any later version.
 #
 # GNU Enterprise is distributed in the hope that it will be
 # useful, but WITHOUT ANY WARRANTY; without even the implied
@@ -16,8 +19,7 @@
 # write to the Free Software Foundation, Inc., 59 Temple Place
 # - Suite 330, Boston, MA 02111-1307, USA.
 #
-# Copyright 2000-2004 Free Software Foundation
-#
+# $Id$
 """
 Info for this database.
 """


Property changes on: trunk/gnue-common/src/datasources/drivers/sapdb/Info.py
___________________________________________________________________
Name: svn:keywords
   + Id

Added: 
trunk/gnue-common/src/datasources/drivers/sapdb/Schema/Creation/Creation.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/sapdb/Schema/Creation/Creation.py 
2004-11-10 11:27:51 UTC (rev 6669)
+++ trunk/gnue-common/src/datasources/drivers/sapdb/Schema/Creation/Creation.py 
2004-11-11 11:15:39 UTC (rev 6670)
@@ -0,0 +1,166 @@
+# GNU Enterprise Common - MaxDB/SAP-DB Driver - Schema Creation
+#
+# Copyright 2001-2004 Free Software Foundation
+#
+# This file is part of GNU Enterprise
+#
+# GNU Enterprise is free software; you can redistribute it
+# and/or modify it under the terms of the GNU General Public
+# License as published by the Free Software Foundation; either
+# version 2, or (at your option) any later version.
+#
+# GNU Enterprise is distributed in the hope that it will be
+# useful, but WITHOUT ANY WARRANTY; without even the implied
+# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+# PURPOSE. See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public
+# License along with program; see the file COPYING. If not,
+# write to the Free Software Foundation, Inc., 59 Temple Place
+# - Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id$
+
+from gnue.common.apps import errors
+from gnue.common.datasources.drivers.DBSIG2.Schema.Creation import \
+    Creation as Base
+
+
+# =============================================================================
+#
+# =============================================================================
+
+class Creation (Base.Creation):
+
+  END_COMMAND     = ""
+  MAX_NAME_LENGTH = 32
+  MAX_VARCHAR_LEN = 3999                # For ASCII type, UNICODE is 4000
+
+  # ---------------------------------------------------------------------------
+  # We cannot create a database (atm)
+  # ---------------------------------------------------------------------------
+
+  def createDatabase (self):
+    """
+    """
+
+    raise errors.AdminError, \
+        u_("MaxDB/SAP-DB driver does not support database creation")
+
+
+  # ---------------------------------------------------------------------------
+  # Handle special defaults
+  # ---------------------------------------------------------------------------
+
+  def _defaultwith (self, code, tableName, fieldDef, forAlter):
+    """
+    This function set's the defaults for 'serial'- and 'timestamp'-defaults
+            
+    @param code: code-tuple to merge the result in
+    @param tableName: name of the table
+    @param fieldDef: dictionary describing the field with the default
+    @param forAlter: TRUE if the definition is used in a table modification
+    """
+
+    if fieldDef ['defaultwith'] == 'serial':
+      fieldDef ['default'] = 'SERIAL'
+
+    elif fieldDef ['defaultwith'] == 'timestamp':
+      fieldDef ['default'] = 'TIMESTAMP'
+
+
+  # ---------------------------------------------------------------------------
+  # A key is an integer
+  # ---------------------------------------------------------------------------
+
+  def key (self, fieldDefinition):
+    """
+    Native datatype for a key field is INTEGER
+
+    @param fieldDefinition: dictionary describing the field
+
+    @return: 'INTEGER'
+    """
+
+    return "INTEGER"
+
+
+  # ---------------------------------------------------------------------------
+  # Create an apropriate datatype for numbers
+  # ---------------------------------------------------------------------------
+
+  def number (self, fieldDefinition):
+    """
+    This function returns an apropriate numeric type
+
+    @param fieldDefinition: dictionary describing the field
+
+    @return: numeric type (smallint, integer, fixed)
+    """
+
+    scale  = fieldDefinition.get ('precision', 0)
+    length = fieldDefinition.get ('length', 0)
+
+    if not scale:
+      if length <= 5:
+        return "SMALLINT"
+
+      elif length <= 10:
+        return "INTEGER"
+
+      else:
+        return "FIXED (%d)" % length
+
+    else:
+      return "FIXED (%d,%d)" % (length, scale)
+
+
+  # ---------------------------------------------------------------------------
+  # Native datatype for booleans
+  # ---------------------------------------------------------------------------
+
+  def boolean (self, fieldDefinition):
+    """
+    This funciton returns the native data type for a boolean, which is 
'boolean'
+
+    @param fieldDefinition: dictionary describing the field
+    @return: 'BOOLEAN'
+    """
+
+    return "BOOLEAN"
+
+
+  # ---------------------------------------------------------------------------
+  # Native datatype for datetime is timestamp
+  # ---------------------------------------------------------------------------
+
+  def datetime (self, fieldDefinition):
+    """
+    This function returns the native type for a datetime value
+
+    @param fieldDefinition: dictionary describing the field
+    @return: 'TIMESTAMP'
+    """
+
+    return "TIMESTAMP"
+
+
+  # ---------------------------------------------------------------------------
+  # Get an apropriate type for strings
+  # ---------------------------------------------------------------------------
+
+  def string (self, fieldDefinition):
+    """
+    This function returns a native type for strings
+
+    @param fieldDefinition: dictionary describing the field
+    @return: 'VARCHAR (?)' or 'LONG'
+    """
+
+    length = fieldDefinition.get ('length', self.MAX_VARCHAR_LEN)
+
+    if length <= self.MAX_VARCHAR_LEN:
+      return "VARCHAR (%d)" % length
+
+    else:
+      return "LONG"


Property changes on: 
trunk/gnue-common/src/datasources/drivers/sapdb/Schema/Creation/Creation.py
___________________________________________________________________
Name: svn:keywords
   + Id

Modified: 
trunk/gnue-common/src/datasources/drivers/sapdb/Schema/Discovery/Introspection.py
===================================================================
--- 
trunk/gnue-common/src/datasources/drivers/sapdb/Schema/Discovery/Introspection.py
   2004-11-10 11:27:51 UTC (rev 6669)
+++ 
trunk/gnue-common/src/datasources/drivers/sapdb/Schema/Discovery/Introspection.py
   2004-11-11 11:15:39 UTC (rev 6670)
@@ -1,10 +1,13 @@
+# GNU Enterprise Common - MaxDB/SAP-DB Driver - Schema Introspection
 #
-# This file is part of GNU Enterprise.
+# Copyright 2001-2004 Free Software Foundation
 #
+# This file is part of GNU Enterprise
+#
 # GNU Enterprise is free software; you can redistribute it
 # and/or modify it under the terms of the GNU General Public
 # License as published by the Free Software Foundation; either
-# version 2, or(at your option) any later version.
+# version 2, or (at your option) any later version.
 #
 # GNU Enterprise is distributed in the hope that it will be
 # useful, but WITHOUT ANY WARRANTY; without even the implied
@@ -16,178 +19,207 @@
 # write to the Free Software Foundation, Inc., 59 Temple Place
 # - Suite 330, Boston, MA 02111-1307, USA.
 #
-# Copyright 2000-2004 Free Software Foundation
-#
-# FILE:
-# Introspection.py
-#
-# DESCRIPTION:
-#
-# NOTES:
-#
+# $Id$
 
 __all__ = ['Introspection']
 
 import string
-from string import lower, join, split
-import sys
 
-from gnue.common.apps import GDebug, GConfig
-from gnue.common.apps import GDebug, GConfig
 from gnue.common.datasources import GIntrospection
 
-class Introspection(GIntrospection.Introspection):
 
-  # list of the types of Schema objects this driver provides
-  types =[ ('table',    _('Tables'),1),
-           ('view',     _('Views'), 1),
-           ('synonym',  _('Synonyms'),1),
-           ('result',   _('Result Table'),1) ]
+# =============================================================================
+# This class implements schema introspection for MaxDB/SAP-DB backends
+# =============================================================================
 
-  #
-  # TODO: This is a quick hack to get this class
-  # TODO: into the new-style schema format.
-  # TODO: getSchema* should be merged into find()
-  #
-  def find(self, name=None, type=None):
-    if name is None:
-      return self.getSchemaList(type)
-    else:
-      rs = self.getSchemaByName(name, type)
-      if rs:
-        return [rs]
-      else:
-        return None
+class Introspection (GIntrospection.Introspection):
 
+  # list of the types of Schema objects this driver provides
+  types =[ ('table',   _('Tables'),       1),
+           ('view',    _('Views'),        1),
+           ('synonym', _('Synonyms'),     1),
+           ('result',  _('Result Table'), 1) ]
 
-  # TODO: Merge into find()
-  # Return a list of Schema objects
+  # ---------------------------------------------------------------------------
+  # Find a schema element by name or type
+  # ---------------------------------------------------------------------------
 
-  # Return a list of Schema objects
-  def getSchemaList(self, type=None):
+  def find (self, name = None, type = None):
+    """
+    This function searches the schema for an element by name and/or type. If no
+    name and no type is given, all elements will be retrieved.
 
-    where_user = ""
-    if type == None:
-      where_type = "where TYPE <> 'SYSTEM' and TYPE <> 'SYNONYM' "
-    else:
-      where_type = "where TYPE='%s'" % string.upper(type)
+    @param name: look for an element with this name
+    @param type: look for an element of this type
+    @return: A sequence of schema instances, one per element found, or None if
+        no element could be found.
+    """
 
+    result = []
+    cond   = ["TYPE <> 'SYSTEM'"]
 
-    statement = \
-      "select owner||'.'||tablename||'.'||type, " + \
-        "owner||'.'||tablename table_name, " + \
-        "type table_type " + \
-        "from domain.tables %s" \
-              % (where_type) + \
-          "order by tablename "
+    if name is not None:
+      cond.append ("TABLENAME = '%s'" % name.upper ())
 
-    GDebug.printMesg(5,statement)
+    if type is not None:
+      cond.append ("TABLETYPE = '%s'" % type.upper ())
 
-    cursor = self._connection.native.cursor()
-    cursor.execute(statement)
+    cmd = u"SELECT tableid, tablename, tabletype, owner FROM DOMAIN.TABLES " \
+           "WHERE %s ORDER BY tablename" % string.join (cond, " AND ")
 
-    list = []
-    for rs in cursor.fetchall():
-      list.append(GIntrospection.Schema(attrs={'id':rs[0], 'name':rs[1],
-                         'type':string.lower(rs[2])},
-                         getChildSchema=self.__getFieldSchema))
+    cursor = self._connection.makecursor (cmd)
+    try:
+      for rs in cursor.fetchall ():
+        attrs = {'id'        : rs [0],
+                 'name'      : rs [1],
+                 'type'      : rs [2],
+                 'owner'     : rs [3],
+                 'indices'   : self.__getIndices (rs [1]),
+                 'primarykey': self.__getPrimaryKey (rs [1], rs [2])}
 
-    cursor.close()
-    return list
+        result.append (GIntrospection.Schema (attrs, self._getChildSchema))
 
+    finally:
+      cursor.close ()
 
-  # Find a schema object with specified name
-  def getSchemaByName(self, name, type=None):
+    return len (result) and result or None
 
-    where_user = ""
-    parts = string.split(string.upper(name),'.')
-    name = parts[-1]
-    if len(parts) > 1:
-      schema = " and owner='%s'" % parts[-2]
-    else:
-      schema = ""
 
-    statement = \
-      "select owner||'.'||tablename||'.'||type, " + \
-        "owner||'.'||tablename table_name, " + \
-        "type table_type, " + \
-        "owner, tablename " + \
-        "from domain.tables where tablename='%s'%s" \
-              % (name, schema) + \
-          "order by tablename "
+  # ---------------------------------------------------------------------------
+  # Get all fields of a relation
+  # ---------------------------------------------------------------------------
 
-    GDebug.printMesg(5,statement)
+  def _getChildSchema (self, parent):
+    """
+    This function returns a list of all child elements of a given parent
+    relation.
 
-    cursor = self._connection.native.cursor()
-    cursor.execute(statement)
+    @param parent: schema instance to fetch child elements for
+    @return: sequence of schema instances, one per element found
+    """
 
-    list = []
-    for rs in cursor.fetchall():
-      list.append(GIntrospection.Schema(attrs={'id':string.lower(rs[0]), 
'name':rs[1],
-                         'type':rs[2], 'sapdbId': (rs [3], rs [4])},
-                         getChildSchema=self.__getFieldSchema))
+    cmd = u"SELECT columnname, mode, datatype, len, dec, nullable, " \
+           "\"DEFAULT\", \"DEFAULTFUNCTION\", pos, keypos " \
+           "FROM DOMAIN.COLUMNS " \
+           "WHERE tablename = '%s' AND owner = '%s' AND tabletype = '%s' " \
+           "ORDER BY columnname" \
+           % (parent.name.upper (), parent.owner, parent.type)
 
-    cursor.close()
+    result = []
+    cursor = self._connection.makecursor (cmd)
 
     try:
-      return list[0]
-    except:
-      return None
+      for rs in cursor.fetchall ():
+        nativetype = rs [2]
+        attrs = {'id'        : "%s.%s" % (parent.name, rs [0]),
+                 'name'      : rs [0],
+                 'type'      : 'field',
+                 'nativetype': nativetype,
+                 'required'  : rs [5] == 'NO',
+                 'pos'       : rs [8],
+                 'keypos'    : rs [9]}
 
+        if nativetype in ['DATE', 'TIME', 'TIMESTAMP']:
+          attrs ['datatype'] = 'date'
 
+        elif nativetype in ['FIXED', 'FLOAT', 'INTEGER', 'SMALLINT']:
+          attrs ['datatype']  = 'number'
+          attrs ['length']    = rs [3]
 
-  # Get fields for a table
-  def __getFieldSchema(self, parent):
+          if nativetype == 'FIXED':
+            attrs ['precision'] = rs [4]
 
-    # TODO: This does not support user-defined datatypes...
-    # TODO: it will always report such as TEXT-like fields.
+        elif nativetype in ['BOOLEAN']:
+          attrs ['datatype'] = 'number'
 
-    schema, name, type = string.split(parent.id,'.')
-    owner, basename = parent.sapdbId
-    cursor = self._connection.native.cursor()
+        else:
+          attrs ['datatype'] = 'text'
+          attrs ['length']   = rs [3]
 
-#    if type == 'synonym':
-#      statement = "select base_tabschema, base_tabname " + \
-#                  "from syscat.tables " + \
-#                  "where tabschema = '%s' and tabname='%s'" % (schema, name)
-#
-#      GDebug.printMesg(5,statement)
-#
-#      cursor.execute(statement)
-#      rs = cursor.fetchone()
-#      schema, name = rs
+        if rs [6] is not None:
+          attrs ['defaulttype'] = 'constant'
+          attrs ['defaultval']  = rs [6]
 
-    statement = \
-       "select owner||'.'||tablename||'.'||columnname, " + \
-       "columnname, datatype, 'Y', len, dec " + \
-       "from domain.columns " + \
-       "where owner = '%s' and tablename = '%s' " % (owner, basename) + \
-       'order by "POS"'
+        elif rs [7] is not None:
+          attrs ['defaulttype'] = 'system'
+          attrs ['defaultval']  = rs [7]
 
-    GDebug.printMesg(5,statement)
+        result.append (GIntrospection.Schema (attrs))
 
-    cursor.execute(statement)
+    finally:
+      cursor.close ()
 
-    list = []
-    for rs in cursor.fetchall():
+    return result
 
-      attrs={'id': rs[0], 'name': rs[1],
-             'type':'field', 'nativetype': rs[2],
-             'required': 'N'}
 
-      if rs[2] in ('BOOLEAN','FIXED','FLOAT','INTEGER','LONG','SMALLINT'):
-        attrs['precision'] = rs[5]
-        attrs['datatype'] = 'number'
-      elif rs[2] in ('DATE','TIME','TIMESTAMP'):
-        attrs['datatype'] = 'date'
-      else:
-        attrs['datatype'] = 'text'
+  # ---------------------------------------------------------------------------
+  # Get the primary key of a relation (if it has one)
+  # ---------------------------------------------------------------------------
 
-      if rs[5] != 0:
-        attrs['length'] = rs[4]
+  def __getPrimaryKey (self, tablename, tabletype):
+    """
+    This function returns a sequence with the primary key fields or None if the
+    given relation has no primary key.
 
-      list.append(GIntrospection.Schema(attrs=attrs))
+    @param tablename: name of the table to fetch the primary key for
+    @param tabletype: type of the table to fetch the primary key for
 
-    cursor.close()
-    return tuple(list)
+    @return: sequence of primary key fields or None
+    """
 
+    cmd = u"SELECT columnname FROM DOMAIN.COLUMNS " \
+           "WHERE tablename = '%s' AND tabletype = '%s' AND mode = 'KEY'" \
+           "ORDER BY keypos" % (tablename.upper (), tabletype)
+
+    cursor = self._connection.makecursor (cmd)
+
+    try:
+      result = [rs [0] for rs in cursor.fetchall ()]
+
+    finally:
+      cursor.close ()
+
+    return len (result) and result or None
+
+
+  # ---------------------------------------------------------------------------
+  # Get a dictionary of all indices defined for a relation
+  # ---------------------------------------------------------------------------
+
+  def __getIndices (self, tablename):
+    """
+    This function returns a dictionary with indices of the given table. The
+    keys are the index names and the values are dictionaries describing the
+    index.
+
+    @param tablename: name of the table to fetch indices for.
+    @return: dictionary with indices or None
+    """
+
+    cmd = u"SELECT indexname, type FROM INDEXES WHERE tablename = '%s'" \
+          % tablename.upper ()
+
+    result = {}
+    cursor = self._connection.makecursor (cmd)
+
+    try:
+      for rs in cursor.fetchall ():
+        result [rs [0]] = {'unique' : rs [1] == 'UNIQUE',
+                           'primary': False,
+                           'fields' : []}
+
+        cmd = u"SELECT columnname FROM INDEXCOLUMNS " \
+               "WHERE tablename = '%s' AND indexname = '%s' " \
+               "ORDER BY columnno" % (tablename.upper (), rs [0])
+
+        fcursor = self._connection.makecursor (cmd)
+        try:
+          result [rs [0]]['fields'] = [fr [0] for fr in fcursor.fetchall ()]
+
+        finally:
+          fcursor.close ()
+
+    finally:
+      cursor.close ()
+
+    return len (result.keys ()) and result or None


Property changes on: 
trunk/gnue-common/src/datasources/drivers/sapdb/Schema/Discovery/Introspection.py
___________________________________________________________________
Name: svn:keywords
   + Id

Modified: trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/Connection.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/Connection.py 
2004-11-10 11:27:51 UTC (rev 6669)
+++ trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/Connection.py 
2004-11-11 11:15:39 UTC (rev 6670)
@@ -1,6 +1,9 @@
+# GNU Enterprise Common - Database Drivers - Driver for MaxDB/SAP-DB
 #
-# This file is part of GNU Enterprise.
+# Copyright 2001-2004 Free Software Foundation
 #
+# This file is part of GNU Enterprise
+#
 # GNU Enterprise is free software; you can redistribute it
 # and/or modify it under the terms of the GNU General Public
 # License as published by the Free Software Foundation; either
@@ -16,99 +19,71 @@
 # write to the Free Software Foundation, Inc., 59 Temple Place
 # - Suite 330, Boston, MA 02111-1307, USA.
 #
-# Copyright 2000-2004 Free Software Foundation
-#
-# FILE:
-# sapdb/DBdriver.py
-#
-# DESCRIPTION:
-# Driver to provide access to data via MySQL's MaxDB/SAP-DB Python Driver
-#
-# NOTES:
-#
-#   Supported attributes (via connections.conf or <database> tag)
-#
-#     host=      This is the SAP-DB host for your connection (optional)
-#     dbname=    This is the SAP-DB database to use (required)
-#     timeout=   Command timeout in seconds (optional)
-#     isolation= Isolation level (options)
-#     sqlmode=   INTERNAL or ORACLE (optional)
-#     sqlsubmode= ODBC or empty (optional)
-#
+# $Id$
 
 __all__ = ['Connection']
 
-####                                   ####
-#### IF YOU MODIFY ANY CONNECTION      ####
-#### ATTRIBUTES, PLEASE UPDATE info.py ####
-####                                   ####
-
-import string
-from string import lower
-import sys
-from gnue.common.datasources import GDataObjects, GConditions, GConnections
-from gnue.common.apps import GDebug
+from gnue.common.apps import errors, i18n
+from gnue.common.datasources import Exceptions
 from gnue.common.datasources.drivers import DBSIG2
+from DataObject import *
 
-try:
-  import sapdbapi as SIG2api
-except ImportError:
-  raise GConnections.DependencyError, ('sapdbapi', None)
+import sapdb.dbapi
 
-from gnue.common.datasources.drivers.sapdb.Schema.Discovery.Introspection 
import Introspection
+from gnue.common.datasources.drivers.sapdb.Schema.Discovery.Introspection \
+    import Introspection
+from gnue.common.datasources.drivers.sapdb.Schema.Creation.Creation \
+    import Creation
 
 
-######################################################################
-#
-#  GConnection object for PostgreSQL-based drivers
-#
-class Connection(DBSIG2.Connection):
+# =============================================================================
+# Connection object for MaxDB/SAP-DB backends
+# =============================================================================
 
-  driver = SIG2api
-  _DatabaseError = SIG2api.DatabaseError
-  defaultBehavior = Introspection
+class Connection (DBSIG2.Connection):
+
+  _driver            = sapdb.dbapi
+  _DatabaseError     = sapdb.dbapi.DatabaseError
+  _named_as_sequence = True
+  defaultBehavior    = Introspection
+  defaultCreator     = Creation
+  _boolean_false     = False
+  _boolean_true      = True
+  _numbers_as_string = False
+
   supportedDataObjects = {
     'object': DataObject_Object,
     'sql':    DataObject_SQL
   }
 
-  def connect(self, connectData={}):
-    GDebug.printMesg(1,"SAP database driver initializing")
+  # ---------------------------------------------------------------------------
+  # Connect to the database
+  # ---------------------------------------------------------------------------
+
+  def connect (self, connectData = {}):
+    """
+    """
+
+    gDebug (1, "SAP database driver initializing")
+
     try:
       options = {'autocommit': 'off'}
-      for gnueName, sapdbName in [('sqlmode', 'sqlmode'),
-                                  ('timeout', 'timeout'),
-                                  ('isolation', 'isolation'),
+      
+      for gnueName, sapdbName in [('sqlmode'   , 'sqlmode'),
+                                  ('timeout'   , 'timeout'),
+                                  ('isolation' , 'isolation'),
                                   ('sqlsubmode', 'component')]:
-          if connectData.has_key (gnueName):
-              options [sapdbName] = connectData [gnueName]
-      self.native = apply (SIG2api.connect,
-        (connectData['_username'], connectData['_password'],
-        connectData['dbname'], connectData.get ('host', '')),
-        options)
-      #self.native = SIG2api.connect( \
-      #             user=connectData['_username'], \
-      #             password=connectData['_password'], \
-      #             database=connectData['dbname'], \
-      #             host=connectData.get ('host', ''), \
-      #             autocommit="off")
-    except self._DatabaseError, value:
-      raise GDataObjects.LoginError, value
+        if connectData.has_key (gnueName):
+          options [sapdbName] = connectData [gnueName]
 
+      user   = connectData ['_username']
+      passwd = connectData ['_password']
+      dbname = connectData ['dbname']
+      host   = connectData.get ('host', '')
 
-def createConnection (conn, **overrides):
-    from gnue.common.datasources.GConnections import GConnections
-    connections = GConnections (r'D:\Python22\etc\connections.conf')
-    parameters = connections.getConnectionParameters (conn).copy ()
-    dataObject = connections.getDataObject (conn, 'object')
-    parameters.update (overrides)
-    dataObject.connect (parameters)
-    return dataObject
+      self.native = sapdb.dbapi.connect (user, passwd, dbname, host, **options)
 
-def testConnection ():
-    conn, user, pwd = sys.argv [1:4]
-    connection = createConnection (conn, _username = user, _password = pwd)
-    connection.getSchemaList ()
-
-if __name__ == "__main__":
-    testConnection ()
+    except self._DatabaseError:
+      raise Exceptions.LoginError, \
+          u_("The MaxDB/SAP-DB driver returned the following error:\n%s") \
+          % errors.getException () [2]


Property changes on: 
trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/Connection.py
___________________________________________________________________
Name: svn:keywords
   + Id

Modified: trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/DataObject.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/DataObject.py 
2004-11-10 11:27:51 UTC (rev 6669)
+++ trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/DataObject.py 
2004-11-11 11:15:39 UTC (rev 6670)
@@ -1,6 +1,9 @@
+# GNU Enterprise Common - Database Drivers - MaxDB/SAP-DB Driver
 #
-# This file is part of GNU Enterprise.
+# Copyright 2001-2004 Free Software Foundation
 #
+# This file is part of GNU Enterprise
+#
 # GNU Enterprise is free software; you can redistribute it
 # and/or modify it under the terms of the GNU General Public
 # License as published by the Free Software Foundation; either
@@ -16,310 +19,19 @@
 # write to the Free Software Foundation, Inc., 59 Temple Place
 # - Suite 330, Boston, MA 02111-1307, USA.
 #
-# Copyright 2000-2004 Free Software Foundation
-#
-# FILE:
-# sapdb/DBdriver.py
-#
-# DESCRIPTION:
-# Driver to provide access to data via SAP's SAP-DB/Python Driver
-# Requires SAP-DB (http://www.sapdb.org/)
-#
-# NOTES:
-#
-#   Supported attributes (via connections.conf or <database> tag)
-#
-#     host=      This is the SAP-DB host for your connection (optional)
-#     dbname=    This is the SAP-DB database to use (required)
-#     timeout=   Command timeout in seconds (optional)
-#     isolation= Isolation level (options)
-#     sqlmode=   INTERNAl or ORACLE (optional)
-#     sqlsubmode= ODBC or empty (optional)
-#
+# $Id$
 
-_exampleConfig = """
-# This connection uses the SAP DB  driver
-# We will be connecting to the SAP DB server on
-# "localhost" to a database called "TST".
-[sapdb]
-comment = XYZ Development Database
-provider = sapdb
-dbname = TST
-# host = localhost   # (optional)
-# sqlmode = INTERNAL # (default) or ORACLE
-# sqlsubmode = ODBC  # (for compatibility with the SAP DB ODBC driver)
-# timeout = 900      # (command timeout in seconds)
-# isolation = 1      # 0, 1 (default), 10, 15, 2, 20, 3, 30
-"""
-#### THIS IS AN UNTESTED DRIVER ####
-####      Any volunteers?       ####
+__all__ = ['DataObject_SQL', 'DataObject_Object']
 
-import string
-from string import lower
-import sys
-from gnue.common.datasources import GDataObjects, GConditions, GConnections
-from gnue.common.apps import GDebug
 from gnue.common.datasources.drivers import DBSIG2
 
-raise "This data driver has not been upgraded to the new format."
+class _Base:
+  _escapeSingleQuote = "'"
+  _dateTimeFormat    = "'%Y-%m-%d %H:%M:%S'"
 
-try:
-  import sapdbapi as SIG2api
-except ImportError, message:
-  tmsg = u_("Driver not installed: sapdbapi for SAP-DB 7.x \n[%s]") % message
-  raise GConnections.AdapterNotInstalled, tmsg
+class DataObject_SQL (_Base, DBSIG2.DataObject_SQL):
+  pass
 
-class SAP_RecordSet(DBSIG2.RecordSet):
+class DataObject_Object (_Base, DBSIG2.DataObject_Object):
   pass
 
-
-class SAP_ResultSet(DBSIG2.ResultSet):
-  def __init__(self, dataObject, cursor=None, defaultValues={}, 
masterRecordSet=None):
-    DBSIG2.ResultSet.__init__(self, dataObject, \
-            cursor, defaultValues, masterRecordSet)
-    self._recordSetClass = SAP_RecordSet
-
-
-
-class SAP_DataObject(DBSIG2.DataObject):
-  def __init__(self):
-    DBSIG2.DataObject.__init__(self)
-    self._DatabaseError = SIG2api.DatabaseError
-    self._resultSetClass = SAP_ResultSet
-
-
-  def connect(self, connectData={}):
-    GDebug.printMesg(1,"SAP database driver initializing")
-    try:
-      options = {'autocommit': 'off'}
-      for gnueName, sapdbName in [('sqlmode', 'sqlmode'),
-                                  ('timeout', 'timeout'),
-                                  ('isolation', 'isolation'),
-                                  ('sqlsubmode', 'component')]:
-          if connectData.has_key (gnueName):
-              options [sapdbName] = connectData [gnueName]
-      self._dataConnection = apply (SIG2api.connect,
-        (connectData['_username'], connectData['_password'],
-        connectData['dbname'], connectData.get ('host', '')),
-        options)
-      #self._dataConnection = SIG2api.connect( \
-      #             user=connectData['_username'], \
-      #             password=connectData['_password'], \
-      #             database=connectData['dbname'], \
-      #             host=connectData.get ('host', ''), \
-      #             autocommit="off")
-    except self._DatabaseError, value:
-      raise GDataObjects.LoginError, value
-
-    self._postConnect()
-
-  def _postConnect(self):
-    self.triggerExtensions = TriggerExtensions(self._dataConnection)
-
-
-  #
-  # Schema (metadata) functions
-  #
-
-  # Return a list of the types of Schema objects this driver provides
-  def getSchemaTypes(self):
-    return [ ('table',    _('Tables'),1),
-             ('view',     _('Views'), 1),
-             ('synonym',  _('Synonyms'),1),
-             ('result',   _('Result Table'),1) ]
-
-
-  # Return a list of Schema objects
-  def getSchemaList(self, type=None):
-
-    where_user = ""
-    if type == None:
-      where_type = "where TYPE <> 'SYSTEM' and TYPE <> 'SYNONYM' "
-    else:
-      where_type = "where TYPE='%s'" % string.upper(type)
-
-
-    statement = \
-      "select owner||'.'||tablename||'.'||type, " + \
-        "owner||'.'||tablename table_name, " + \
-        "type table_type " + \
-        "from domain.tables %s" \
-              % (where_type) + \
-          "order by tablename "
-
-    GDebug.printMesg(5,statement)
-
-    cursor = self._dataConnection.cursor()
-    cursor.execute(statement)
-
-    list = []
-    for rs in cursor.fetchall():
-      list.append(GDataObjects.Schema(attrs={'id':rs[0], 'name':rs[1],
-                         'type':string.lower(rs[2])},
-                         getChildSchema=self.__getFieldSchema))
-
-    cursor.close()
-    return list
-
-
-  # Find a schema object with specified name
-  def getSchemaByName(self, name, type=None):
-
-    where_user = ""
-    parts = string.split(string.upper(name),'.')
-    name = parts[-1]
-    if len(parts) > 1:
-      schema = " and owner='%s'" % parts[-2]
-    else:
-      schema = ""
-
-    statement = \
-      "select owner||'.'||tablename||'.'||type, " + \
-        "owner||'.'||tablename table_name, " + \
-        "type table_type, " + \
-        "owner, tablename " + \
-        "from domain.tables where tablename='%s'%s" \
-              % (name, schema) + \
-          "order by tablename "
-
-    GDebug.printMesg(5,statement)
-
-    cursor = self._dataConnection.cursor()
-    cursor.execute(statement)
-
-    list = []
-    for rs in cursor.fetchall():
-      list.append(GDataObjects.Schema(attrs={'id':string.lower(rs[0]), 
'name':rs[1],
-                         'type':rs[2], 'sapdbId': (rs [3], rs [4])},
-                         getChildSchema=self.__getFieldSchema))
-
-    cursor.close()
-
-    try:
-      return list[0]
-    except:
-      return None
-
-
-
-  # Get fields for a table
-  def __getFieldSchema(self, parent):
-
-    # TODO: This does not support user-defined datatypes...
-    # TODO: it will always report such as TEXT-like fields.
-
-    schema, name, type = string.split(parent.id,'.')
-    owner, basename = parent.sapdbId
-    cursor = self._dataConnection.cursor()
-
-#    if type == 'synonym':
-#      statement = "select base_tabschema, base_tabname " + \
-#                  "from syscat.tables " + \
-#                  "where tabschema = '%s' and tabname='%s'" % (schema, name)
-#
-#      GDebug.printMesg(5,statement)
-#
-#      cursor.execute(statement)
-#      rs = cursor.fetchone()
-#      schema, name = rs
-
-    statement = \
-       "select owner||'.'||tablename||'.'||columnname, " + \
-       "columnname, datatype, 'Y', len, dec " + \
-       "from domain.columns " + \
-       "where owner = '%s' and tablename = '%s' " % (owner, basename) + \
-       'order by "POS"'
-
-    GDebug.printMesg(5,statement)
-
-    cursor.execute(statement)
-
-    list = []
-    for rs in cursor.fetchall():
-
-      attrs={'id': rs[0], 'name': rs[1],
-             'type':'field', 'nativetype': rs[2],
-             'required': 'N'}
-
-      if rs[2] in ('BOOLEAN','FIXED','FLOAT','INTEGER','LONG','SMALLINT'):
-        attrs['precision'] = rs[5]
-        attrs['datatype'] = 'number'
-      elif rs[2] in ('DATE','TIME','TIMESTAMP'):
-        attrs['datatype'] = 'date'
-      else:
-        attrs['datatype'] = 'text'
-
-      if rs[5] != 0:
-        attrs['length'] = rs[4]
-
-      list.append(GDataObjects.Schema(attrs=attrs))
-
-    cursor.close()
-    return tuple(list)
-
-
-class SAP_DataObject_Object(SAP_DataObject, \
-      DBSIG2.DataObject_Object):
-
-  def __init__(self):
-    SAP_DataObject.__init__(self)
-
-  def _buildQuery(self, conditions={},forDetail=None,additionalSQL=""):
-    return DBSIG2.DataObject_Object._buildQuery(self, 
conditions,forDetail,additionalSQL)
-
-
-class SAP_DataObject_SQL(SAP_DataObject, \
-      DBSIG2.DataObject_SQL):
-  def __init__(self):
-    # Call DBSIG init first because SAP_DataObject needs to overwrite
-    # some of its values
-    DBSIG2.DataObject_SQL.__init__(self)
-    SAP_DataObject.__init__(self)
-
-  def _buildQuery(self, conditions={}):
-    return DBSIG2.DataObject_SQL._buildQuery(self, conditions)
-
-
-#
-#  Extensions to Trigger Namespaces
-#
-class TriggerExtensions:
-
-  def __init__(self, connection):
-    self.__connection = connection
-
-
-
-
-
-######################################
-#
-#  The following hashes describe
-#  this driver's characteristings.
-#
-######################################
-
-#
-#  All datasource "types" and corresponding DataObject class
-#
-supportedDataObjects = {
-  'object': SAP_DataObject_Object,
-  'sql':    SAP_DataObject_SQL
-}
-
-def createConnection (conn, **overrides):
-    from gnue.common.datasources.GConnections import GConnections
-    connections = GConnections (r'D:\Python22\etc\connections.conf')
-    parameters = connections.getConnectionParameters (conn).copy ()
-    dataObject = connections.getDataObject (conn, 'object')
-    parameters.update (overrides)
-    dataObject.connect (parameters)
-    return dataObject
-
-def testConnection ():
-    conn, user, pwd = sys.argv [1:4]
-    connection = createConnection (conn, _username = user, _password = pwd)
-    connection.getSchemaList ()
-
-if __name__ == "__main__":
-    testConnection ()


Property changes on: 
trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/DataObject.py
___________________________________________________________________
Name: svn:keywords
   + Id

Modified: trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/Info.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/Info.py       
2004-11-10 11:27:51 UTC (rev 6669)
+++ trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/Info.py       
2004-11-11 11:15:39 UTC (rev 6670)
@@ -1,10 +1,13 @@
+# GNU Enterprise Common - Database Drivers - MaxDB/SAP-DB
 #
-# This file is part of GNU Enterprise.
+# Copyright 2001-2004 Free Software Foundation
 #
+# This file is part of GNU Enterprise
+#
 # GNU Enterprise is free software; you can redistribute it
 # and/or modify it under the terms of the GNU General Public
 # License as published by the Free Software Foundation; either
-# version 2, or(at your option) any later version.
+# version 2, or (at your option) any later version.
 #
 # GNU Enterprise is distributed in the hope that it will be
 # useful, but WITHOUT ANY WARRANTY; without even the implied
@@ -16,8 +19,7 @@
 # write to the Free Software Foundation, Inc., 59 Temple Place
 # - Suite 330, Boston, MA 02111-1307, USA.
 #
-# Copyright 2000-2004 Free Software Foundation
-#
+# $Id$
 """
 Information on this driver
 """
@@ -60,7 +62,12 @@
 dbname = TST
 timeout = 900
 
+
 Notes
 -----
-1. This driver is currently unmaintained and not functional.
+
+1. Creation of new database instances with 'gnue-schema --createdb' does not
+   work 
+
+2. Other than that the driver is fully functional
 """


Property changes on: 
trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/Info.py
___________________________________________________________________
Name: svn:keywords
   + Id

Deleted: trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/RecordSet.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/RecordSet.py  
2004-11-10 11:27:51 UTC (rev 6669)
+++ trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/RecordSet.py  
2004-11-11 11:15:39 UTC (rev 6670)
@@ -1,326 +0,0 @@
-#
-# This file is part of GNU Enterprise.
-#
-# GNU Enterprise is free software; you can redistribute it
-# and/or modify it under the terms of the GNU General Public
-# License as published by the Free Software Foundation; either
-# version 2, or (at your option) any later version.
-#
-# GNU Enterprise is distributed in the hope that it will be
-# useful, but WITHOUT ANY WARRANTY; without even the implied
-# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
-# PURPOSE. See the GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public
-# License along with program; see the file COPYING. If not,
-# write to the Free Software Foundation, Inc., 59 Temple Place
-# - Suite 330, Boston, MA 02111-1307, USA.
-#
-# Copyright 2000-2004 Free Software Foundation
-#
-# FILE:
-# sapdb/DBdriver.py
-#
-# DESCRIPTION:
-# Driver to provide access to data via SAP's SAP-DB/Python Driver
-# Requires SAP-DB (http://www.sapdb.org/)
-#
-# NOTES:
-#
-#   Supported attributes (via connections.conf or <database> tag)
-#
-#     host=      This is the SAP-DB host for your connection (optional)
-#     dbname=    This is the SAP-DB database to use (required)
-#     timeout=   Command timeout in seconds (optional)
-#     isolation= Isolation level (options)
-#     sqlmode=   INTERNAl or ORACLE (optional)
-#     sqlsubmode= ODBC or empty (optional)
-#
-
-_exampleConfig = """
-# This connection uses the SAP DB  driver
-# We will be connecting to the SAP DB server on
-# "localhost" to a database called "TST".
-[sapdb]
-comment = XYZ Development Database
-provider = sapdb
-dbname = TST
-# host = localhost   # (optional)
-# sqlmode = INTERNAL # (default) or ORACLE
-# sqlsubmode = ODBC  # (for compatibility with the SAP DB ODBC driver)
-# timeout = 900      # (command timeout in seconds)
-# isolation = 1      # 0, 1 (default), 10, 15, 2, 20, 3, 30
-"""
-#### THIS IS AN UNTESTED DRIVER ####
-####      Any volunteers?       ####
-
-import string
-from string import lower
-import sys
-from gnue.common.datasources import GDataObjects, GConditions, GConnections
-from gnue.common.apps import GDebug
-from gnue.common.datasources.drivers import DBSIG2
-
-raise "This data driver has not been upgraded to the new format."
-
-
-try:
-  import sapdbapi as SIG2api
-except ImportError, message:
-  tmsg = u_("Driver not installed: sapdbapi for SAP-DB 7.x \n[%s]") % message
-  raise GConnections.AdapterNotInstalled, tmsg
-
-class SAP_RecordSet(DBSIG2.RecordSet):
-  pass
-
-
-class SAP_ResultSet(DBSIG2.ResultSet):
-  def __init__(self, dataObject, cursor=None, defaultValues={}, 
masterRecordSet=None):
-    DBSIG2.ResultSet.__init__(self, dataObject, \
-            cursor, defaultValues, masterRecordSet)
-    self._recordSetClass = SAP_RecordSet
-
-
-
-class SAP_DataObject(DBSIG2.DataObject):
-  def __init__(self):
-    DBSIG2.DataObject.__init__(self)
-    self._DatabaseError = SIG2api.DatabaseError
-    self._resultSetClass = SAP_ResultSet
-
-
-  def connect(self, connectData={}):
-    GDebug.printMesg(1,"SAP database driver initializing")
-    try:
-      options = {'autocommit': 'off'}
-      for gnueName, sapdbName in [('sqlmode', 'sqlmode'),
-                                  ('timeout', 'timeout'),
-                                  ('isolation', 'isolation'),
-                                  ('sqlsubmode', 'component')]:
-          if connectData.has_key (gnueName):
-              options [sapdbName] = connectData [gnueName]
-      self._dataConnection = apply (SIG2api.connect,
-        (connectData['_username'], connectData['_password'],
-        connectData['dbname'], connectData.get ('host', '')),
-        options)
-      #self._dataConnection = SIG2api.connect( \
-      #             user=connectData['_username'], \
-      #             password=connectData['_password'], \
-      #             database=connectData['dbname'], \
-      #             host=connectData.get ('host', ''), \
-      #             autocommit="off")
-    except self._DatabaseError, value:
-      raise GDataObjects.LoginError, value
-
-    self._postConnect()
-
-  def _postConnect(self):
-    self.triggerExtensions = TriggerExtensions(self._dataConnection)
-
-
-  #
-  # Schema (metadata) functions
-  #
-
-  # Return a list of the types of Schema objects this driver provides
-  def getSchemaTypes(self):
-    return [ ('table',    _('Tables'),1),
-             ('view',     _('Views'), 1),
-             ('synonym',  _('Synonyms'),1),
-             ('result',   _('Result Table'),1) ]
-
-
-  # Return a list of Schema objects
-  def getSchemaList(self, type=None):
-
-    where_user = ""
-    if type == None:
-      where_type = "where TYPE <> 'SYSTEM' and TYPE <> 'SYNONYM' "
-    else:
-      where_type = "where TYPE='%s'" % string.upper(type)
-
-
-    statement = \
-      "select owner||'.'||tablename||'.'||type, " + \
-        "owner||'.'||tablename table_name, " + \
-        "type table_type " + \
-        "from domain.tables %s" \
-              % (where_type) + \
-          "order by tablename "
-
-    GDebug.printMesg(5,statement)
-
-    cursor = self._dataConnection.cursor()
-    cursor.execute(statement)
-
-    list = []
-    for rs in cursor.fetchall():
-      list.append(GDataObjects.Schema(attrs={'id':rs[0], 'name':rs[1],
-                         'type':string.lower(rs[2])},
-                         getChildSchema=self.__getFieldSchema))
-
-    cursor.close()
-    return list
-
-
-  # Find a schema object with specified name
-  def getSchemaByName(self, name, type=None):
-
-    where_user = ""
-    parts = string.split(string.upper(name),'.')
-    name = parts[-1]
-    if len(parts) > 1:
-      schema = " and owner='%s'" % parts[-2]
-    else:
-      schema = ""
-
-    statement = \
-      "select owner||'.'||tablename||'.'||type, " + \
-        "owner||'.'||tablename table_name, " + \
-        "type table_type, " + \
-        "owner, tablename " + \
-        "from domain.tables where tablename='%s'%s" \
-              % (name, schema) + \
-          "order by tablename "
-
-    GDebug.printMesg(5,statement)
-
-    cursor = self._dataConnection.cursor()
-    cursor.execute(statement)
-
-    list = []
-    for rs in cursor.fetchall():
-      list.append(GDataObjects.Schema(attrs={'id':string.lower(rs[0]), 
'name':rs[1],
-                         'type':rs[2], 'sapdbId': (rs [3], rs [4])},
-                         getChildSchema=self.__getFieldSchema))
-
-    cursor.close()
-
-    try:
-      return list[0]
-    except:
-      return None
-
-
-
-  # Get fields for a table
-  def __getFieldSchema(self, parent):
-
-    # TODO: This does not support user-defined datatypes...
-    # TODO: it will always report such as TEXT-like fields.
-
-    schema, name, type = string.split(parent.id,'.')
-    owner, basename = parent.sapdbId
-    cursor = self._dataConnection.cursor()
-
-#    if type == 'synonym':
-#      statement = "select base_tabschema, base_tabname " + \
-#                  "from syscat.tables " + \
-#                  "where tabschema = '%s' and tabname='%s'" % (schema, name)
-#
-#      GDebug.printMesg(5,statement)
-#
-#      cursor.execute(statement)
-#      rs = cursor.fetchone()
-#      schema, name = rs
-
-    statement = \
-       "select owner||'.'||tablename||'.'||columnname, " + \
-       "columnname, datatype, 'Y', len, dec " + \
-       "from domain.columns " + \
-       "where owner = '%s' and tablename = '%s' " % (owner, basename) + \
-       'order by "POS"'
-
-    GDebug.printMesg(5,statement)
-
-    cursor.execute(statement)
-
-    list = []
-    for rs in cursor.fetchall():
-
-      attrs={'id': rs[0], 'name': rs[1],
-             'type':'field', 'nativetype': rs[2],
-             'required': 'N'}
-
-      if rs[2] in ('BOOLEAN','FIXED','FLOAT','INTEGER','LONG','SMALLINT'):
-        attrs['precision'] = rs[5]
-        attrs['datatype'] = 'number'
-      elif rs[2] in ('DATE','TIME','TIMESTAMP'):
-        attrs['datatype'] = 'date'
-      else:
-        attrs['datatype'] = 'text'
-
-      if rs[5] != 0:
-        attrs['length'] = rs[4]
-
-      list.append(GDataObjects.Schema(attrs=attrs))
-
-    cursor.close()
-    return tuple(list)
-
-
-class SAP_DataObject_Object(SAP_DataObject, \
-      DBSIG2.DataObject_Object):
-
-  def __init__(self):
-    SAP_DataObject.__init__(self)
-
-  def _buildQuery(self, conditions={},forDetail=None,additionalSQL=""):
-    return DBSIG2.DataObject_Object._buildQuery(self, 
conditions,forDetail,additionalSQL)
-
-
-class SAP_DataObject_SQL(SAP_DataObject, \
-      DBSIG2.DataObject_SQL):
-  def __init__(self):
-    # Call DBSIG init first because SAP_DataObject needs to overwrite
-    # some of its values
-    DBSIG2.DataObject_SQL.__init__(self)
-    SAP_DataObject.__init__(self)
-
-  def _buildQuery(self, conditions={}):
-    return DBSIG2.DataObject_SQL._buildQuery(self, conditions)
-
-
-#
-#  Extensions to Trigger Namespaces
-#
-class TriggerExtensions:
-
-  def __init__(self, connection):
-    self.__connection = connection
-
-
-
-
-
-######################################
-#
-#  The following hashes describe
-#  this driver's characteristings.
-#
-######################################
-
-#
-#  All datasource "types" and corresponding DataObject class
-#
-supportedDataObjects = {
-  'object': SAP_DataObject_Object,
-  'sql':    SAP_DataObject_SQL
-}
-
-def createConnection (conn, **overrides):
-    from gnue.common.datasources.GConnections import GConnections
-    connections = GConnections (r'D:\Python22\etc\connections.conf')
-    parameters = connections.getConnectionParameters (conn).copy ()
-    dataObject = connections.getDataObject (conn, 'object')
-    parameters.update (overrides)
-    dataObject.connect (parameters)
-    return dataObject
-
-def testConnection ():
-    conn, user, pwd = sys.argv [1:4]
-    connection = createConnection (conn, _username = user, _password = pwd)
-    connection.getSchemaList ()
-
-if __name__ == "__main__":
-    testConnection ()

Deleted: trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/ResultSet.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/ResultSet.py  
2004-11-10 11:27:51 UTC (rev 6669)
+++ trunk/gnue-common/src/datasources/drivers/sapdb/sapdb/ResultSet.py  
2004-11-11 11:15:39 UTC (rev 6670)
@@ -1,321 +0,0 @@
-#
-# This file is part of GNU Enterprise.
-#
-# GNU Enterprise is free software; you can redistribute it
-# and/or modify it under the terms of the GNU General Public
-# License as published by the Free Software Foundation; either
-# version 2, or (at your option) any later version.
-#
-# GNU Enterprise is distributed in the hope that it will be
-# useful, but WITHOUT ANY WARRANTY; without even the implied
-# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
-# PURPOSE. See the GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public
-# License along with program; see the file COPYING. If not,
-# write to the Free Software Foundation, Inc., 59 Temple Place
-# - Suite 330, Boston, MA 02111-1307, USA.
-#
-# Copyright 2000-2004 Free Software Foundation
-#
-# FILE:
-# sapdb/DBdriver.py
-#
-# DESCRIPTION:
-# Driver to provide access to data via SAP's SAP-DB/Python Driver
-# Requires SAP-DB (http://www.sapdb.org/)
-#
-# NOTES:
-#
-#   Supported attributes (via connections.conf or <database> tag)
-#
-#     host=      This is the SAP-DB host for your connection (optional)
-#     dbname=    This is the SAP-DB database to use (required)
-#     timeout=   Command timeout in seconds (optional)
-#     isolation= Isolation level (options)
-#     sqlmode=   INTERNAl or ORACLE (optional)
-#     sqlsubmode= ODBC or empty (optional)
-#
-
-_exampleConfig = """
-# This connection uses the SAP DB  driver
-# We will be connecting to the SAP DB server on
-# "localhost" to a database called "TST".
-[sapdb]
-comment = XYZ Development Database
-provider = sapdb
-dbname = TST
-# host = localhost   # (optional)
-# sqlmode = INTERNAL # (default) or ORACLE
-# sqlsubmode = ODBC  # (for compatibility with the SAP DB ODBC driver)
-# timeout = 900      # (command timeout in seconds)
-# isolation = 1      # 0, 1 (default), 10, 15, 2, 20, 3, 30
-"""
-#### THIS IS AN UNTESTED DRIVER ####
-####      Any volunteers?       ####
-
-import string
-from string import lower
-import sys
-from gnue.common.datasources import GDataObjects, GConditions, GConnections
-from gnue.common.apps import GDebug
-from gnue.common.datasources.drivers import DBSIG2
-
-raise "This data driver has not been upgraded to the new format."
-
-import sapdbapi as SIG2api
-
-class SAP_RecordSet(DBSIG2.RecordSet):
-  pass
-
-
-class SAP_ResultSet(DBSIG2.ResultSet):
-  def __init__(self, dataObject, cursor=None, defaultValues={}, 
masterRecordSet=None):
-    DBSIG2.ResultSet.__init__(self, dataObject, \
-            cursor, defaultValues, masterRecordSet)
-    self._recordSetClass = SAP_RecordSet
-
-
-
-class SAP_DataObject(DBSIG2.DataObject):
-  def __init__(self):
-    DBSIG2.DataObject.__init__(self)
-    self._DatabaseError = SIG2api.DatabaseError
-    self._resultSetClass = SAP_ResultSet
-
-
-  def connect(self, connectData={}):
-    GDebug.printMesg(1,"SAP database driver initializing")
-    try:
-      options = {'autocommit': 'off'}
-      for gnueName, sapdbName in [('sqlmode', 'sqlmode'),
-                                  ('timeout', 'timeout'),
-                                  ('isolation', 'isolation'),
-                                  ('sqlsubmode', 'component')]:
-          if connectData.has_key (gnueName):
-              options [sapdbName] = connectData [gnueName]
-      self._dataConnection = apply (SIG2api.connect,
-        (connectData['_username'], connectData['_password'],
-        connectData['dbname'], connectData.get ('host', '')),
-        options)
-      #self._dataConnection = SIG2api.connect( \
-      #             user=connectData['_username'], \
-      #             password=connectData['_password'], \
-      #             database=connectData['dbname'], \
-      #             host=connectData.get ('host', ''), \
-      #             autocommit="off")
-    except self._DatabaseError, value:
-      raise GDataObjects.LoginError, value
-
-    self._postConnect()
-
-  def _postConnect(self):
-    self.triggerExtensions = TriggerExtensions(self._dataConnection)
-
-
-  #
-  # Schema (metadata) functions
-  #
-
-  # Return a list of the types of Schema objects this driver provides
-  def getSchemaTypes(self):
-    return [ ('table',    _('Tables'),1),
-             ('view',     _('Views'), 1),
-             ('synonym',  _('Synonyms'),1),
-             ('result',   _('Result Table'),1) ]
-
-
-  # Return a list of Schema objects
-  def getSchemaList(self, type=None):
-
-    where_user = ""
-    if type == None:
-      where_type = "where TYPE <> 'SYSTEM' and TYPE <> 'SYNONYM' "
-    else:
-      where_type = "where TYPE='%s'" % string.upper(type)
-
-
-    statement = \
-      "select owner||'.'||tablename||'.'||type, " + \
-        "owner||'.'||tablename table_name, " + \
-        "type table_type " + \
-        "from domain.tables %s" \
-              % (where_type) + \
-          "order by tablename "
-
-    GDebug.printMesg(5,statement)
-
-    cursor = self._dataConnection.cursor()
-    cursor.execute(statement)
-
-    list = []
-    for rs in cursor.fetchall():
-      list.append(GDataObjects.Schema(attrs={'id':rs[0], 'name':rs[1],
-                         'type':string.lower(rs[2])},
-                         getChildSchema=self.__getFieldSchema))
-
-    cursor.close()
-    return list
-
-
-  # Find a schema object with specified name
-  def getSchemaByName(self, name, type=None):
-
-    where_user = ""
-    parts = string.split(string.upper(name),'.')
-    name = parts[-1]
-    if len(parts) > 1:
-      schema = " and owner='%s'" % parts[-2]
-    else:
-      schema = ""
-
-    statement = \
-      "select owner||'.'||tablename||'.'||type, " + \
-        "owner||'.'||tablename table_name, " + \
-        "type table_type, " + \
-        "owner, tablename " + \
-        "from domain.tables where tablename='%s'%s" \
-              % (name, schema) + \
-          "order by tablename "
-
-    GDebug.printMesg(5,statement)
-
-    cursor = self._dataConnection.cursor()
-    cursor.execute(statement)
-
-    list = []
-    for rs in cursor.fetchall():
-      list.append(GDataObjects.Schema(attrs={'id':string.lower(rs[0]), 
'name':rs[1],
-                         'type':rs[2], 'sapdbId': (rs [3], rs [4])},
-                         getChildSchema=self.__getFieldSchema))
-
-    cursor.close()
-
-    try:
-      return list[0]
-    except:
-      return None
-
-
-
-  # Get fields for a table
-  def __getFieldSchema(self, parent):
-
-    # TODO: This does not support user-defined datatypes...
-    # TODO: it will always report such as TEXT-like fields.
-
-    schema, name, type = string.split(parent.id,'.')
-    owner, basename = parent.sapdbId
-    cursor = self._dataConnection.cursor()
-
-#    if type == 'synonym':
-#      statement = "select base_tabschema, base_tabname " + \
-#                  "from syscat.tables " + \
-#                  "where tabschema = '%s' and tabname='%s'" % (schema, name)
-#
-#      GDebug.printMesg(5,statement)
-#
-#      cursor.execute(statement)
-#      rs = cursor.fetchone()
-#      schema, name = rs
-
-    statement = \
-       "select owner||'.'||tablename||'.'||columnname, " + \
-       "columnname, datatype, 'Y', len, dec " + \
-       "from domain.columns " + \
-       "where owner = '%s' and tablename = '%s' " % (owner, basename) + \
-       'order by "POS"'
-
-    GDebug.printMesg(5,statement)
-
-    cursor.execute(statement)
-
-    list = []
-    for rs in cursor.fetchall():
-
-      attrs={'id': rs[0], 'name': rs[1],
-             'type':'field', 'nativetype': rs[2],
-             'required': 'N'}
-
-      if rs[2] in ('BOOLEAN','FIXED','FLOAT','INTEGER','LONG','SMALLINT'):
-        attrs['precision'] = rs[5]
-        attrs['datatype'] = 'number'
-      elif rs[2] in ('DATE','TIME','TIMESTAMP'):
-        attrs['datatype'] = 'date'
-      else:
-        attrs['datatype'] = 'text'
-
-      if rs[5] != 0:
-        attrs['length'] = rs[4]
-
-      list.append(GDataObjects.Schema(attrs=attrs))
-
-    cursor.close()
-    return tuple(list)
-
-
-class SAP_DataObject_Object(SAP_DataObject, \
-      DBSIG2.DataObject_Object):
-
-  def __init__(self):
-    SAP_DataObject.__init__(self)
-
-  def _buildQuery(self, conditions={},forDetail=None,additionalSQL=""):
-    return DBSIG2.DataObject_Object._buildQuery(self, 
conditions,forDetail,additionalSQL)
-
-
-class SAP_DataObject_SQL(SAP_DataObject, \
-      DBSIG2.DataObject_SQL):
-  def __init__(self):
-    # Call DBSIG init first because SAP_DataObject needs to overwrite
-    # some of its values
-    DBSIG2.DataObject_SQL.__init__(self)
-    SAP_DataObject.__init__(self)
-
-  def _buildQuery(self, conditions={}):
-    return DBSIG2.DataObject_SQL._buildQuery(self, conditions)
-
-
-#
-#  Extensions to Trigger Namespaces
-#
-class TriggerExtensions:
-
-  def __init__(self, connection):
-    self.__connection = connection
-
-
-
-
-
-######################################
-#
-#  The following hashes describe
-#  this driver's characteristings.
-#
-######################################
-
-#
-#  All datasource "types" and corresponding DataObject class
-#
-supportedDataObjects = {
-  'object': SAP_DataObject_Object,
-  'sql':    SAP_DataObject_SQL
-}
-
-def createConnection (conn, **overrides):
-    from gnue.common.datasources.GConnections import GConnections
-    connections = GConnections (r'D:\Python22\etc\connections.conf')
-    parameters = connections.getConnectionParameters (conn).copy ()
-    dataObject = connections.getDataObject (conn, 'object')
-    parameters.update (overrides)
-    dataObject.connect (parameters)
-    return dataObject
-
-def testConnection ():
-    conn, user, pwd = sys.argv [1:4]
-    connection = createConnection (conn, _username = user, _password = pwd)
-    connection.getSchemaList ()
-
-if __name__ == "__main__":
-    testConnection ()





reply via email to

[Prev in Thread] Current Thread [Next in Thread]