summaryrefslogtreecommitdiffstats
path: root/examples3/SQL/runsqlex.py
blob: 2235699087f20ec8cc9ac01c5466721e1c37ebbf (plain)
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
#!/usr/bin/env python

import sys
from python_tqt.qt import *
from python_tqt.qtsql import *

from sqlex import SqlEx
from connect import ConnectDialog

from dbpar import *

TRUE = 1
FALSE = 0

def showError(err, parent):
    errStr = TQString("The database reported an error:\n\n")
    if not err.databaseText().isEmpty():
        errStr.append(err.databaseText())
        errStr.append("\n")
    if not err.driverText().isEmpty():
        errStr.append(err.driverText())
        errStr.append("\n")
    TQMessageBox.warning(parent, "Error", errStr)

class CustomSqlCursor(TQSqlCursor):
    def __init__(self, query = None, autopopulate = TRUE, db = None):
        TQSqlCursor.__init__(self, None, autopopulate, db)
        self.execQuery(query)
        if self.isSelect() and autopopulate:
            fields = self.driver().recordInfo(self)
            for f in fields:
                self.append(f)
        self.setMode(TQSqlCursor.ReadOnly)

    def select(self, filter, sort = TQSqlIndex()):
        return self.execQuery(self.lastQuery())

    def primaryIndex(self, prime = TRUE):
        return TQSqlIndex()

    def insert(self, invalidate = TRUE):
        return FALSE

    def update(self, invalidate = TRUE):
        return FALSE

    def delRecords(self, invalidate = TRUE):
        return FALSE

    def setName(self, name, autopopulate = TRUE):
        return


class MainWindow(SqlEx):
    def __init__(self,parent = None,name = None,fl = 0):
        SqlEx.__init__(self,parent,name,fl)
        self.conDiag = ConnectDialog(self, "Connection Dialog", TRUE)
        self.firstconn = TRUE

    def dbConnect(self):
        if self.firstconn:
            self.firstconn = FALSE
            self.conDiag.editUsername.setText(DB_USERNAME)
            self.conDiag.editPassword.setText(DB_PASSWORD)
            self.conDiag.editHostname.setText(DB_HOSTNAMES[0])
            self.conDiag.editDatabase.setText(DB_DATABASES[0])
            for i in range(self.conDiag.comboDriver.count()):
                if str(self.conDiag.comboDriver.text(i)) == DB_DRIVER:
                    self.conDiag.comboDriver.setCurrentItem(i)
                    break
        if self.conDiag.exec_loop() != TQDialog.Accepted:
            return
        if self.dt.sqlCursor():
            self.dt.setSqlCursor()

        # close old connection (if any)
        if TQSqlDatabase.contains("SqlEx"):
            oldDb = TQSqlDatabase.database("SqlEx")
            oldDb.close()
            TQSqlDatabase.removeDatabase("SqlEx")

        # open the new connection
        db = TQSqlDatabase.addDatabase(self.conDiag.comboDriver.currentText(), "SqlEx")
        if not db:
            TQMessageBox.warning(self, "Error", "Could not open database")
            return

        db.setHostName(self.conDiag.editHostname.text())
        db.setDatabaseName(self.conDiag.editDatabase.text())
        db.setPort(self.conDiag.portSpinBox.value())
        if not db.open(self.conDiag.editUsername.text(),
                       self.conDiag.editPassword.text()):
            showError(db.lastError(), self)
            return

        self.lbl.setText("Double-Click on a table-name to view the contents")
        self.lv.clear()
        
        tables = db.tables()
        for t in tables:
            lvi = TQListViewItem(self.lv, t)
            fields = db.recordInfo(t)
            for f in fields:
                req = "?"
                if f.isRequired() > 0:
                    req = "Yes"
                elif f.isRequired() == 0:
                    req = "No"
                fi = TQListViewItem(lvi, f.name(), TQVariant.typeToName(f.type()), req)
                lvi.insertItem(fi)
            self.lv.insertItem(lvi)

        self.submitBtn.setEnabled(TRUE)

    def execQuery(self):
        cursor = CustomSqlCursor(self.te.text(), TRUE,
                                 TQSqlDatabase.database("SqlEx", TRUE))
        if cursor.isSelect():
            self.dt.setSqlCursor(cursor, TRUE, TRUE)
            self.dt.refresh()
            txt = TQString("Query OK")
            if cursor.size() >= 0:
                txt.append(", returned rows: %s" % cursor.size())
            self.lbl.setText(txt)
        else:
            if not cursor.isActive():
                # an error occured
                showError(cursor.lastError(), self)
            else:
                self.lbl.setText("Query OK, affected rows: %s" %
                                 cursor.numRowsAffected())

    def showTable(self, item):
        i = item.parent()
        if not i:
            i = item
        cursor = TQSqlCursor(i.text(0), TRUE, TQSqlDatabase.database("SqlEx", TRUE))
        self.dt.setSqlCursor(cursor, TRUE, TRUE)
        self.dt.setSort(cursor.primaryIndex())
        self.dt.refresh(TQDataTable.RefreshAll)
        self.lbl.setText("Displaying table %s" % i.text(0))


if __name__ == "__main__":
    a = TQApplication(sys.argv)
    TQObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()"))
    w = MainWindow()
    a.setMainWidget(w)
    w.show()
    a.exec_loop()