del net-oscar
[learning-git.git] / pgworksheet_yvesf / pgw / RunSQL.py
blob48367e4acf5d8244942f61f8bc50c9abae53fd56
1 # -*- coding: latin-1; -*-
3 # PgWorksheet - PostgreSQL Front End
4 # http://pgworksheet.projects.postgresql.org/
6 # Copyright © 2004-2005 Henri Michelon & CML http://www.e-cml.org/
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License
10 # as published by the Free Software Foundation; either version 2
11 # of the License, or (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details (read LICENSE.txt).
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 # $Id
24 import string
25 import pygtk
26 import gtk
27 import sys
29 import pgw
31 class Column:
32 def __init__(self, col):
33 self.name = col[0]
34 self.type_code = col[1]
35 self.display_size = col[2]
36 self.internal_size = col[3]
37 self.precision = col[4]
38 self.scale = col[5]
39 self.null_ok = col[6]
41 class Result:
42 def __init__(self, sql, result):
43 self.sql = sql
45 self.description = [] #(name, type_code, display_size, internal_size, precision, scale,null_ok)
46 for col in result.description:
47 self.description.append(Column(col))
49 self.rows = []
50 row = result.fetchone()
51 while row is not None:
52 self.rows.append(row)
53 row = result.fetchone()
57 class RunSQL:
58 """Execute the SQL buffer and fill the GtkNotebook with the results."""
60 def __init__(self, execute, txtSQL, tabResult):
61 self.execute = execute
62 self.txtSQL = txtSQL
63 self.tabResult = tabResult
64 self.error_font = {}
67 def result(self, msg):
68 """update status bar text"""
69 print '<span foreground="#004400">' + msg + '</span>'
72 def str_limit(self, s, max = 20):
73 s = string.replace(s, '\\\\', '\\')
74 if (len(s) > (max + 3)):
75 return s[:max] + "..."
76 return s
79 def fill_treeview(self, sql, cursor):
80 result = Result(sql, cursor)
81 self.tabResult.add_results(result)
82 return 0#XXX remove this dependency
84 def run(self):
85 """Run the query and update the results"""
86 # clear the treeviews and the error text buffers
87 self.tabResult.clear()
89 self.result(_("Please wait, executing the query and fetching the results..."))
90 # update the display
91 while (gtk.events_pending() == True):
92 gtk.main_iteration_do(False)
94 # execute the query
95 sqlbuffer= self.txtSQL.get_buffer()
96 notices = []
97 try:
98 result = self.execute.execute(sqlbuffer)
99 rows = 0
100 if (isinstance(result, list)):
101 # multiple queries and multiple results...
102 parts = self.execute.split(sqlbuffer)
103 sqls = []
104 have_errors = 0
105 for sql in parts :
106 sql = string.strip(sql)
107 if (len(sql) > 0) :
108 sqls.append(sql)
109 for res in result:
110 sql = sqls.pop(0)
111 try:
112 if (res['cursor'].description is not None):
113 self.fill_treeview(sql, res['cursor'])
114 rows += res['cursor'].rowcount
115 notices = res['notices']
116 except KeyError:
117 try:
118 self.tabResult.add_error(res['text'], "psql : " + self.str_limit(sql))
119 except KeyError:
120 notices = res['notices']
121 self.tabResult.add_error(res['error'],
122 '<span foreground="#880000">' + _('Errors :') + '</span> ' +
123 self.str_limit(sql))
124 have_errors += 1
125 self.tabResult.set_current_page(0)
126 else: # one query
127 sql = sqlbuffer.get_text(sqlbuffer.get_start_iter(),
128 sqlbuffer.get_end_iter())
129 try:
130 if (result is None):
131 self.result(_("No result"))
132 elif (result['cursor'].description is None):
133 # not a SELECT
134 rows = result['cursor'].rowcount
135 notices = result['notices']
136 else:
137 # only one SELECT
138 rows = self.fill_treeview(sql, result['cursor'])
139 notices = result['notices']
140 except KeyError:
141 try:
142 self.tabResult.add_error(result['text'], "psql : " + self.str_limit(sql))
143 except KeyError:
144 self.tabResult.add_error(result['error'])
145 notices = result['notices']
147 buffer = self.txtSQL.get_buffer()
148 buffer.move_mark_by_name('selection_bound', buffer.get_start_iter());
149 buffer.move_mark_by_name('insert', buffer.get_end_iter());
151 except Exception, errstr:
152 import traceback
153 info= sys.exc_info()
154 self.result('<span foreground="#880000">' + _('query failed') + '</span>')
155 self.tabResult.add_error("Fehler %s in line %d"%(str(errstr), traceback.tb_lineno(info[2]) ))
156 traceback.print_tb(info[2])
158 if (len(notices) > 0):
159 msg = ""
160 while len(notices):
161 msg += notices.pop()
162 self.tabResult.add_error(msg, '<span foreground="#000088">'+ _("log") + '</span>')
164 self.result("")
165 # restore the focus
166 self.txtSQL.grab_focus()