File: dbdialog.py

package info (click to toggle)
thuban 1.2.2-14
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 9,176 kB
  • sloc: python: 30,410; ansic: 6,181; xml: 4,234; cpp: 1,595; makefile: 145
file content (391 lines) | stat: -rw-r--r-- 14,450 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# Copyright (c) 2001, 2003, 2004, 2007 by Intevation GmbH
# Authors:
# Martin Mueller <mmueller@intevation.de>
# Bernhard Herzog <bh@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.


"""Dialogs to manage database connections"""

import sys, traceback

import wx

try:
    import psycopg
except ImportError:
    psycopg = None

from Thuban import _
from Thuban.UI import internal_from_wxstring
from Thuban.UI.dialogs import NonModalDialog
from Thuban.Model.table import FIELDTYPE_INT
from Thuban.Model.postgisdb import ConnectionError, PostGISConnection
from Thuban.Model.messages import DBCONN_ADDED, DBCONN_REMOVED
from messages import SESSION_REPLACED


ID_DB_ADD    = 9101
ID_DB_REMOVE = 9102

ID_DBCHOOSE_RETRIEVE = 9201
ID_DBCHOOSE_OK       = 9202
ID_DBCHOOSE_CANCEL   = 9203
ID_LB_DCLICK         = 9204


class ChooseDBTableDialog(wx.Dialog):

    def __init__(self, parent, session):
        wx.Dialog.__init__(self, parent, -1, _("Choose layer from database"),
                          style = wx.CAPTION)
        self.session = session
        self.dbconns = self.session.DBConnections()
        self.tables = []

        #
        # Build the dialog
        #

        # Sizer for the entire dialog
        top = wx.FlexGridSizer(2, 1, 0, 0)

        # Sizer for the main part with the list boxes
        main_sizer = wx.BoxSizer(wx.HORIZONTAL)
        top.Add(main_sizer, 1, wx.EXPAND, 0)

        # The list box with the connections
        static_box = wx.StaticBoxSizer(wx.StaticBox(self, -1, _("Databases")),
                                   wx.HORIZONTAL)
        self.lb_connections = wx.ListBox(self, -1)
        static_box.Add(self.lb_connections, 0, wx.EXPAND, 0)
        main_sizer.Add(static_box, 1, wx.EXPAND, 0)

        for i in range(len(self.dbconns)):
            self.lb_connections.Append(self.dbconns[i].BriefDescription())
        if self.lb_connections.GetCount() > 0:
            self.lb_connections.SetSelection(0, True)

        # The button box between the connections list box and the table
        # list box
        buttons = wx.FlexGridSizer(3, 1, 0, 0)
        buttons.Add( (20, 80), 0, wx.EXPAND, 0)
        retrieve_button = wx.Button(self, ID_DBCHOOSE_RETRIEVE, _("Retrieve"))
        self.Bind(wx.EVT_BUTTON, self.OnRetrieve, id=ID_DBCHOOSE_RETRIEVE)
        buttons.Add(retrieve_button, 0, wx.ALL
                    |wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 4)
        buttons.Add( (20, 80), 0, wx.EXPAND, 0)
        main_sizer.Add(buttons, 0, wx.EXPAND, 0)

        # The list box with the tables
        static_box = wx.StaticBoxSizer(wx.StaticBox(self, -1, _("Tables")),
                                   wx.HORIZONTAL)
        self.lb_tables = wx.ListBox(self, ID_LB_DCLICK)
        self.Bind(wx.EVT_LISTBOX, self.OnTableSelect, id=ID_LB_DCLICK)
        self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnLBDClick, id=ID_LB_DCLICK)
        static_box.Add(self.lb_tables, 0, wx.EXPAND, 0)
        main_sizer.Add(static_box, 1, wx.EXPAND, 0)

        # id column and geometry column selection
        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(wx.StaticText(self, -1, _("ID Column")), 0,
                wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
        self.text_id_column = wx.ComboBox(self, -1, "")
        box.Add(self.text_id_column, 0,
                wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 4)

        box.Add(wx.StaticText(self, -1, _("Geometry Column")), 0,
                wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
        self.text_geo_column = wx.ComboBox(self, -1, "")
        box.Add(self.text_geo_column, 0,
                wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 4)
        main_sizer.Add(box, 1, wx.EXPAND, 0)

        # The standard button box at the bottom of the dialog
        buttons = wx.FlexGridSizer(1, 2, 0, 0)
        ok_button = wx.Button(self, ID_DBCHOOSE_OK, _("OK"))
        self.Bind(wx.EVT_BUTTON, self.OnOK, id=ID_DBCHOOSE_OK)
        buttons.Add(ok_button, 0, wx.ALL|wx.ALIGN_RIGHT, 4)
        cancel_button = wx.Button(self, ID_DBCHOOSE_CANCEL, _("Cancel"))
        self.Bind(wx.EVT_BUTTON, self.OnCancel, id=ID_DBCHOOSE_CANCEL)
        buttons.Add(cancel_button, 0, wx.ALL, 4)
        top.Add(buttons, 1, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 4)

        # Autosizing
        self.SetAutoLayout(1)
        self.SetSizer(top)
        top.Fit(self)
        top.SetSizeHints(self)
        self.Layout()


    def GetTable(self):
        i = self.lb_tables.GetSelection()
        if i >= 0:
            return (self.selected_conn, self.tables[i],
                    internal_from_wxstring(self.text_id_column.GetValue()),
                    internal_from_wxstring(self.text_geo_column.GetValue()))
        return None

    def OnRetrieve(self, event):
        i = self.lb_connections.GetSelection()
        if i >= 0:
            self.selected_conn = self.dbconns[i]
            self.tables = self.selected_conn.GeometryTables()
            self.lb_tables.Set(self.tables)

    def OnTableSelect(self, event):
        i = self.lb_tables.GetSelection()
        self.text_id_column.Clear()
        self.text_geo_column.Clear()
        if i >= 0:
            for name, typ in self.selected_conn.table_columns(self.tables[i]):
                if typ == "geometry":
                    self.text_geo_column.Append(name)
                elif typ == FIELDTYPE_INT:
                    self.text_id_column.Append(name)

    def OnLBDClick(self, event):
        if self.lb_tables.GetSelection() >= 0:
            self.EndModal(wx.ID_OK)
            self.Show(False)

    def OnOK(self, event):
        self.EndModal(wx.ID_OK)
        self.Show(False)

    def OnCancel(self, event):
        self.EndModal(wx.ID_CANCEL)
        self.Show(False)


class DBDialog(wx.Dialog):

    """Dialog for the parameters of a database connection"""

    def __init__(self, parent, title, parameters, message = ""):
        """Initialize the dialog box.

        The parameters argument should be a dictionary containing known
        connection parameters.

        The optional message parameter will be displayed at the top of
        the dialog box and can be used to display error messages when
        using the dialog to ask for correct parameters when the
        connection can't be established.
        """
        wx.Dialog.__init__(self, parent, -1, title)

        top = wx.BoxSizer(wx.VERTICAL)

        if message:
            top.Add(wx.StaticText(self, -1, message), 0,
                    wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)

        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(wx.StaticText(self, -1, _("Hostname:")), 0,
                wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
        self.text_host = wx.TextCtrl(self, -1, parameters.get("host", ""))
        box.Add(self.text_host, 2, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 4)
        box.Add(wx.StaticText(self, -1, _("Port:")), 0,
                wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
        self.text_port = wx.TextCtrl(self, -1, parameters.get("port", ""))
        box.Add(self.text_port, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 4)
        top.Add(box, 0, wx.EXPAND)

        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(wx.StaticText(self, -1, _("Database Name:")), 0,
                wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
        self.text_dbname = wx.TextCtrl(self, -1,
                                      parameters.get("dbname", ""))
        box.Add(self.text_dbname, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 4)
        top.Add(box, 0, wx.EXPAND)

        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(wx.StaticText(self, -1, _("User:")), 0,
                wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
        self.text_user = wx.TextCtrl(self, -1,
                                    parameters.get("user", ""))
        box.Add(self.text_user, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 4)
        box.Add(wx.StaticText(self, -1, _("Password:")), 0,
                wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
        self.text_password = wx.TextCtrl(self, -1,
                                        parameters.get("password", ""),
                                        style = wx.TE_PASSWORD)
        box.Add(self.text_password, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
                4)
        top.Add(box, 0, wx.EXPAND)

        buttons = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(self, wx.ID_OK, _("OK"))
        buttons.Add(button, 0, wx.ALL, 4)
        button = wx.Button(self, wx.ID_CANCEL, _("Cancel"))
        buttons.Add(button, 0, wx.ALL, 4)
        top.Add(buttons, 0, wx.ALIGN_RIGHT, 4)

        self.SetAutoLayout(1)
        self.SetSizer(top)
        top.Fit(self)
        top.SetSizeHints(self)

        self.Bind(wx.EVT_BUTTON, self.OnOK, id=wx.ID_OK)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, id=wx.ID_CANCEL)

    def RunDialog(self):
        self.ShowModal()
        self.Destroy()
        return self.result

    def end_dialog(self, result):
        self.result = result
        if result is not None:
            self.EndModal(wx.ID_OK)
        else:
            self.EndModal(wx.ID_CANCEL)
        self.Show(False)

    def OnOK(self, event):
        result = {}
        for name in ("host", "port", "dbname", "user", "password"):
            result[name] = getattr(self, "text_" + name).GetValue()
        self.end_dialog(result)

    def OnCancel(self, event):
        self.end_dialog(None)



class DBFrame(NonModalDialog):

    """Databse connection management dialog"""

    def __init__(self, parent, name, session, *args, **kwds):
        kwds["style"] = wx.ICONIZE|wx.CAPTION|wx.MINIMIZE
        NonModalDialog.__init__(self, parent, name, "")
        self.session = session
        self.app = self.parent.application

        self.app.Subscribe(SESSION_REPLACED, self.session_replaced)
        self.subscribe_session()

        self.DB_ListBox = wx.ListBox(self, -1,
                              style=wx.LB_SINGLE|wx.LB_HSCROLL|wx.LB_ALWAYS_SB)
        self.DB_Add = wx.Button(self, ID_DB_ADD, _("Add"))
        self.DB_Remove = wx.Button(self, ID_DB_REMOVE, _("Remove"))
        self.DB_CLOSE = wx.Button(self, wx.ID_CLOSE, _("Close"))
        self.__set_properties()
        self.__do_layout()
        self.Bind(wx.EVT_BUTTON, self.OnAdd, id=ID_DB_ADD)
        self.Bind(wx.EVT_BUTTON, self.OnRemove, id=ID_DB_REMOVE)
        self.Bind(wx.EVT_BUTTON, self.OnClose, id=wx.ID_CLOSE)

        self.conns_changed()

    def __set_properties(self):
        self.SetTitle(_("Database Management"))
        self.DB_ListBox.SetSize((200, 157))

    def __do_layout(self):
        top = wx.BoxSizer(wx.VERTICAL)

        box = wx.BoxSizer(wx.HORIZONTAL)

        box.Add(self.DB_ListBox, 1, wx.ALL|wx.EXPAND
                |wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 4)

        buttons = wx.BoxSizer(wx.VERTICAL)
        buttons.Add(self.DB_Add, 0, wx.ALL, 4)
        buttons.Add(self.DB_Remove, 0, wx.ALL, 4)

        box.Add(buttons, 0, wx.EXPAND)
        top.Add(box, 1, wx.EXPAND)

        buttons = wx.BoxSizer(wx.HORIZONTAL)
        buttons.Add(self.DB_CLOSE, 1, wx.ALL|wx.ALIGN_RIGHT, 4)
        top.Add(buttons, 0, wx.ALIGN_RIGHT)

        self.SetAutoLayout(1)
        self.SetSizer(top)
        top.Fit(self)
        top.SetSizeHints(self)

    def subscribe_session(self):
        """Internal: Subscribe to some session messages"""
        self.session.Subscribe(DBCONN_ADDED, self.conns_changed)
        self.session.Subscribe(DBCONN_REMOVED, self.conns_changed)

    def unsubscribe_session(self):
        """Internal: Subscribe from messages subscribe in subscribe_session"""
        self.session.Subscribe(DBCONN_ADDED, self.conns_changed)
        self.session.Subscribe(DBCONN_REMOVED, self.conns_changed)

    def session_replaced(self, *args):
        """Internal: resubscribe the session messages

        This method is a subscriber for the application's
        SESSION_REPLACED messages.
        """
        self.unsubscribe_session()
        self.session = self.app.Session()
        self.subscribe_session()
        self.conns_changed()

    def conns_changed(self, *args):
        """Internal: update the db connection list box

        Subscribed to the DBCONN_ADDED and DBCONN_REMOVED messages.
        """
        self.DB_ListBox.Clear()
        for conn in self.session.DBConnections():
            self.DB_ListBox.Append(conn.BriefDescription(), conn)

    def OnClose(self, event):
        self.unsubscribe_session()
        self.app.Unsubscribe(SESSION_REPLACED, self.session_replaced)
        NonModalDialog.OnClose(self, event)

    def RunMessageBox(self, title, text, flags = wx.OK | wx.ICON_INFORMATION):
        """Run a modal message box with the given text, title and flags
        and return the result"""
        dlg = wxMessageDialog(self, text, title, flags)
        dlg.CenterOnParent()
        result = dlg.ShowModal()
        dlg.Destroy()
        return result

    def OnAdd(self, event):
        message = ""
        parameters = {}
        while 1:
            dialog = DBDialog(self, _("Add Database"), parameters, message)
            parameters = dialog.RunDialog()
            if parameters is not None:
                for conn in self.session.DBConnections():
                    if conn.MatchesParameters(parameters):
                        self.RunMessageBox(_("Add Database"),
                                         _("Connection '%s' already exists")
                                           % conn.BriefDescription())
                        break
                else:
                    try:
                        conn = PostGISConnection(**parameters)
                    except ConnectionError, val:
                        message = str(val)
                    else:
                        self.session.AddDBConnection(conn)
                        break
            else:
                break

    def OnRemove(self, event):
        i = self.DB_ListBox.GetSelection()
        if i >= 0:
            conn = self.DB_ListBox.GetClientData(i)
            if self.session.CanRemoveDBConnection(conn):
                self.session.RemoveDBConnection(conn)
            else:
                self.RunMessageBox(_("Remove Database Connection"),
                                   _("The connection %s\nis still in use")
                                   % conn.BriefDescription())