Update of /cvsroot/informixdb/zinformixda
In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv2000/zinformixda
Added Files:
CHANGES.txt COPYING.txt CREDITS.txt DA.py DABase.py
DEPENDENCIES.txt INSTALL.txt TODO.txt VERSION.txt
ZopePublicLicense.txt __init__.py db.py
Log Message:
initial source commit
--- NEW FILE: TODO.txt ---
Z Informix DA todo list
-----------------------
- Advanced error handling ( display warnings )
- Implement Scroll Cursors and Cursors with Hold
- Check Blob possible usage
- Add test units
- Release a Zope 3 Package version
--- NEW FILE: DABase.py ---
##############################################################################
#
# Copyright (c) 2004, 2005, 2006 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
##############################################################################
import Globals, Shared.DC.ZRDB.Connection, sys, string
from ExtensionClass import Base
import Acquisition
from db import table_icons, field_icons
from AccessControl import ClassSecurityInfo
import AccessControl.Permissions
__doc__ = '''Database Connection'''
__revision__ = '$Id: DABase.py,v 1.1 2006/10/14 02:43:40 olavosantos Exp $'
__version__ = string.split(__revision__)[2]
class Connection(Shared.DC.ZRDB.Connection.Connection):
_isAnSQLConnection = 1
security = ClassSecurityInfo()
manage_options = Shared.DC.ZRDB.Connection.Connection.manage_options + (
{ 'label':'Browse', 'action':'manage_browse' },
)
security.declareProtected(AccessControl.Permissions.view_management_screens, 'manage_browse')
manage_browse = Globals.HTMLFile('dtml/browse',globals())
def tpValues(self):
r = []
c = self._v_database_connection
try:
for d in c.tables(rdb=0):
try:
name = d['TABLE_NAME']
b = TableBrowser()
b.__name__ = name
b._d = d
b._c = c
b.icon = table_icons.get(d['TABLE_TYPE'],'text')
r.append(b)
except:
pass
finally: pass
return r
def __getitem__(self, name):
if name == 'tableNamed':
if not hasattr(self, '_v_tables'): self.tpValues()
return self._v_tables.__of__(self)
raise KeyError, name
Globals.InitializeClass(Connection)
class Browser(Base):
def __getattr__(self, name):
try: return self._d[name]
except KeyError: raise AttributeError, name
class values:
def len(self): return 1
def __getitem__(self, i):
try: return self._d[i]
except AttributeError: pass
self._d = self._f()
return self._d[i]
class TableBrowser(Browser, Acquisition.Implicit):
icon = 'what'
Description = check = ''
def tpValues(self):
v = values()
v._f = self.tpValues_
return v
def tpValues_(self):
r = []
tname = self.__name__
for d in self._c.columns(tname):
b = ColumnBrowser()
b._d = d
b.icon = field_icons.get(d['Type'], 'text')
b.TABLE_NAME = tname
r.append(b)
return r
def tpId(self): return self._d['TABLE_NAME']
def tpURL(self): return "Table/%s" % self._d['TABLE_NAME']
def Name(self): return self._d['TABLE_NAME']
def Type(self): return self._d['TABLE_TYPE']
class ColumnBrowser(Browser):
icon = 'field'
#def check(self): return ('\t<input type=checkbox name="%s.%s">' % (self.TABLE_NAME, self._d['Name']))
def tpId(self): return self._d['Name']
def tpURL(self): return "Column/%s" % self._d['Name']
def Description(self):
d = self._d
t = { True:'null', False:'not null' }
d['Nullable'] = t.get(d['Nullable'],'')
if d['Scale']:
return " %(Type)s(%(Precision)s,%(Scale)s) %(Nullable)s" % d
else:
return " %(Type)s(%(Precision)s) %(Nullable)s" % d
--- NEW FILE: VERSION.txt ---
ZInformixDA 0.3
--- NEW FILE: CREDITS.txt ---
ZInformixDA contributors
------------------------
Name: papa
Link: http://www.zope.org/Members/papa/
Note: Very usefull modified ZInformixDA version
Name: Isaac Salsberg ( isa...@ya... )
Link: http://www.zope.org/Members/isalsberg/
Note: How to compile/link ZInformixDA on win32 using MS VC 6.0
Name: Carsten Haese ( ch...@us... )
Link: http://informixdb.sourceforge.net/
Note: informixdb current maintainter & zinformixda project hosting
Name: Stephen J. Turner ( sjt...@ix... )
Link: http://starship.python.net/crew/sturner/informixdb.html
Note: old informixdb maintainer
Name: Alexander Kuznetsov
Link: http://thor.prohosting.com/~alexan/pub/Kinfxdb/
Note: Kinfxdb maintainer
Name: Mark Rees
Link: http://www.zope.org/Members/mark_rees/, http://hex-dump.blogspot.com/
Note: ZInformixDA version 0.2
Name: Andy Dustman ( an...@du... )
Link: http://www.zope.org/Members/adustman/, http://sourceforge.net/projects/mysql-python/
Note: MySQLdb and DA
Thank you
---------
- Zope Corporation for the ZOPE/ZEO environment. :)
- Entire Zope Community for their big help.
- Julio Silva ( aka zorton ) for findind the need to
have and support ZInformixDA. :>
--- NEW FILE: db.py ---
##############################################################################
#
# Copyright (c) 2004, 2005, 2006 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
##############################################################################
# informix specific
import informixdb
import Shared.DC.ZRDB.TM
import string, sys
from DateTime import DateTime
from string import strip, split, find, upper
from time import time
from UserDict import UserDict
import logging
database_type = 'Informix'
__doc__ = '''%s Database Connection''' % database_type
__revision__ = '$Id: db.py,v 1.1 2006/10/14 02:43:40 olavosantos Exp $'
__version__ = string.split(__revision__)[2]
logger = logging.getLogger('Product.Z%sDA' % database_type)
logger.setLevel(logging.INFO)
class Icons(UserDict):
"""icon values are registered in __init__.py"""
def __init__(self):
UserDict.__init__(self)
self.update(self.icons)
def get(self, i, x=None):
i = upper(i)
if i in self.keys(): return self[i]
else: return x
class TableIcons(Icons):
icons = {
'TABLE':'table',
'VIEW':'view2',
'SYSTEM_TABLE':'stable',
}
table_icons = TableIcons()
class FieldIcons(Icons):
icons = {
'BLOB':'bin',
'BOOLEAN':'bin',
'BYTE':'text',
'CHAR':'text',
'CLOB':'bin',
'DATE':'date',
'DATETIME':'date',
'DECIMAL':'float',
'DOUBLE':'float',
'FLOAT':'float',
'INT':'int',
'INTEGER':'int',
'INTERVAL':'field',
'INT8':'int',
'INT24':'int',
'LONG':'int',
'LONGLONG':'int',
'LVARCHAR':'text',
'MONEY':'float',
'NCHAR':'text',
'NVARCHAR':'text',
'SERIAL':'int',
'SERIAL8':'int',
'SHORT':'int',
'SMALLFLOAT':'float',
'SMALLINT':'int',
'TEXT':'text',
'TIMESTAMP':'date',
'TINY':'int',
'VARCHAR':'text',
'YEAR':'int',
}
field_icons = FieldIcons()
# Python Database API Specification v2.0
# http://www.python.org/dev/peps/pep-0249/
#
apilevel_required = 2.0
_v = float(getattr(informixdb, 'apilevel', '0.0'))
if _v < apilevel_required:
_vp = (database_type, apilevel_required, _v)
_msg = "Z%sDA requires at least python database api %s, level %s found.\nPlease upgrade your informixdb version.\n" % _vp
raise RuntimeError, _msg
class DB(Shared.DC.ZRDB.TM.TM):
_p_oid = _p_changed = _registered = None
def __init__(self, connection, transactions=None, verbose=None):
self.connection = connection
self.transactions = transactions
self.verbose = verbose
self.kwargs = self._parse_connection_string(self.connection)
if self.verbose: logger.info('%s : open database connection.' % self.kwargs[0])
self.db = apply(informixdb.connect, self.kwargs)
# autocommit = true when transactions are disabled by user
if not transactions:
if self.verbose: logger.info('%s : enabling autocommit.' % self.kwargs[0])
self.db.autocommit = True
def _parse_connection_string(self, connection):
kwargs = ''
items = split(connection)
if not items: return kwargs
else: return items
def tables(self, rdb=0, _care=('TABLE', 'VIEW')):
r = []
a = r.append
# Table Types:
#
# T - Table
# V - View
#
# Table IDs:
#
# 100 -> nnn - user defined
# 0 -> 24 - system defined
#
if self.verbose: logger.info('%s : listing database tables.' % self.kwargs[0])
result = self.query('SELECT tabname, owner, tabid, tabtype FROM systables WHERE tabtype IN ("T","V") ORDER BY owner, tabname', max_rows=9999999)[1]
for row in result:
ttype = 'VIEW'
if row[3] == 'T':
if int(row[2]) >= 100:
ttype = 'TABLE'
else:
ttype = 'SYSTEM_TABLE'
a({'TABLE_NAME': strip(row[1])+'.'+strip(row[0]), 'TABLE_TYPE': ttype, 'TABLE_OWNER': row[1]})
return r
def columns(self, table_name):
if self.transactions: self._register()
if self.verbose: logger.info('%s : create cursor.' % self.kwargs[0])
c = self.db.cursor()
if self.verbose: logger.info('%s : %s : listing table columns.' % (self.kwargs[0], table_name))
# get column description ( for some yet-to-know reason informixdb doesn't retrieve the correct value for null_ok )
rtype = {}
c.execute('SELECT * FROM %s ' % table_name)
desc = c.description
for name, type, width, ds, p, scale, null_ok in desc:
rtype[name] = type
# get column details
table_name = string.split(table_name,'.')[-1]
r = []
a = r.append
c.execute("SELECT * FROM syscolumns WHERE tabid = (SELECT tabid FROM systables WHERE tabname = '%s') ORDER BY colno" % table_name)
while 1:
row = c.fetchone()
if not row: break
null_ok = row[3] < 256 # if coltype >= 256, column don't allow null values
a( { 'Name': row[0],
'Type': rtype.get(row[0]),
'Precision': row[4],
'Scale': None,
'Nullable': null_ok,
} )
if c:
if self.verbose: logger.info('%s : close cursor.' % self.kwargs[0])
c.close()
return r
def query(self, query_string, max_rows=1000):
if self.transactions: self._register()
desc = None
result = ()
try:
for qs in filter(None, map(strip,split(query_string, '\0'))):
qtype = upper(split(qs, None, 1)[0])
if self.verbose: logger.info('%s : create cursor.' % self.kwargs[0])
c = self.db.cursor()
if self.verbose: logger.info('%s : sql statement : %s' % ( self.kwargs[0], string.join(map(strip,split(qs))) ) )
c.execute(qs)
if desc is not None:
if c and (c.description != desc):
raise 'Query Error', (
'multiple select schema are not allowed'
)
if c:
desc = c.description
if qtype == "SELECT" or qtype == "EXECUTE":
result = c.fetchmany(max_rows)
if self.verbose: logger.info('%s : close cursor.' % self.kwargs[0])
c.close()
else:
desc = None
except informixdb.Error, m:
raise
if desc is None: return (),()
r = []
a = r.append
for name, type, width, ds, p, scale, null_ok in desc:
a( { 'name': name,
'type': type,
'width': width,
'null': null_ok,
} )
return r, result
def string_literal(self, s):
return "'" + s + "'"
def _begin(self, *ignored):
if self.verbose: logger.info('%s : begin work.' % self.kwargs[0])
pass
def _finish(self, *ignored):
if self.verbose: logger.info('%s : commit work.' % self.kwargs[0])
self.db.commit()
def _abort(self, *ignored):
if self.verbose: logger.info('%s : rollback work.' % self.kwargs[0])
self.db.rollback()
def close(self):
if self.verbose: logger.info('%s : close database connection.' % self.kwargs[0])
self.db.close()
--- NEW FILE: COPYING.txt ---
ZInformixDA is distributed under the provisions of the Zope Public License
(ZPL) v2.1. See ZopePublicLicense.txt for the license text.
Copyright (C) 2005 ZInformixDA Contributors. See CREDITS.txt for a list
of ZInformixDA contributors.
ZInformixDA contains source code derived from:
- Zope 2, copyright (C) 2001-2006 by Zope Corporation.
--- NEW FILE: INSTALL.txt ---
Z Informix DA installation
--------------------------
Supported Platforms
ZInformixDA should work in any platform where you can
run Zope, build the informixdb python package, or in
other words in any IBM Informix supported platform.
Prerequisites
Please check DEPENDENCIES.txt for more information.
Installation ( short version )
Fullfill the prerequesites. Unzip/Untar ZInformixDA
into your "Products" folder and restart Zope.
Installation ( long version )
Linux:
I will try to describe an installation on a redhat-like linux.
It should be similar in any other linux distro.
step 1) Informix Client Software Development Kit (CSDK)
Create a temp installation folder.
# cd ~
# mkdir temp
# cd temp
Download the CSDK into temp. You may need to register
at IBM to be able to download the file.
# tar xvf clientsdk.2.90.UC4.LINUX.tar
# chown -R root.root .
# chmod -R 755 .
Add a group and user for informix and prepare
some needed environment values. We will use /opt/informix
to install the csdk.
# groupadd informix
# useradd -g informix -d /dev/null informix
# mkdir /opt/informix
# INFORMIXDIR=/opt/informix
# export INFORMIXDIR
# ACCEPTLICENSE=yes
# export ACCEPTLICENSE
Install using the rpm installation method. Please read
the doc/Client_install_guide.pdf. You have there plenty
of options for your specific system.
# rpm -ivh --prefix $INFORMIXDIR message.rpm
# rpm -ivh --prefix $INFORMIXDIR gls.rpm
# rpm -ivh --prefix $INFORMIXDIR clientsdkcontent.rpm
step 2) InformixDB Python Module
Download it.
# tar xvfz InformixDB-2.2.tar.gz
# chown -R root.root InformixDB-2.2
# chmod -R 755 InformixDB-2.2
# cd InformixDB-2.2
If you are using a binary package of Zope, you need run
setup.py with the python executable that came with Zope.
# /usr/local/bin/python2.4 setup.py build_ext
# /usr/local/bin/python2.4 setup.py install
Please read the InformixDB README.txt. You have there more
usefull options that you can use in your system.
step 3) System Configurations
Don't forget to configure your dynamic linker run time bindings. :>
# vi /etc/ld.so.conf
/opt/informix/lib
/opt/informix/lib/esql
# ldconfig
If you are going to use onsoctcp as the connectivity protocol, don't
forget to add some network services into /etc/services.
# vi /etc/services
sqlexec 1525/tcp # Informix SQL
sqlexec2 1526/tcp # Informix SQL
And of course, edit the default sqlhosts to add your own informix
servers.
# vi /opt/informix/etc/sqlhosts
dbinst2 onsoctcp 10.10.12.44 sqlexec2
ancdb01 onsoctcp 10.0.12.14 sqlexec
At least two environment values have to exist in all profiles.
Without them, informixdb won't work.
# vi /etc/profile.d/informix.sh
INFORMIXDIR=/opt/informix
INFORMIXSERVER=ptdpt2000
export INFORMIXDIR INFORMIXSERVER
# chmod 755 /etc/profile.d/informix.sh
# reboot
step 4) Test your informixdb installation
# /usr/local/bin/python2.4
Python 2.4.3 (#1, Aug 23 2006, 15:28:44)
[GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import informixdb
>>>
step 5) ZInformixDA
Download ZInformixDA. I assume that you have your zope
installation and/or instance in /usr/local/zope.
# tar xvfz ZInformixDA-0.3.tar.gz
# chown -R root.root ZInformixDA
# chmod -R 755 ZInformixDA/
# mv ZInformixDA /usr/local/zope/Products/
# /usr/local/zope/bin/runzope
If everything went well you will see a new Product in your
Zope ControlPanel and the possibility to add a Z Informix
Database Connection.
Windows:
This installation description should be similar in any windows
release.
step 1) Informix Client Software Development Kit (CSDK)
Create a temp installation folder.
c:\temp
Download the CSDK into temp. You may need to register
at IBM to be able to download the file.
c:\temp\clientsdk.2.90.TC6.WIN.zip
Unzip the file and run installation.
c:\temp\clientsdk.2.90.TC6.WIN\IBM Informix Client-SDK.msi
Use the custom installation mode and don't forget to
"Set INFORMIXDIR to the newly chosen directory".
Follow the instructions and reboot your system after
installation.
step 2) InformixDB Python Module
Download into temp folder and run installation.
c:\temp\InformixDB-2.3.win32-py2.4.exe
If you are using a binary package of Zope, you probably
have to copy informixdb.* files from a python installation
into Zope lib folder.
C:\Program Files\Zope-2.9.4\bin\Lib\site-packages
Please read Isaac Salsberg tutorial on how to compile/link
ZInformixDA on win32 if you need to compile informixdb
module from scratch:
http://www.zope.org/Members/isalsberg/InformixDA/How-ToZInformixDA
step 3) System Configurations
Use "Setnet32" program to setup informix hosts and
environment variables. Set at least INFORMIXDIR and
INFORMIXSERVER.
step 4) Test your informixdb installation
C:\Program Files\Zope-2.9.4\bin>python
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import informixdb
>>>
step 5) ZInformixDA
Download and unzip ZInformixDA into your Products folder.
If everything went well you will see a new Product in your
Zope ControlPanel and the possibility to add a Z Informix
Database Connection.
Database Adapter Usage
Add a Z Informix Database Connection and start using
ZSQL Methods to query your database.
Upgrading
I've tried to evolve the code without breaking nothing. So the
upgrade process is ( or at least "should be" ) transparent.
The only restriction is the need to use an informixdb that follows
the Python Database API Specification v2.0. If you use the old
informixdb module on your zope python version, your have to
upgrade it too.
Support/Bugs/Features/Future
If you have some questions about this zope product, please drop
me an email and i will be glad to help you.
--
Olavo Santos <nb...@cy...>
http://www.varkala.net/
--- NEW FILE: __init__.py ---
##############################################################################
#
# Copyright (c) 2004, 2005, 2006 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
##############################################################################
import string, os
from db import database_type
import DA, Globals
from App.ImageFile import ImageFile
__doc__ = '''%s Database Adapter Package Registration''' % database_type
__revision__ = '$Id: __init__.py,v 1.1 2006/10/14 02:43:40 olavosantos Exp $'
__version__ = string.split(__revision__)[2]
# generic database adapter icons
misc_ = {
'conn':ImageFile(os.path.join('Shared','DC','ZRDB','www','DBAdapterFolder_icon.gif')),
}
for icon in ( 'table', 'view2', 'stable', 'what', 'field', 'text', 'bin', 'int', 'float', 'date', 'time', 'datetime'):
misc_[icon] = ImageFile(os.path.join('www','%s.gif') % icon, globals())
# generic database adapter manage_add method
manage_addZDAConnectionForm = Globals.HTMLFile( 'dtml/connectionAdd',
globals(),
database_type=database_type )
def manage_addZDAConnection( self, id, title,
connection_string, check=None, transactions=None, verbose=None,
REQUEST=None):
"""DA Connection Add Method"""
self._setObject(id, DA.Connection(id, title, connection_string, check, transactions, verbose))
if REQUEST is not None: return self.manage_main(self, REQUEST)
# initialization method
def initialize(context):
context.registerClass(
instance_class = DA.Connection,
permission = 'Add Z %s Database Connections' % database_type,
constructors = ( manage_addZDAConnectionForm,
manage_addZDAConnection )
)
--- NEW FILE: ZopePublicLicense.txt ---
Zope Public License (ZPL) Version 2.1
-------------------------------------
A copyright notice accompanies this license document that
identifies the copyright holders.
This license has been certified as open source. It has also
been designated as GPL compatible by the Free Software
Foundation (FSF).
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the
following conditions are met:
1. Redistributions in source code must retain the
accompanying copyright notice, this list of conditions,
and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying
copyright notice, this list of conditions, and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
3. Names of the copyright holders must not be used to
endorse or promote products derived from this software
without prior written permission from the copyright
holders.
4. The right to distribute this software or to use it for
any purpose does not give you the right to use
Servicemarks (sm) or Trademarks (tm) of the copyright
holders. Use of them is covered by separate agreement
with the copyright holders.
5. If any files are modified, you must cause the modified
files to carry prominent notices stating that you changed
the files and the date of any change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS''
AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
NO EVENT SHALL THE COPYRIGHT HOLDERS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
--- NEW FILE: CHANGES.txt ---
Z Informix DA releases
----------------------
0.3
License update.
Facelift to get rid of all Deprecation warnings in 2.9/2.10 zope trunk.
Added "Verbose Mode".
Minor changes to use informixdb api 2.0 python module.
0.2
"This was originally an alpha release of the DA so others can review it,
help me improve it and give me feedback. But it has been used in a number
of production environments over the last few months and has exhibited no bugs :-)"
( by Mark Rees )
0.1
This is the first (alpha) version of the database adapter using Informix
for Zope. This database adapter is based on the many Z DA's tht others
have provided to the Zope distribution.
--- NEW FILE: DEPENDENCIES.txt ---
Z Informix DA dependencies
--------------------------
* Informix Client Software Development Kit (CSDK) 2.90 or newer
http://www.ibm.com/software/data/informix/downloads.html
* Python 2.3.5 or newer
http://www.python.org/
* InformixDB 2.2 or newer
http://informixdb.sourceforge.net/
* Zope 2.7.0 or newer
http://www.zope.org/
--- NEW FILE: DA.py ---
##############################################################################
#
# Copyright (c) 2004, 2005, 2006 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
##############################################################################
from db import DB, database_type
import Globals, DABase, string
from App.Dialogs import MessageDialog
from DateTime import DateTime
from AccessControl import ClassSecurityInfo
import AccessControl.Permissions
import logging
logger = logging.getLogger('Product.Z%sDA' % database_type)
logger.setLevel(logging.INFO)
__doc__ = '''%s Database Connection''' % database_type
__revision__ = '$Id: DA.py,v 1.1 2006/10/14 02:43:40 olavosantos Exp $'
__version__ = string.split(__revision__)[2]
class Connection(DABase.Connection):
"""DA Connection Class"""
database_type = database_type
id = '%s_database_connection' % database_type
meta_type = title = 'Z %s Database Connection' % database_type
icon = 'misc_/Z%sDA/conn' % database_type
check = True
verbose = None
transactions = None
security = ClassSecurityInfo()
security.declareProtected(AccessControl.Permissions.manage_properties, 'manage_properties')
manage_properties = Globals.HTMLFile('dtml/connectionEdit', globals())
security.declareProtected(AccessControl.Permissions.view_management_screens, 'manage_main')
manage_main = Globals.HTMLFile('dtml/connectionStatus', globals())
def __init__(self, id, title, connection_string, check=None, transactions=None, verbose=None):
self.id = str(id)
self.edit(title, connection_string, check, transactions, verbose)
if self.verbose: logger.info('%s: running __init__ method.' % self.id)
def factory(self): return DB
def edit(self, title, connection_string, check=None, transactions=None, verbose=None):
self.title = title
self.connection_string = connection_string
self.check = check
self.transactions = transactions
self.verbose = verbose
if self.verbose: logger.info('%s: properties edited.' % self.id)
if check: self.connect(connection_string)
security.declareProtected(AccessControl.Permissions.manage_properties, 'manage_edit')
def manage_edit(self, title, connection_string, check=None, transactions=None, verbose=None, REQUEST=None):
"""Change connection properties"""
self.edit(title, connection_string, check, transactions, verbose)
if REQUEST is not None:
return MessageDialog(
title='Edited',
message='<strong>%s</strong> has been edited.' % self.id,
action ='./manage_main',
)
security.declareProtected(AccessControl.Permissions.open_close_database_connection, 'manage_open_connection')
def manage_open_connection(self, REQUEST=None):
"""Open database connection"""
if self.verbose: logger.info('%s: trying to open database connection...' % self.id)
self.connect(self.connection_string)
return self.manage_main(self, REQUEST)
security.declareProtected(AccessControl.Permissions.open_close_database_connection, 'manage_close_connection')
def manage_close_connection(self, REQUEST=None):
"""Close database connection"""
if self.verbose: logger.info('%s: trying to close database connection...' % self.id)
try:
if hasattr(self,'_v_database_connection'):
self._v_database_connection.close()
self._v_connected = ''
except:
logger.error('Error closing relational database connection.', exc_info=True)
if REQUEST is not None:
return self.manage_main(self, REQUEST)
def __setstate__(self, state):
Globals.Persistent.__setstate__(self, state)
if self.connection_string and self.check:
try:
self.connect(self.connection_string)
except:
logger.error('Error connecting to relational database.', exc_info=True)
def connect(self, s):
if self.verbose: logger.info('%s: running connect method.' % self.id)
self.manage_close_connection()
DB = self.factory()
try:
# some added properties
if not hasattr(self, 'transactions'): self.transactions = None
if not hasattr(self, 'verbose'): self.verbose = None
## No try. DO.
if self.verbose: logger.info('%s: create db instance.' % self.id)
self._v_database_connection = DB(s, self.transactions, self.verbose)
self._v_connected = DateTime()
except:
raise
return self
def table_info(self):
return self._v_database_connection.table_info()
def sql_quote__(self, v, escapes={}):
return self._v_database_connection.string_literal(v)
Globals.InitializeClass(Connection)
|