~psycopg/psycopg/2.0.x

« back to all changes in this revision

Viewing changes to ZPsycopgDA/DABase.py

  • Committer: Federico Di Gregorio
  • Date: 2004-10-29 16:15:45 UTC
  • Revision ID: fog-a4e5ae2c65dfd04775bcecac32ed8e8dda664017
Undo of wrong commit of 1.1.x source code over 2.x.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
##############################################################################
2
 
3
 
# Zope Public License (ZPL) Version 1.0
4
 
# -------------------------------------
5
 
6
 
# Copyright (c) Digital Creations.  All rights reserved.
7
 
8
 
# This license has been certified as Open Source(tm).
9
 
10
 
# Redistribution and use in source and binary forms, with or without
11
 
# modification, are permitted provided that the following conditions are
12
 
# met:
13
 
14
 
# 1. Redistributions in source code must retain the above copyright
15
 
#    notice, this list of conditions, and the following disclaimer.
16
 
17
 
# 2. Redistributions in binary form must reproduce the above copyright
18
 
#    notice, this list of conditions, and the following disclaimer in
19
 
#    the documentation and/or other materials provided with the
20
 
#    distribution.
21
 
22
 
# 3. Digital Creations requests that attribution be given to Zope
23
 
#    in any manner possible. Zope includes a "Powered by Zope"
24
 
#    button that is installed by default. While it is not a license
25
 
#    violation to remove this button, it is requested that the
26
 
#    attribution remain. A significant investment has been put
27
 
#    into Zope, and this effort will continue if the Zope community
28
 
#    continues to grow. This is one way to assure that growth.
29
 
30
 
# 4. All advertising materials and documentation mentioning
31
 
#    features derived from or use of this software must display
32
 
#    the following acknowledgement:
33
 
34
 
#      "This product includes software developed by Digital Creations
35
 
#      for use in the Z Object Publishing Environment
36
 
#      (http://www.zope.org/)."
37
 
38
 
#    In the event that the product being advertised includes an
39
 
#    intact Zope distribution (with copyright and license included)
40
 
#    then this clause is waived.
41
 
42
 
# 5. Names associated with Zope or Digital Creations must not be used to
43
 
#    endorse or promote products derived from this software without
44
 
#    prior written permission from Digital Creations.
45
 
46
 
# 6. Modified redistributions of any form whatsoever must retain
47
 
#    the following acknowledgment:
48
 
49
 
#      "This product includes software developed by Digital Creations
50
 
#      for use in the Z Object Publishing Environment
51
 
#      (http://www.zope.org/)."
52
 
53
 
#    Intact (re-)distributions of any official Zope release do not
54
 
#    require an external acknowledgement.
55
 
56
 
# 7. Modifications are encouraged but must be packaged separately as
57
 
#    patches to official Zope releases.  Distributions that do not
58
 
#    clearly separate the patches from the original work must be clearly
59
 
#    labeled as unofficial distributions.  Modifications which do not
60
 
#    carry the name Zope may be packaged in any form, as long as they
61
 
#    conform to all of the clauses above.
62
 
63
 
64
 
# Disclaimer
65
 
66
 
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
67
 
#   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
68
 
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
69
 
#   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
70
 
#   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
71
 
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
72
 
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
73
 
#   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
74
 
#   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
75
 
#   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
76
 
#   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
77
 
#   SUCH DAMAGE.
78
 
79
 
80
 
# This software consists of contributions made by Digital Creations and
81
 
# many individuals on behalf of Digital Creations.  Specific
82
 
# attributions are listed in the accompanying credits file.
83
 
84
 
##############################################################################
85
 
__doc__='''Database Connection
86
 
 
87
 
$Id: DABase.py 400 2003-01-20 14:39:34Z fog $'''
88
 
__version__='$Revision: 1.10 $'[11:-2]
89
 
 
90
 
 
91
 
import Shared.DC.ZRDB.Connection, sys
92
 
from App.Dialogs import MessageDialog
93
 
from Globals import HTMLFile, ImageFile
 
1
# ZPsycopgDA/DABase.py - ZPsycopgDA Zope product: Database inspection
 
2
#
 
3
# Copyright (C) 2004 Federico Di Gregorio <fog@initd.org>
 
4
#
 
5
# This program is free software; you can redistribute it and/or modify
 
6
# it under the terms of the GNU General Public License as published by the
 
7
# Free Software Foundation; either version 2, or (at your option) any later
 
8
# version.
 
9
#
 
10
# Or, at your option this program (ZPsycopgDA) can be distributed under the
 
11
# Zope Public License (ZPL) Version 1.0, as published on the Zope web site,
 
12
# http://www.zope.org/Resources/ZPL.
 
13
#
 
14
# This program is distributed in the hope that it will be useful, but
 
15
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
 
16
# or FITNESS FOR A PARTICULAR PURPOSE.
 
17
#
 
18
# See the LICENSE file for details.
 
19
 
 
20
import sys
 
21
import Shared.DC.ZRDB.Connection
 
22
 
 
23
from db import DB
 
24
from Globals import HTMLFile
 
25
from ImageFile import ImageFile
94
26
from ExtensionClass import Base
95
 
import Acquisition
96
 
from psycopg import NUMBER, ROWID, STRING, INTEGER, FLOAT
97
 
from psycopg import BOOLEAN, DATETIME, LONGINTEGER
 
27
from DateTime import DateTime
 
28
 
 
29
# import psycopg and functions/singletons needed for date/time conversions
 
30
 
 
31
import psycopg
 
32
from psycopg.extensions import INTEGER, LONGINTEGER, FLOAT, BOOLEAN
 
33
from psycopg import NUMBER, STRING, ROWID, DATETIME 
 
34
 
 
35
 
98
36
 
99
37
class Connection(Shared.DC.ZRDB.Connection.Connection):
100
38
    _isAnSQLConnection = 1
101
39
 
 
40
    info = None
102
41
    
103
 
    manage_options=Shared.DC.ZRDB.Connection.Connection.manage_options+(
104
 
        {'label': 'Browse', 'action':'manage_browse'},
105
 
        # {'label': 'Design', 'action':'manage_tables'}
106
 
        )
107
 
 
108
 
    manage_tables = HTMLFile('tables',globals())
109
 
    manage_browse = HTMLFile('browse',globals())
110
 
 
111
 
    info=None
112
 
 
113
 
    def tpValues(self):
114
 
        #if hasattr(self, '_v_tpValues'): return self._v_tpValues
115
 
        r=[]
116
 
        # self._v_tables=tables=TableBrowserCollection()
117
 
        #tables=tables.__dict__
118
 
        c = self._v_database_connection
119
 
        try:
120
 
            for d in c.tables(rdb=0):
121
 
                try:
122
 
                    name=d['TABLE_NAME']
123
 
                    b=TableBrowser()
124
 
                    b.__name__=name
125
 
                    b._d=d
126
 
                    b._c=c
127
 
                    # b._columns=c.columns(name)
128
 
                    try: b.icon=table_icons[d['TABLE_TYPE']]
129
 
                    except: pass
130
 
                    r.append(b)
131
 
                    # tables[name]=b
132
 
                except:
133
 
                    # print d['TABLE_NAME'], sys.exc_type, sys.exc_value
134
 
                    pass
135
 
 
136
 
        finally: pass #print sys.exc_type, sys.exc_value
137
 
        #self._v_tpValues=r
138
 
        return r
 
42
    #manage_options = Shared.DC.ZRDB.Connection.Connection.manage_options + (
 
43
    #    {'label': 'Browse', 'action':'manage_browse'},)
 
44
 
 
45
    #manage_tables = HTMLFile('tables', globals())
 
46
    #manage_browse = HTMLFile('browse',globals())
139
47
 
140
48
    def __getitem__(self, name):
141
 
        if name=='tableNamed':
 
49
        if name == 'tableNamed':
142
50
            if not hasattr(self, '_v_tables'): self.tpValues()
143
51
            return self._v_tables.__of__(self)
144
52
        raise KeyError, name
145
53
 
 
54
    
 
55
    ## old stuff from ZPsycopgDA 1.1 (never implemented) ##
 
56
 
146
57
    def manage_wizard(self, tables):
147
 
        " "
 
58
        "Wizard of what? Oozing?"
148
59
 
149
60
    def manage_join(self, tables, select_cols, join_cols, REQUEST=None):
150
61
        """Create an SQL join"""
154
65
 
155
66
    def manage_update(self, table, keys, cols, REQUEST=None):
156
67
        """Create an SQL update"""
157
 
 
158
 
class TableBrowserCollection(Acquisition.Implicit):
159
 
    "Helper class for accessing tables via URLs"
160
 
    pass
161
 
 
162
 
class Browser(Base):
163
 
    def __getattr__(self, name):
164
 
        try: return self._d[name]
165
 
        except KeyError: raise AttributeError, name
166
 
 
167
 
class values:
168
 
 
169
 
    def len(self): return 1
170
 
 
171
 
    def __getitem__(self, i):
172
 
        try: return self._d[i]
173
 
        except AttributeError:
174
 
            pass
175
 
        self._d=self._f()
176
 
        return self._d[i]
177
 
 
178
 
class TableBrowser(Browser, Acquisition.Implicit):
179
 
    icon='what'
180
 
    Description=check=''
181
 
    info=HTMLFile('table_info',globals())
182
 
    menu=HTMLFile('table_menu',globals())
183
 
 
184
 
    def tpValues(self):
185
 
        v=values()
186
 
        v._f=self.tpValues_
187
 
        return v
188
 
 
189
 
    def tpValues_(self):
190
 
        r=[]
191
 
        tname=self.__name__
192
 
        for d in self._c.columns(tname):
193
 
            b=ColumnBrowser()
194
 
            b._d=d
195
 
            try: b.icon=field_icons[d['Type']]
196
 
            except: pass
197
 
            b.TABLE_NAME=tname
198
 
            r.append(b)
199
 
        return r
200
 
            
201
 
    def tpId(self): return self._d['TABLE_NAME']
202
 
    def tpURL(self): return "Table/%s" % self._d['TABLE_NAME']
203
 
    def Name(self): return self._d['TABLE_NAME']
204
 
    def Type(self): return self._d['TABLE_TYPE']
205
 
 
206
 
    manage_designInput=HTMLFile('designInput',globals())
207
 
    def manage_buildInput(self, id, source, default, REQUEST=None):
208
 
        "Create a database method for an input form"
209
 
        args=[]
210
 
        values=[]
211
 
        names=[]
212
 
        columns=self._columns
213
 
        for i in range(len(source)):
214
 
            s=source[i]
215
 
            if s=='Null': continue
216
 
            c=columns[i]
217
 
            d=default[i]
218
 
            t=c['Type']
219
 
            n=c['Name']
220
 
            names.append(n)
221
 
            if s=='Argument':
222
 
                values.append("<dtml-sqlvar %s type=%s>'" %
223
 
                              (n, vartype(t)))
224
 
                a='%s%s' % (n, boboType(t))
225
 
                if d: a="%s=%s" % (a,d)
226
 
                args.append(a)
227
 
            elif s=='Property':
228
 
                values.append("<dtml-sqlvar %s type=%s>'" %
229
 
                              (n, vartype(t)))
230
 
            else:
231
 
                if isStringType(t):
232
 
                    if find(d,"\'") >= 0: d=join(split(d,"\'"),"''")
233
 
                    values.append("'%s'" % d)
234
 
                elif d:
235
 
                    values.append(str(d))
236
 
                else:
237
 
                    raise ValueError, (
238
 
                        'no default was given for <em>%s</em>' % n)
239
 
 
240
 
class ColumnBrowser(Browser):
241
 
    icon='field'
242
 
 
243
 
    def check(self):
244
 
        return ('\t<input type=checkbox name="%s.%s">' %
245
 
                (self.TABLE_NAME, self._d['Name']))
246
 
    def tpId(self): return self._d['Name']
247
 
    def tpURL(self): return "Column/%s" % self._d['Name']
248
 
    def Description(self):
249
 
        d=self._d
250
 
        if d['Scale']:
251
 
            return " %(Type)s(%(Precision)s,%(Scale)s) %(Nullable)s" % d
252
 
        else:
253
 
            return " %(Type)s(%(Precision)s) %(Nullable)s" % d
254
 
 
255
 
table_icons={
256
 
    'TABLE': 'table',
257
 
    'VIEW':'view',
258
 
    'SYSTEM_TABLE': 'stable',
259
 
    }
260
 
 
261
 
field_icons={
262
 
    NUMBER.name: 'int',
263
 
    STRING.name: 'text',
264
 
    DATETIME.name: 'date',
265
 
    INTEGER.name: 'int',
266
 
    FLOAT.name: 'float',
267
 
    BOOLEAN.name: 'bin',
268
 
    ROWID.name: 'int'
269
 
    }