[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
r5933 - in trunk/gnue-common/src/datasources/drivers: postgresql/psycopg
From: |
johannes |
Subject: |
r5933 - in trunk/gnue-common/src/datasources/drivers: postgresql/psycopg sqlite/Schema/Discovery sqlite/sqlite |
Date: |
Wed, 7 Jul 2004 17:14:13 -0500 (CDT) |
Author: johannes
Date: 2004-07-02 09:40:44 -0500 (Fri, 02 Jul 2004)
New Revision: 5933
Modified:
trunk/gnue-common/src/datasources/drivers/postgresql/psycopg/Driver.py
trunk/gnue-common/src/datasources/drivers/sqlite/Schema/Discovery/Introspection.py
trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/Connection.py
trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/DataObject.py
trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/Info.py
trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/RecordSet.py
trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/ResultSet.py
trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/__init__.py
Log:
Reactivated the sqlite driver, fixed sqlite introspection
Modified: trunk/gnue-common/src/datasources/drivers/postgresql/psycopg/Driver.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/postgresql/psycopg/Driver.py
2004-07-01 09:38:43 UTC (rev 5932)
+++ trunk/gnue-common/src/datasources/drivers/postgresql/psycopg/Driver.py
2004-07-02 14:40:44 UTC (rev 5933)
@@ -38,7 +38,7 @@
except:
raise GConnections.DependencyError, ('psycopg', None)
-print dir (psycopg)
+#print dir (psycopg)
class Connection(Base.Connection):
_driver = psycopg
# _DatabaseError = (psycopg.DatabaseError, psycopg.Error,
psycopg.ProgrammingError)
Modified:
trunk/gnue-common/src/datasources/drivers/sqlite/Schema/Discovery/Introspection.py
===================================================================
---
trunk/gnue-common/src/datasources/drivers/sqlite/Schema/Discovery/Introspection.py
2004-07-01 09:38:43 UTC (rev 5932)
+++
trunk/gnue-common/src/datasources/drivers/sqlite/Schema/Discovery/Introspection.py
2004-07-02 14:40:44 UTC (rev 5933)
@@ -23,168 +23,137 @@
#
# DESCRIPTION:
#
-# NOTES:
-#
+# $Id$
__all__ = ['Introspection']
import string
-from string import lower, join, split
-import sys
+import re
-from gnue.common.apps import GDebug, GConfig
-from gnue.common.apps import GDebug, GConfig
from gnue.common.datasources import GIntrospection
-class Introspection(GIntrospection.Introspection):
+class Introspection (GIntrospection.Introspection):
# list of the types of Schema objects this driver provides
- types =[ ('view',_('Views'),1),
- ('table',_('Tables'),1) ]
+ types = [ ('view', _('Views'), True), ('table', _('Tables'), True) ]
- #
- # 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
+ _REPCOMMAS = re.compile ('\(\s*(\d+)\s*,\s*(\d+)\s*\)')
+ _ALIGN = re.compile ('\s*\(\s*(.*?)\s*\)')
+ _LEN_SCALE = re.compile ('^\s*(\w+)\s*\((\d+)[;]{0,1}(\d*)\)\s*')
+ _TEXTTYPE = re.compile ('.*(BLOB|CHAR|CLOB|TEXT){1}.*')
+ _BLANKS = re.compile ('\s+')
+ _NOTNULL = re.compile ('(.*)(NOT NULL)(.*)', re.IGNORECASE)
+ _CONSTRAINTS = re.compile ('.*?((UNIQUE|CHECK|PRIMARY KEY)\s*\(.*?\)).*', \
+ re.IGNORECASE)
+ # ---------------------------------------------------------------------------
+ # Get a schema object matching name and type
+ # ---------------------------------------------------------------------------
- # TODO: Merge into find()
- # Return a list of Schema objects
- def getSchemaList(self, type=None):
+ def find (self, name = None, type = None):
+ """
+ """
- if type!=None:
- where=" WHERE type='%s'" % type
+ result = []
+ condition = ""
+
+ if name is None:
+ if type is not None:
+ condition = "WHERE type = '%s'" % type.lower ()
else:
- where=""
+ condition = "WHERE name = '%s'" % name
- statement = "SELECT type,name,tbl_name,sql FROM master "+\
- where+" UNION ALL "+\
- "SELECT type,name,tbl_name,sql FROM temp_master "+\
- where+" ORDER BY name;"
+ cmd = "SELECT type, name, sql FROM sqlite_master %s" % condition
+ cursor = self._connection.makecursor (cmd)
- cursor = self._connection.native.cursor()
- GDebug.printMesg(1,"** Executing: %s **" % statement)
- cursor.execute(statement)
+ try:
+ for rs in cursor.fetchall ():
+ if not rs [0] in [tp [0] for tp in self.types]:
+ continue
- list = []
- for rs in cursor.fetchall():
- if rs[0] in ('table','view'):
- list.append(GIntrospection.Schema(attrs={'id':rs[1], 'name':rs[1], \
- 'type':rs[0],},
- getChildSchema=self.__getFieldSchema))
+ attrs = {'id' : rs [1],
+ 'name': rs [1],
+ 'type': rs [0],
+ 'sql' : rs [2]}
+ result.append ( \
+ GIntrospection.Schema (attrs, getChildSchema = self._getChildSchema))
- cursor.close()
- print list
- return list
+ finally:
+ cursor.close ()
+ return len (result) and result or None
- # Find a schema object with specified name
- def getSchemaByName(self, name, type=None):
- if type!=None:
- where=" AND type='%s'" % type
- else:
- where=""
+ # ---------------------------------------------------------------------------
+ # Get all fields from a table / view
+ # ---------------------------------------------------------------------------
- statement = ("SELECT type,name,tbl_name,sql FROM master "+\
- "WHERE name='%s'"+where+" UNION ALL "+\
- "SELECT type,name,tbl_name,sql FROM temp_master "+\
- "WHERE name='%s' "+where+" ORDER BY name;") % (name,name)
+ def _getChildSchema (self, parent):
+ result = []
- cursor = self._connection.native.cursor()
- GDebug.printMesg(1,"** Executing: %s **" % statement)
- cursor.execute(statement)
+ cmd = "SELECT sql FROM sqlite_master WHERE type = '%s' AND name = '%s'" \
+ % (parent.type, parent.name)
- rs = cursor.fetchone()
- if rs and rs[0] in ('table','view'):
- schema = GIntrospection.Schema(attrs={'id':rs[1], 'name':rs[1], \
- 'type':rs[0],},
- getChildSchema=self.__getFieldSchema)
- else:
- schema = None
+ cursor = self._connection.makecursor (cmd)
- cursor.close()
- return schema
+ try:
+ for rs in cursor.fetchall ():
+ code = string.join (rs [0].splitlines (), ' ')
+ code = code [string.find (code, '(') + 1:string.rfind (code, ')')]
- # Get fields for a table
- def __getFieldSchema(self, parent):
+ code = self._BLANKS.sub (' ', code)
+ code = self._REPCOMMAS.sub (r'(\1;\2)', code)
+ code = self._ALIGN.sub (r' (\1)', code)
- if parent.type=='view':
- print "Views are not supported at the moment"
- return None
+ # we currently skip all constraints (primary key, unique, check)
+ cma = self._CONSTRAINTS.match (code)
+ while cma is not None:
+ constraint = cma.groups () [0]
+ code = string.replace (code, constraint, '')
+ cma = self._CONSTRAINTS.match (code)
- statement = ("SELECT type,name,tbl_name,sql FROM master "+\
- "WHERE type='%s' and name='%s' UNION ALL "+\
- "SELECT type,name,tbl_name,sql FROM temp_master "+\
- "WHERE type='%s' "+\
- "and name='%s' ORDER BY name;") % (parent.type,parent.id,\
- parent.type,parent.id)
+ for item in [i.strip () for i in code.split (',')]:
+ if not len (item):
+ continue
- cursor = self._connection.native.cursor()
- GDebug.printMesg(1,"** Executing: %s **" % statement)
- cursor.execute(statement)
- columns = cursor.description
+ parts = item.split ()
+ attrs = {'id' : "%s.%s" % (parent.name, parts [0]),
+ 'name': parts [0],
+ 'type': 'field'}
- # Because sqlite don't store column definitions, but computes it
- # every time anew from the 'create table' statement, we have to
- # parse that statement to get the data
+ datatype = string.join (parts [1:], ' ')
+ lsmatch = self._LEN_SCALE.match (datatype)
+ if lsmatch is not None:
+ (typename, length, scale) = lsmatch.groups ()
+ else:
+ typename = parts [1]
+ length = 0
+ scale = 0
- # get sql definition of table
- rs = cursor.fetchone()
- cursor.close()
- if rs:
- sql=rs[3]
- else:
- return None
+ nativetype = typename
+ add = []
+ if length: add.append (length)
+ if scale : add.append (scale)
+ if len (add):
+ nativetype += "(%s)" % string.join (add, ",")
- # parse the sql definition
- GDebug.printMesg(3,"** Table definition: %s **" % sql)
+ attrs ['length'] = length
+ attrs ['precision'] = scale or 0
+ attrs ['nativetype'] = nativetype
+ attrs ['required'] = self._NOTNULL.match (item) is not None
- sql=sql[find(sql,'(')+1:rfind(sql,')')]
- fields = split(sql,',')
- list = []
- for field in fields:
+ if self._TEXTTYPE.match (typename.upper ()):
+ attrs ['datatype'] = 'text'
+ elif typename.lower () in ['date', 'datetime']:
+ attrs ['datatype'] = 'date'
+ else:
+ attrs ['datatype'] = 'number'
- fls=split(strip(field),' ',2)
+ print "ATTR:", attrs
+ result.append (GIntrospection.Schema (attrs))
- if not fls[0] in ('Constraint','Primary'):
-
- try:
- nativetype= fls[1][:find(fls[1],'(')]
+ finally:
+ cursor.close ()
- size=int(fls[1][find(fls[1],'(')+1:-1])
- except:
- nativetype = fls[1]
- size=None
-
- attrs={'id': "%s.%s" % (parent.id, fls[0]), 'name': fls[0],
- 'type':'field', 'nativetype': nativetype,
- 'required':fls[2]=="NOT NULL"}
-
- if size!=None:
- attrs['length'] = size
-
- if nativetype in ('int','integer','bigint','mediumint',
- 'smallint','tinyint','float','real',
- 'double','decimal'):
- attrs['datatype']='number'
- elif nativetype[0] in ('date','time','timestamp','datetime'):
- attrs['datatype']='date'
- else:
- attrs['datatype']='text'
-
- list.append(GIntrospection.Schema(attrs=attrs))
-
- return list
-
+ return result
Property changes on:
trunk/gnue-common/src/datasources/drivers/sqlite/Schema/Discovery/Introspection.py
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/Connection.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/Connection.py
2004-07-01 09:38:43 UTC (rev 5932)
+++ trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/Connection.py
2004-07-02 14:40:44 UTC (rev 5933)
@@ -31,6 +31,7 @@
#
# dbname= This is the SQLite database to use (required)
#
+# $Id: $
__all__ = ['Connection']
@@ -39,14 +40,15 @@
#### ATTRIBUTES, PLEASE UPDATE info.py ####
#### ####
-from string import lower,find,rfind,split,strip
-import sys
-from gnue.common.datasources import GDataObjects, GConditions, GConnections
from gnue.common.apps import GDebug
+from gnue.common.datasources import Exceptions
from gnue.common.datasources.drivers import DBSIG2
+from DataObject import *
+
try:
import sqlite as SIG2api
+
except ImportError:
raise GConnections.DependencyError, ('SQLitedbapi', None)
@@ -57,24 +59,41 @@
#
# GConnection object for PostgreSQL-based drivers
#
-class Connection(DBSIG2.Connection):
+class Connection (DBSIG2.Connection):
- _driver = SIG2api
- _DatabaseError = SIG2api.DatabaseError
+ _driver = SIG2api
+ _DatabaseError = SIG2api.DatabaseError
defaultBehavior = Introspection
supportedDataObjects = {
'object': DataObject_Object,
'sql': DataObject_SQL
}
- def connect(self, connectData={}):
+
+ # ---------------------------------------------------------------------------
+ # Connect to a given database according to the connectData dictionary
+ # ---------------------------------------------------------------------------
+
+ def connect (self, connectData):
+ """
+ """
GDebug.printMesg(1,"SQLite database driver initializing")
+
+ if not hasattr (self, '_DatabaseError'):
+ try:
+ self._DatabaseError = self._driver.Error
+ except:
+ self._DatabaseError = self._driver.DatabaseError
+
try:
- self.native = SIG2api.connect( \
- db=connectData['dbname'], \
- mode=077 )
+ self.native = SIG2api.connect (db = connectData['dbname'],
+ mode = 077,
+ encoding = self._encoding)
+
except self._DatabaseError, value:
- raise GDataObjects.LoginError, value
+ GDebug.printMesg (1, "Exception %s" % value)
+ raise Exceptions.LoginError, u_("The SQLite driver returned the "
+ "following error:\n\t%s") % value
# Return a list of necessary login fields (e.g., user/pass).
Property changes on:
trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/Connection.py
___________________________________________________________________
Name: svn:keywords
+ +Id
Modified: trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/DataObject.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/DataObject.py
2004-07-01 09:38:43 UTC (rev 5932)
+++ trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/DataObject.py
2004-07-02 14:40:44 UTC (rev 5933)
@@ -25,255 +25,19 @@
# Driver to provide access to data via SQLite's Python Driver.
# Requires PySQLite (http://pysqlite.sf.net/)
#
-# NOTES:
-#
-# Supported attributes (via connections.conf or <database> tag)
-#
-# dbname= This is the SQLite database to use (required)
-#
+# $Id: $
+__all__ = ['DataObject_SQL', 'DataObject_Object']
-from string import lower,find,rfind,split,strip
-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:
+ pass
-try:
- import sqlite as SIG2api
-except ImportError, message:
- tmsg = _("Driver not installed: SQLitedbapi for SQLite 7.x \n[%s]") % message
- raise GConnections.AdapterNotInstalled, tmsg
+class DataObject_SQL (_Base, DBSIG2.DataObject_SQL):
+ pass
-
-class SQLite_RecordSet(DBSIG2.RecordSet):
+class DataObject_Object (_Base, DBSIG2.DataObject_Object):
pass
-
-class SQLite_ResultSet(DBSIG2.ResultSet):
- def __init__(self, dataObject, cursor=None, defaultValues={},
masterRecordSet=None):
- DBSIG2.ResultSet.__init__(self, dataObject, \
- cursor, defaultValues, masterRecordSet)
- self._recordSetClass = SQLite_RecordSet
-
-
-
-class SQLite_DataObject(DBSIG2.DataObject):
- def __init__(self):
- DBSIG2.DataObject.__init__(self)
- self._DatabaseError = SIG2api.DatabaseError
- self._resultSetClass = SQLite_ResultSet
-
-
- def connect(self, connectData={}):
- GDebug.printMesg(1,"SQLite database driver initializing")
- try:
- self._dataConnection = SIG2api.connect( \
- db=connectData['dbname'], \
- mode=077 )
- except self._DatabaseError, value:
- raise GDataObjects.LoginError, value
-
- self._postConnect()
-
- def _postConnect(self):
- self.triggerExtensions = TriggerExtensions(self._dataConnection)
-
-
- # Return a list of necessary login fields (e.g., user/pass).
- # Each list item is another list of ["field label", isPassword?]
- def getLoginFields(self):
- return []
-
- #
- # Schema (metadata) functions
- #
-
- # Return a list of the types of Schema objects this driver provides
- def getSchemaTypes(self):
- return [('view',_('Views'),1),
- ('table',_('Table'),1)]
-
- # Return a list of Schema objects
- def getSchemaList(self, type=None):
-
- if type!=None:
- where=" WHERE type='%s'" % type
- else:
- where=""
-
- statement = "SELECT type,name,tbl_name,sql FROM sqlite_master "+\
- where+" UNION ALL "+\
- "SELECT type,name,tbl_name,sql FROM sqlite_temp_master "+\
- where+" ORDER BY name;"
-
- cursor = self._dataConnection.cursor()
- GDebug.printMesg(1,"** Executing: %s **" % statement)
- cursor.execute(statement)
-
- list = []
- for rs in cursor.fetchall():
- if rs[0] in ('table','view'):
- list.append(GDataObjects.Schema(attrs={'id':rs[1], 'name':rs[1], \
- 'type':rs[0],},
- getChildSchema=self.__getFieldSchema))
-
- cursor.close()
- print list
- return list
-
-
- # Find a schema object with specified name
- def getSchemaByName(self, name, type=None):
-
- if type!=None:
- where=" AND type='%s'" % type
- else:
- where=""
-
- statement = ("SELECT type,name,tbl_name,sql FROM sqlite_master "+\
- "WHERE name='%s'"+where+" UNION ALL "+\
- "SELECT type,name,tbl_name,sql FROM sqlite_temp_master "+\
- "WHERE name='%s' "+where+" ORDER BY name;") % (name,name)
-
- cursor = self._dataConnection.cursor()
- GDebug.printMesg(1,"** Executing: %s **" % statement)
- cursor.execute(statement)
-
- rs = cursor.fetchone()
- if rs and rs[0] in ('table','view'):
- schema = GDataObjects.Schema(attrs={'id':rs[1], 'name':rs[1], \
- 'type':rs[0],},
- getChildSchema=self.__getFieldSchema)
- else:
- schema = None
-
- cursor.close()
- return schema
-
-
- # Get fields for a table
- def __getFieldSchema(self, parent):
-
- if parent.type=='view':
- print "Views are not supported at the moment"
- return None
-
- statement = ("SELECT type,name,tbl_name,sql FROM sqlite_master "+\
- "WHERE type='%s' and name='%s' UNION ALL "+\
- "SELECT type,name,tbl_name,sql FROM sqlite_temp_master "+\
- "WHERE type='%s' "+\
- "and name='%s' ORDER BY name;") % (parent.type,parent.id,\
- parent.type,parent.id)
-
- cursor = self._dataConnection.cursor()
- GDebug.printMesg(1,"** Executing: %s **" % statement)
- cursor.execute(statement)
- columns = cursor.description
-
- # Because sqlite don't store column definitions, but computes it
- # every time anew from the 'create table' statement, we have to
- # parse that statement to get the data
-
- # get sql definition of table
- rs = cursor.fetchone()
- cursor.close()
- if rs:
- sql=rs[3]
- else:
- return None
-
- # parse the sql definition
- GDebug.printMesg(3,"** Table definition: %s **" % sql)
-
- sql=sql[find(sql,'(')+1:rfind(sql,')')]
- fields = split(sql,',')
- list = []
- for field in fields:
-
- fls=split(strip(field),' ',2)
-
- if not fls[0] in ('Constraint','Primary'):
-
- try:
- nativetype= fls[1][:find(fls[1],'(')]
-
- size=int(fls[1][find(fls[1],'(')+1:-1])
- except:
- nativetype = fls[1]
- size=None
-
- attrs={'id': "%s.%s" % (parent.id, fls[0]), 'name': fls[0],
- 'type':'field', 'nativetype': nativetype,
- 'required':fls[2]=="NOT NULL"}
-
- if size!=None:
- attrs['length'] = size
-
- if nativetype in ('int','integer','bigint','mediumint',
- 'smallint','tinyint','float','real',
- 'double','decimal'):
- attrs['datatype']='number'
- elif nativetype[0] in ('date','time','timestamp','datetime'):
- attrs['datatype']='date'
- else:
- attrs['datatype']='text'
-
- list.append(GDataObjects.Schema(attrs=attrs))
-
- return list
-
-
-class SQLite_DataObject_Object(SQLite_DataObject, \
- DBSIG2.DataObject_Object):
-
- def __init__(self):
- SQLite_DataObject.__init__(self)
-
- def _buildQuery(self, conditions={},forDetail=None,additionalSQL=""):
- return DBSIG2.DataObject_Object._buildQuery(self, conditions,forDetail,
additionalSQL)
-
-
-class SQLite_DataObject_SQL(SQLite_DataObject, \
- DBSIG2.DataObject_SQL):
- def __init__(self):
- # Call DBSIG init first because SQLite_DataObject needs to overwrite
- # some of its values
- DBSIG2.DataObject_SQL.__init__(self)
- SQLite_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 datasouce "types" and corresponding DataObject class
-#
-supportedDataObjects = {
- 'object': SQLite_DataObject_Object,
- 'sql': SQLite_DataObject_SQL
-}
-
Property changes on:
trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/DataObject.py
___________________________________________________________________
Name: svn:keywords
+ +Id
Property changes on:
trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/Info.py
___________________________________________________________________
Name: svn:keywords
+ +Id
Modified: trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/RecordSet.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/RecordSet.py
2004-07-01 09:38:43 UTC (rev 5932)
+++ trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/RecordSet.py
2004-07-02 14:40:44 UTC (rev 5933)
@@ -25,255 +25,11 @@
# Driver to provide access to data via SQLite's Python Driver.
# Requires PySQLite (http://pysqlite.sf.net/)
#
-# NOTES:
-#
-# Supported attributes (via connections.conf or <database> tag)
-#
-# dbname= This is the SQLite database to use (required)
-#
+# $Id: $
-from string import lower,find,rfind,split,strip
-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 sqlite as SIG2api
-except ImportError, message:
- tmsg = _("Driver not installed: SQLitedbapi for SQLite 7.x \n[%s]") % message
- raise GConnections.AdapterNotInstalled, tmsg
-
-
-class SQLite_RecordSet(DBSIG2.RecordSet):
+class RecordSet (DBSIG2.RecordSet):
pass
-
-
-class SQLite_ResultSet(DBSIG2.ResultSet):
- def __init__(self, dataObject, cursor=None, defaultValues={},
masterRecordSet=None):
- DBSIG2.ResultSet.__init__(self, dataObject, \
- cursor, defaultValues, masterRecordSet)
- self._recordSetClass = SQLite_RecordSet
-
-
-
-class SQLite_DataObject(DBSIG2.DataObject):
- def __init__(self):
- DBSIG2.DataObject.__init__(self)
- self._DatabaseError = SIG2api.DatabaseError
- self._resultSetClass = SQLite_ResultSet
-
-
- def connect(self, connectData={}):
- GDebug.printMesg(1,"SQLite database driver initializing")
- try:
- self._dataConnection = SIG2api.connect( \
- db=connectData['dbname'], \
- mode=077 )
- except self._DatabaseError, value:
- raise GDataObjects.LoginError, value
-
- self._postConnect()
-
- def _postConnect(self):
- self.triggerExtensions = TriggerExtensions(self._dataConnection)
-
-
- # Return a list of necessary login fields (e.g., user/pass).
- # Each list item is another list of ["field label", isPassword?]
- def getLoginFields(self):
- return []
-
- #
- # Schema (metadata) functions
- #
-
- # Return a list of the types of Schema objects this driver provides
- def getSchemaTypes(self):
- return [('view',_('Views'),1),
- ('table',_('Table'),1)]
-
- # Return a list of Schema objects
- def getSchemaList(self, type=None):
-
- if type!=None:
- where=" WHERE type='%s'" % type
- else:
- where=""
-
- statement = "SELECT type,name,tbl_name,sql FROM sqlite_master "+\
- where+" UNION ALL "+\
- "SELECT type,name,tbl_name,sql FROM sqlite_temp_master "+\
- where+" ORDER BY name;"
-
- cursor = self._dataConnection.cursor()
- GDebug.printMesg(1,"** Executing: %s **" % statement)
- cursor.execute(statement)
-
- list = []
- for rs in cursor.fetchall():
- if rs[0] in ('table','view'):
- list.append(GDataObjects.Schema(attrs={'id':rs[1], 'name':rs[1], \
- 'type':rs[0],},
- getChildSchema=self.__getFieldSchema))
-
- cursor.close()
- print list
- return list
-
-
- # Find a schema object with specified name
- def getSchemaByName(self, name, type=None):
-
- if type!=None:
- where=" AND type='%s'" % type
- else:
- where=""
-
- statement = ("SELECT type,name,tbl_name,sql FROM sqlite_master "+\
- "WHERE name='%s'"+where+" UNION ALL "+\
- "SELECT type,name,tbl_name,sql FROM sqlite_temp_master "+\
- "WHERE name='%s' "+where+" ORDER BY name;") % (name,name)
-
- cursor = self._dataConnection.cursor()
- GDebug.printMesg(1,"** Executing: %s **" % statement)
- cursor.execute(statement)
-
- rs = cursor.fetchone()
- if rs and rs[0] in ('table','view'):
- schema = GDataObjects.Schema(attrs={'id':rs[1], 'name':rs[1], \
- 'type':rs[0],},
- getChildSchema=self.__getFieldSchema)
- else:
- schema = None
-
- cursor.close()
- return schema
-
-
- # Get fields for a table
- def __getFieldSchema(self, parent):
-
- if parent.type=='view':
- print "Views are not supported at the moment"
- return None
-
- statement = ("SELECT type,name,tbl_name,sql FROM sqlite_master "+\
- "WHERE type='%s' and name='%s' UNION ALL "+\
- "SELECT type,name,tbl_name,sql FROM sqlite_temp_master "+\
- "WHERE type='%s' "+\
- "and name='%s' ORDER BY name;") % (parent.type,parent.id,\
- parent.type,parent.id)
-
- cursor = self._dataConnection.cursor()
- GDebug.printMesg(1,"** Executing: %s **" % statement)
- cursor.execute(statement)
- columns = cursor.description
-
- # Because sqlite don't store column definitions, but computes it
- # every time anew from the 'create table' statement, we have to
- # parse that statement to get the data
-
- # get sql definition of table
- rs = cursor.fetchone()
- cursor.close()
- if rs:
- sql=rs[3]
- else:
- return None
-
- # parse the sql definition
- GDebug.printMesg(3,"** Table definition: %s **" % sql)
-
- sql=sql[find(sql,'(')+1:rfind(sql,')')]
- fields = split(sql,',')
- list = []
- for field in fields:
-
- fls=split(strip(field),' ',2)
-
- if not fls[0] in ('Constraint','Primary'):
-
- try:
- nativetype= fls[1][:find(fls[1],'(')]
-
- size=int(fls[1][find(fls[1],'(')+1:-1])
- except:
- nativetype = fls[1]
- size=None
-
- attrs={'id': "%s.%s" % (parent.id, fls[0]), 'name': fls[0],
- 'type':'field', 'nativetype': nativetype,
- 'required':fls[2]=="NOT NULL"}
-
- if size!=None:
- attrs['length'] = size
-
- if nativetype in ('int','integer','bigint','mediumint',
- 'smallint','tinyint','float','real',
- 'double','decimal'):
- attrs['datatype']='number'
- elif nativetype[0] in ('date','time','timestamp','datetime'):
- attrs['datatype']='date'
- else:
- attrs['datatype']='text'
-
- list.append(GDataObjects.Schema(attrs=attrs))
-
- return list
-
-
-class SQLite_DataObject_Object(SQLite_DataObject, \
- DBSIG2.DataObject_Object):
-
- def __init__(self):
- SQLite_DataObject.__init__(self)
-
- def _buildQuery(self, conditions={},forDetail=None,additionalSQL=""):
- return DBSIG2.DataObject_Object._buildQuery(self, conditions,forDetail,
additionalSQL)
-
-
-class SQLite_DataObject_SQL(SQLite_DataObject, \
- DBSIG2.DataObject_SQL):
- def __init__(self):
- # Call DBSIG init first because SQLite_DataObject needs to overwrite
- # some of its values
- DBSIG2.DataObject_SQL.__init__(self)
- SQLite_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 datasouce "types" and corresponding DataObject class
-#
-supportedDataObjects = {
- 'object': SQLite_DataObject_Object,
- 'sql': SQLite_DataObject_SQL
-}
-
Property changes on:
trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/RecordSet.py
___________________________________________________________________
Name: svn:keywords
+ +Id
Modified: trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/ResultSet.py
===================================================================
--- trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/ResultSet.py
2004-07-01 09:38:43 UTC (rev 5932)
+++ trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/ResultSet.py
2004-07-02 14:40:44 UTC (rev 5933)
@@ -25,255 +25,11 @@
# Driver to provide access to data via SQLite's Python Driver.
# Requires PySQLite (http://pysqlite.sf.net/)
#
-# NOTES:
-#
-# Supported attributes (via connections.conf or <database> tag)
-#
-# dbname= This is the SQLite database to use (required)
-#
+# $Id: $
-from string import lower,find,rfind,split,strip
-import sys
-from gnue.common.datasources import GDataObjects, GConditions, GConnections
-from gnue.common.apps import GDebug
from gnue.common.datasources.drivers import DBSIG2
+from RecordSet import RecordSet
-raise "This data driver has not been upgraded to the new format."
-
-
-try:
- import sqlite as SIG2api
-except ImportError, message:
- tmsg = _("Driver not installed: SQLitedbapi for SQLite 7.x \n[%s]") % message
- raise GConnections.AdapterNotInstalled, tmsg
-
-
-class SQLite_RecordSet(DBSIG2.RecordSet):
- pass
-
-
-class SQLite_ResultSet(DBSIG2.ResultSet):
- def __init__(self, dataObject, cursor=None, defaultValues={},
masterRecordSet=None):
- DBSIG2.ResultSet.__init__(self, dataObject, \
- cursor, defaultValues, masterRecordSet)
- self._recordSetClass = SQLite_RecordSet
-
-
-
-class SQLite_DataObject(DBSIG2.DataObject):
- def __init__(self):
- DBSIG2.DataObject.__init__(self)
- self._DatabaseError = SIG2api.DatabaseError
- self._resultSetClass = SQLite_ResultSet
-
-
- def connect(self, connectData={}):
- GDebug.printMesg(1,"SQLite database driver initializing")
- try:
- self._dataConnection = SIG2api.connect( \
- db=connectData['dbname'], \
- mode=077 )
- except self._DatabaseError, value:
- raise GDataObjects.LoginError, value
-
- self._postConnect()
-
- def _postConnect(self):
- self.triggerExtensions = TriggerExtensions(self._dataConnection)
-
-
- # Return a list of necessary login fields (e.g., user/pass).
- # Each list item is another list of ["field label", isPassword?]
- def getLoginFields(self):
- return []
-
- #
- # Schema (metadata) functions
- #
-
- # Return a list of the types of Schema objects this driver provides
- def getSchemaTypes(self):
- return [('view',_('Views'),1),
- ('table',_('Table'),1)]
-
- # Return a list of Schema objects
- def getSchemaList(self, type=None):
-
- if type!=None:
- where=" WHERE type='%s'" % type
- else:
- where=""
-
- statement = "SELECT type,name,tbl_name,sql FROM sqlite_master "+\
- where+" UNION ALL "+\
- "SELECT type,name,tbl_name,sql FROM sqlite_temp_master "+\
- where+" ORDER BY name;"
-
- cursor = self._dataConnection.cursor()
- GDebug.printMesg(1,"** Executing: %s **" % statement)
- cursor.execute(statement)
-
- list = []
- for rs in cursor.fetchall():
- if rs[0] in ('table','view'):
- list.append(GDataObjects.Schema(attrs={'id':rs[1], 'name':rs[1], \
- 'type':rs[0],},
- getChildSchema=self.__getFieldSchema))
-
- cursor.close()
- print list
- return list
-
-
- # Find a schema object with specified name
- def getSchemaByName(self, name, type=None):
-
- if type!=None:
- where=" AND type='%s'" % type
- else:
- where=""
-
- statement = ("SELECT type,name,tbl_name,sql FROM sqlite_master "+\
- "WHERE name='%s'"+where+" UNION ALL "+\
- "SELECT type,name,tbl_name,sql FROM sqlite_temp_master "+\
- "WHERE name='%s' "+where+" ORDER BY name;") % (name,name)
-
- cursor = self._dataConnection.cursor()
- GDebug.printMesg(1,"** Executing: %s **" % statement)
- cursor.execute(statement)
-
- rs = cursor.fetchone()
- if rs and rs[0] in ('table','view'):
- schema = GDataObjects.Schema(attrs={'id':rs[1], 'name':rs[1], \
- 'type':rs[0],},
- getChildSchema=self.__getFieldSchema)
- else:
- schema = None
-
- cursor.close()
- return schema
-
-
- # Get fields for a table
- def __getFieldSchema(self, parent):
-
- if parent.type=='view':
- print "Views are not supported at the moment"
- return None
-
- statement = ("SELECT type,name,tbl_name,sql FROM sqlite_master "+\
- "WHERE type='%s' and name='%s' UNION ALL "+\
- "SELECT type,name,tbl_name,sql FROM sqlite_temp_master "+\
- "WHERE type='%s' "+\
- "and name='%s' ORDER BY name;") % (parent.type,parent.id,\
- parent.type,parent.id)
-
- cursor = self._dataConnection.cursor()
- GDebug.printMesg(1,"** Executing: %s **" % statement)
- cursor.execute(statement)
- columns = cursor.description
-
- # Because sqlite don't store column definitions, but computes it
- # every time anew from the 'create table' statement, we have to
- # parse that statement to get the data
-
- # get sql definition of table
- rs = cursor.fetchone()
- cursor.close()
- if rs:
- sql=rs[3]
- else:
- return None
-
- # parse the sql definition
- GDebug.printMesg(3,"** Table definition: %s **" % sql)
-
- sql=sql[find(sql,'(')+1:rfind(sql,')')]
- fields = split(sql,',')
- list = []
- for field in fields:
-
- fls=split(strip(field),' ',2)
-
- if not fls[0] in ('Constraint','Primary'):
-
- try:
- nativetype= fls[1][:find(fls[1],'(')]
-
- size=int(fls[1][find(fls[1],'(')+1:-1])
- except:
- nativetype = fls[1]
- size=None
-
- attrs={'id': "%s.%s" % (parent.id, fls[0]), 'name': fls[0],
- 'type':'field', 'nativetype': nativetype,
- 'required':fls[2]=="NOT NULL"}
-
- if size!=None:
- attrs['length'] = size
-
- if nativetype in ('int','integer','bigint','mediumint',
- 'smallint','tinyint','float','real',
- 'double','decimal'):
- attrs['datatype']='number'
- elif nativetype[0] in ('date','time','timestamp','datetime'):
- attrs['datatype']='date'
- else:
- attrs['datatype']='text'
-
- list.append(GDataObjects.Schema(attrs=attrs))
-
- return list
-
-
-class SQLite_DataObject_Object(SQLite_DataObject, \
- DBSIG2.DataObject_Object):
-
- def __init__(self):
- SQLite_DataObject.__init__(self)
-
- def _buildQuery(self, conditions={},forDetail=None,additionalSQL=""):
- return DBSIG2.DataObject_Object._buildQuery(self, conditions,forDetail,
additionalSQL)
-
-
-class SQLite_DataObject_SQL(SQLite_DataObject, \
- DBSIG2.DataObject_SQL):
- def __init__(self):
- # Call DBSIG init first because SQLite_DataObject needs to overwrite
- # some of its values
- DBSIG2.DataObject_SQL.__init__(self)
- SQLite_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 datasouce "types" and corresponding DataObject class
-#
-supportedDataObjects = {
- 'object': SQLite_DataObject_Object,
- 'sql': SQLite_DataObject_SQL
-}
-
+class ResultSet (DBSIG2.ResultSet):
+ _recordSetClass = RecordSet
Property changes on:
trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/ResultSet.py
___________________________________________________________________
Name: svn:keywords
+ +Id
Property changes on:
trunk/gnue-common/src/datasources/drivers/sqlite/sqlite/__init__.py
___________________________________________________________________
Name: svn:keywords
+ +Id
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- r5933 - in trunk/gnue-common/src/datasources/drivers: postgresql/psycopg sqlite/Schema/Discovery sqlite/sqlite,
johannes <=