コード例 #1
0
ファイル: ConnectionTreeView.py プロジェクト: Zaffy/emma
    def on_table_popup(self, popup, item):
        path, column, _iter, table = self.get_current_table()
        what = item.name

        if what == "refresh_table":
            table.refresh()
            self.redraw_table(table, _iter)
        elif what == "truncate_table":
            if not dialogs.confirm("truncate table",
                                   "do you really want to truncate the <b>%s</b> "
                                   "table in database <b>%s</b> on <b>%s</b>?" % (table.name, table.db.name,
                                                                                  table.db.host.name),
                                   self.emma.mainwindow):
                return
            if table.db.query("truncate `%s`" % table.name):
                table.refresh()
                self.redraw_table(table, _iter)
        elif what == "drop_table":
            if not dialogs.confirm("drop table",
                                   "do you really want to DROP the <b>%s</b> table in database "
                                   "<b>%s</b> on <b>%s</b>?" % (table.name, table.db.name, table.db.host.name),
                                   self.emma.mainwindow):
                return
            db = table.db
            if db.query("drop table `%s`" % table.name):
                self.emma.events.on_table_dropped(table)
        elif what == "check_table":
            self.current_host = table.db.host
            self.current_host.select_database(table.db)
            self.emma.current_query.on_execute_query_clicked(None, "check table `%s`" % table.name)
        elif what == "repair_table":
            self.current_host = table.db.host
            self.current_host.select_database(table.db)
            self.emma.current_query.on_execute_query_clicked(None, "repair table `%s`" % table.name)
コード例 #2
0
    def on_table_popup(self, popup, item):
        """
        :param popup:
        :param item:
        :return:
        """
        path, column, _iter, table = self.get_current_table()
        what = item.name

        if what == "refresh_table":
            table.refresh()
            self.redraw_table(table, _iter)
        elif what == "truncate_table":
            if not dialogs.confirm(
                    "truncate table",
                    "do you really want to truncate the <b>%s</b> "
                    "table in database <b>%s</b> on <b>%s</b>?" % (
                        table.get_escaped_name(),
                        table.db.get_escaped_name(),
                        table.db.host.get_escaped_name(),
                    ), self.emma.mainwindow):
                return
            if table.db.query("truncate `%s`" % table.name):
                table.refresh()
                self.redraw_table(table, _iter)
        elif what == "drop_table":
            if not dialogs.confirm(
                    "drop table",
                    "do you really want to DROP the <b>%s</b> table in database "
                    "<b>%s</b> on <b>%s</b>?" % (
                        table.get_escaped_name(),
                        table.db.get_escaped_name(),
                        table.db.host.get_escaped_name(),
                    ), self.emma.mainwindow):
                return
            db = table.db
            if db.query("drop table `%s`" % table.name):
                self.emma.events.trigger('on_table_dropped', table)
        elif what == "check_table":
            self.current_host = table.db.host
            self.current_host.select_database(table.db)
            self.emma.events.trigger('execute_query', None,
                                     "check table `%s`" % table.name)
        elif what == "repair_table":
            self.current_host = table.db.host
            self.current_host.select_database(table.db)
            self.emma.events.trigger('execute_query', None,
                                     "repair table `%s`" % table.name)
コード例 #3
0
 def _delete_cb(self, widget):
     """Properties dialog delete callback"""
     self._dialog.hide()
     name = brushmanager.translate_group_name(self._group)
     msg = C_(
         "brush group delete",
         u"Really delete group \u201C{group_name}\u201D?",
     ).format(
         group_name = name,
     )
     bm = self._app.brushmanager
     if not dialogs.confirm(self, msg):
         return
     bm.delete_group(self._group)
     if self._group not in bm.groups:
         GLib.idle_add(
             self._remove_panel_idle_cb,
             self.__gtype_name__, (self._group,),
         )
         return
     # Special groups like "Deleted" cannot be deleted,
     # but the error message is very confusing in that case...
     msg = C_(
         "brush group delete",
         u"Could not delete group \u201C{group_name}\u201D.\n"
         u"Some special groups cannot be deleted.",
     ).format(
         group_name = name,
     )
     dialogs.error(self, msg)
コード例 #4
0
    def on_save_query_clicked(self, button):
        d = self.emma.assign_once("save dialog", gtk.FileChooserDialog,
                                  "Save query", self.emma.mainwindow,
                                  gtk.FILE_CHOOSER_ACTION_SAVE,
                                  (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                   gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT))

        d.set_default_response(gtk.RESPONSE_ACCEPT)
        answer = d.run()
        d.hide()
        if not answer == gtk.RESPONSE_ACCEPT:
            return
        filename = d.get_filename()
        if os.path.exists(filename):
            if not os.path.isfile(filename):
                dialogs.show_message(
                    "save query",
                    "%s already exists and is not a file!" % filename)
                return
            if not dialogs.confirm(
                    "Overwrite file?",
                    "%s already exists! Do you want to overwrite it?" %
                    filename, self.emma.mainwindow):
                return
        b = self.textview.get_buffer()
        query_text = b.get_text(b.get_start_iter(), b.get_end_iter())
        try:
            fp = file(filename, "wb")
            fp.write(query_text)
            fp.close()
        except:
            dialogs.show_message(
                "Save Query", "Error writing query to file %s: %s" %
                (filename, sys.exc_value))
コード例 #5
0
 def _delete_cb(self, widget):
     """Properties dialog delete callback"""
     self._dialog.hide()
     name = brushmanager.translate_group_name(self._group)
     msg = C_(
         "brush group delete",
         u"Really delete group \u201C{group_name}\u201D?",
     ).format(group_name=name, )
     bm = self._app.brushmanager
     if not dialogs.confirm(self, msg):
         return
     bm.delete_group(self._group)
     if self._group not in bm.groups:
         GLib.idle_add(
             self._remove_panel_idle_cb,
             self.__gtype_name__,
             (self._group, ),
         )
         return
     # Special groups like "Deleted" cannot be deleted,
     # but the error message is very confusing in that case...
     msg = C_(
         "brush group delete",
         u"Could not delete group \u201C{group_name}\u201D.\n"
         u"Some special groups cannot be deleted.",
     ).format(group_name=name, )
     dialogs.error(self, msg)
コード例 #6
0
ファイル: QueryTab.py プロジェクト: glushko311/emma
    def on_save_query_clicked(self, button):
        d = self.emma.assign_once(
            "save dialog",
            gtk.FileChooserDialog,
            "Save query",
            self.emma.mainwindow,
            gtk.FILE_CHOOSER_ACTION_SAVE,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT),
        )

        d.set_default_response(gtk.RESPONSE_ACCEPT)
        answer = d.run()
        d.hide()
        if not answer == gtk.RESPONSE_ACCEPT:
            return
        filename = d.get_filename()
        if os.path.exists(filename):
            if not os.path.isfile(filename):
                dialogs.show_message("save query", "%s already exists and is not a file!" % filename)
                return
            if not dialogs.confirm(
                "Overwrite file?", "%s already exists! Do you want to overwrite it?" % filename, self.emma.mainwindow
            ):
                return
        b = self.textview.get_buffer()
        query_text = b.get_text(b.get_start_iter(), b.get_end_iter())
        try:
            fp = file(filename, "wb")
            fp.write(query_text)
            fp.close()
        except:
            dialogs.show_message("Save Query", "Error writing query to file %s: %s" % (filename, sys.exc_value))
コード例 #7
0
 def delete_cb(menuitem, bl, brush, menu):
     msg = C_("brush list commands", "Really delete brush from disk?")
     if not dialogs.confirm(menu, msg):
         return
     bl.remove_brush(brush)
     faves = bl.bm.groups[brushmanager.FAVORITES_BRUSH_GROUP]
     bl.bm.brushes_changed(faves)
コード例 #8
0
 def delete_brush_cb(self, window):
     b = self.bm.selected_brush
     if not b.name:
         dialogs.error(self, _('No brush selected!'))
         return
     if not dialogs.confirm(self, _("Really delete brush from disk?")):
         return
     self.bm.select_brush(None)
     self.delete_brush_internal(b)
コード例 #9
0
 def delete_group_cb(self, w, group):
     msg = _('Really delete group %s?') \
             % brushmanager.translate_group_name(group)
     if dialogs.confirm(self, msg):
         self.bm.delete_group(group)
         if group in self.bm.groups:
             msg = _('This group can not be deleted '
                     '(try to empty it first).')
             dialogs.error(self, msg)
コード例 #10
0
    def on_db_popup(self, popup, item):
        """
        :param popup:
        :param item:
        :return:
        """
        path, column = self.get_cursor()
        _iter = self.connections_model.get_iter(path)
        what = item.name
        db = self.connections_model.get_value(_iter, 0)

        if what == "refresh_database":
            new_tables = db.refresh()
            self.redraw_db(db, _iter, new_tables)
        elif what == "drop_database":
            hostname = db.host.name.replace('&', '&amp;')
            dbname = db.name.replace('&', '&amp;')
            if not dialogs.confirm(
                    "drop database",
                    "do you really want to drop the <b>%s</b> "
                    "database on <b>%s</b>?" %
                (dbname, hostname), self.emma.mainwindow):
                return
            host = db.host
            if host.query("drop database`%s`" % db.name, False, True):
                host.refresh()
                self.redraw_host(host,
                                 self.emma.connections_tv.get_host_iter(host))
        elif what == "new_table":
            name = dialogs.input_dialog(
                "New table",
                "Please enter the name of the new table:",
                window=self.emma.mainwindow)
            if not name:
                return
            if db.query(
                    "create table `%s` (`%s_id` int primary key auto_increment)"
                    % (name, name)):
                new_tables = db.refresh()
                self.redraw_db(db, self.emma.connections_tv.get_db_iter(db),
                               new_tables)
        elif what == "check_tables":
            self.current_host = db.host
            self.current_host.select_database(db)
            db.refresh()
            self.emma.events.trigger(
                'execute_query', None, "check table %s" %
                (",".join(map(lambda s: "`%s`" % s, db.tables.keys()))))
        elif what == "repair_tables":
            self.current_host = db.host
            self.current_host.select_database(db)
            db.refresh()
            self.emma.events.trigger(
                'execute_query', None, "repair table %s" %
                (",".join(map(lambda s: "`%s`" % s, db.tables.keys()))))
        elif what == "list_tables":
            self.emma.main_notebook.add_tables_list_tab()
コード例 #11
0
 def delete_cb(menuitem, bl, brush, menu):
     msg = C_(
         "brush list commands",
         "Really delete brush from disk?",
     )
     if not dialogs.confirm(menu, msg):
         return
     bl.remove_brush(brush)
     faves = bl.bm.groups[brushmanager.FAVORITES_BRUSH_GROUP]
     bl.bm.brushes_changed(faves)
コード例 #12
0
 def _remove_cb(self, menuitem):
     bl = self._brushlist
     brush = self._brush
     msg = C_(
         "brush group: context menu: remove from group",
         u"Really remove brush “{brush_name}” " u"from group “{group_name}”?",
     ).format(brush_name=brush.name, group_name=bl.group)
     if not dialogs.confirm(bl, msg):
         return
     bl.remove_brush(brush)
コード例 #13
0
ファイル: brusheditor.py プロジェクト: Griatch/dopey
 def delete_button_clicked_cb(self, button):
     """Deletes the current brush, with a confirmation dialog"""
     bm = self.app.brushmanager
     b = bm.selected_brush
     if not b.name:
         dialogs.error(self, _('No brush selected!'))
         return
     if not dialogs.confirm(self, _("Really delete brush from disk?")):
         return
     bm.select_brush(None)
     self._delete_brush(b, replacement=None)
コード例 #14
0
ファイル: brusheditor.py プロジェクト: Xananax/dopey
 def delete_button_clicked_cb(self, button):
     """Deletes the current brush, with a confirmation dialog"""
     bm = self.app.brushmanager
     b = bm.selected_brush
     if not b.name:
         dialogs.error(self, _('No brush selected!'))
         return
     if not dialogs.confirm(self, _("Really delete brush from disk?")):
         return
     bm.select_brush(None)
     self._delete_brush(b, replacement=None)
コード例 #15
0
 def _remove_cb(self, menuitem):
     bl = self._brushlist
     brush = self._brush
     msg = C_(
         "brush group: context menu: remove from group",
         u"Really remove brush “{brush_name}” "
         u"from group “{group_name}”?").format(
             brush_name=brush.name,
             group_name=bl.group,
         )
     if not dialogs.confirm(bl, msg):
         return
     bl.remove_brush(brush)
コード例 #16
0
 def on_drop_activate(self, *args):
     path, column = self.tv_fields.get_cursor()
     _iter = self.tv_fields_model.get_iter(path)
     _field_name = self.tv_fields_model.get_value(_iter, 2)
     if not dialogs.confirm(
             "Drop field",
             "Do you really want to DROP field <b>%s</b> from table <b>%s</b>"
             " in database <b>%s</b> on <b>%s</b>?" %
         (_field_name, self.table.name, self.table.db.name,
          self.table.db.host.name), None):
         return
     self.table.drop_field(_field_name)
     self.refresh()
コード例 #17
0
ファイル: QueryTab.py プロジェクト: glushko311/emma
    def on_load_query_clicked(self, button):
        d = self.emma.assign_once(
            "load dialog",
            gtk.FileChooserDialog,
            "Load query",
            self.emma.mainwindow,
            gtk.FILE_CHOOSER_ACTION_OPEN,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT),
        )

        d.set_default_response(gtk.RESPONSE_ACCEPT)
        answer = d.run()
        d.hide()
        if not answer == gtk.RESPONSE_ACCEPT:
            return

        filename = d.get_filename()
        try:
            sbuf = os.stat(filename)
        except:
            dialogs.show_message("Load query", "%s does not exists!" % filename)
            return
        if not S_ISREG(sbuf.st_mode):
            dialogs.show_message("Load query", "%s exists, but is not a file!" % filename)
            return

        size = sbuf.st_size
        _max = int(self.emma.config.get("ask_execute_query_from_disk_min_size"))
        if size > _max:
            if dialogs.confirm(
                "load query",
                """
<b>%s</b> is very big (<b>%.2fMB</b>)!
opening it in the normal query-view may need a very long time!
if you just want to execute this skript file without editing and
syntax-highlighting, i can open this file using the <b>execute file from disk</b> function.
<b>shall i do this?</b>"""
                % (filename, size / 1024.0 / 1000.0),
                self.emma.mainwindow,
            ):
                self.emma.on_execute_query_from_disk_activate(None, filename)
                return
        try:
            fp = file(filename, "rb")
            query_text = fp.read()
            fp.close()
        except:
            dialogs.show_message("Load Query", "Error reading query from file %s: %s" % (filename, sys.exc_value))
            return
        self.textview.get_buffer().set_text(query_text)
コード例 #18
0
    def on_host_popup(self, popup, item):
        """
        :param popup:
        :param item:
        :return:
        """
        path, column = self.get_cursor()
        if path:
            _iter = self.connections_model.get_iter(path)
            host = self.connections_model.get_value(_iter, 0)
        else:
            _iter = None
            host = None
        what = item.name

        if what == "refresh_host":
            host.refresh()
            self.redraw_host(host, _iter)
        elif what == "new_database":
            name = dialogs.input_dialog(
                "New database",
                "Please enter the name of the new database:",
                window=self.emma.mainwindow)
            if not name:
                return
            if host.query("Create database `%s`" % name):
                host.refresh()
                self.redraw_host(host, _iter)
        elif what == "modify_connection":
            self.connection_window.host = host
            self.connection_window.show("edit")
        elif what == "delete_connection":
            hostname = host.name.replace('&', '&amp;')
            if not dialogs.confirm(
                    "Delete host",
                    "Do you really want to drop the host <b>%s</b>?" %
                    hostname, self.emma.mainwindow):
                return
            host.close()
            self.connections_model.remove(_iter)
            if self.current_host == host:
                self.current_host = None
            del self.emma.config.config["connection_%s" % host.name]
            del host
            self.emma.config.save()
        elif what == "new_connection":
            self.connection_window.show("new")
        elif what == "show_processes":
            self.emma.main_notebook.add_process_list_tab(host)
コード例 #19
0
    def on_load_query_clicked(self, button):
        d = self.emma.assign_once("load dialog", gtk.FileChooserDialog,
                                  "Load query", self.emma.mainwindow,
                                  gtk.FILE_CHOOSER_ACTION_OPEN,
                                  (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                   gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT))

        d.set_default_response(gtk.RESPONSE_ACCEPT)
        answer = d.run()
        d.hide()
        if not answer == gtk.RESPONSE_ACCEPT:
            return

        filename = d.get_filename()
        try:
            sbuf = os.stat(filename)
        except:
            dialogs.show_message("Load query",
                                 "%s does not exists!" % filename)
            return
        if not S_ISREG(sbuf.st_mode):
            dialogs.show_message("Load query",
                                 "%s exists, but is not a file!" % filename)
            return

        size = sbuf.st_size
        _max = int(
            self.emma.config.get("ask_execute_query_from_disk_min_size"))
        if size > _max:
            if dialogs.confirm(
                    "load query", """
<b>%s</b> is very big (<b>%.2fMB</b>)!
opening it in the normal query-view may need a very long time!
if you just want to execute this skript file without editing and
syntax-highlighting, i can open this file using the <b>execute file from disk</b> function.
<b>shall i do this?</b>""" % (filename, size / 1024.0 / 1000.0),
                    self.emma.mainwindow):
                self.emma.on_execute_query_from_disk_activate(None, filename)
                return
        try:
            fp = file(filename, "rb")
            query_text = fp.read()
            fp.close()
        except:
            dialogs.show_message(
                "Load Query", "Error reading query from file %s: %s" %
                (filename, sys.exc_value))
            return
        self.textview.get_buffer().set_text(query_text)
コード例 #20
0
 def _delete_cb(self, widget):
     """Properties dialog delete callback"""
     self._dialog.hide()
     name = brushmanager.translate_group_name(self._group)
     msg = _('Really delete group "%s"?') % (name,)
     bm = self._app.brushmanager
     if not dialogs.confirm(self, msg):
         return
     bm.delete_group(self._group)
     if self._group not in bm.groups:
         self._app.workspace.hide_tool_widget(self.__gtype_name__,
                                              (self._group,))
         return
     msg = _('Group "%s" cannot be deleted. Try emptying it first.')
     dialogs.error(self, msg % (name,))
コード例 #21
0
ファイル: brushselectionwindow.py プロジェクト: sahwar/dopey
 def _delete_cb(self, widget):
     """Properties dialog delete callback"""
     self._dialog.hide()
     name = brushmanager.translate_group_name(self._group)
     msg = _('Really delete group "%s"?') % (name, )
     bm = self._app.brushmanager
     if not dialogs.confirm(self, msg):
         return
     bm.delete_group(self._group)
     if self._group not in bm.groups:
         self._app.workspace.hide_tool_widget(self.__gtype_name__,
                                              (self._group, ))
         return
     msg = _('Group "%s" cannot be deleted. Try emptying it first.')
     dialogs.error(self, msg % (name, ))
コード例 #22
0
    def on_save_result_clicked(self, button):
        d = self.emma.assign_once(
            "save results dialog",
            gtk.FileChooserDialog, "save results", self.emma.mainwindow, gtk.FILE_CHOOSER_ACTION_SAVE,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT))

        d.set_default_response(gtk.RESPONSE_ACCEPT)
        answer = d.run()
        d.hide()
        if not answer == gtk.RESPONSE_ACCEPT:
            return
        filename = d.get_filename()
        if os.path.exists(filename):
            if not os.path.isfile(filename):
                dialogs.show_message("save results", "%s already exists and is not a file!" % filename)
                return
            if not dialogs.confirm(
                    "overwrite file?",
                    "%s already exists! do you want to overwrite it?" % filename, self.emma.mainwindow):
                return
        q = self.query
        _iter = q.model.get_iter_first()
        indices = range(q.model.get_n_columns())
        field_delim = self.emma.config.get("save_result_as_csv_delim")
        line_delim = self.emma.config.get("save_result_as_csv_line_delim")
        try:
            fp = file(filename, "wb")
            for search, replace in {"\\n": "\n", "\\r": "\r", "\\t": "\t", "\\0": "\0"}.iteritems():
                field_delim = field_delim.replace(search, replace)
                line_delim = line_delim.replace(search, replace)
            while _iter:
                row = q.model.get(_iter, *indices)
                for field in row:
                    value = field
                    if value is None:
                        value = ""
                    fp.write(value.replace(field_delim, "\\" + field_delim))
                    fp.write(field_delim)
                fp.write(line_delim)
                _iter = q.model.iter_next(_iter)
            fp.close()
        except:
            dialogs.show_message("save results", "error writing query to file %s: %s" % (filename, sys.exc_value))
コード例 #23
0
ファイル: brusheditor.py プロジェクト: MeanGreanHare/mypaint
 def delete_button_clicked_cb(self, button):
     """Deletes the current brush, with a confirmation dialog"""
     bm = self.app.brushmanager
     b = bm.selected_brush
     if not b.name:
         dialogs.error(self, C_(
             'brush settings editor: delete brush: error message',
             'No brush selected!',
         ))
         return
     b_name_pp = b.name.replace('_', ' ')
     msg = C_(
         "brush settings editor: delete brush: confirm dialog question",
         "Really delete brush “{brush_name}” from disk?",
     ).format(
         brush_name = b_name_pp,
     )
     if not dialogs.confirm(self, msg):
         return
     bm.select_brush(None)
     self._delete_brush(b, replacement=None)
コード例 #24
0
ファイル: brusheditor.py プロジェクト: mmorello1/mypaint
 def delete_button_clicked_cb(self, button):
     """Deletes the current brush, with a confirmation dialog"""
     bm = self.app.brushmanager
     b = bm.selected_brush
     if not b.name:
         dialogs.error(self, C_(
             'brush settings editor: delete brush: error message',
             'No brush selected!',
         ))
         return
     b_name_pp = b.name.replace('_', ' ')
     msg = C_(
         "brush settings editor: delete brush: confirm dialog question",
         "Really delete brush “{brush_name}” from disk?",
     ).format(
         brush_name = b_name_pp,
     )
     if not dialogs.confirm(self, msg):
         return
     bm.select_brush(None)
     self._delete_brush(b, replacement=None)
コード例 #25
0
ファイル: ConnectionTreeView.py プロジェクト: Zaffy/emma
    def on_db_popup(self, popup, item):
        path, column = self.get_cursor()
        _iter = self.connections_model.get_iter(path)
        what = item.name
        db = self.connections_model.get_value(_iter, 0)

        if what == "refresh_database":
            new_tables = db.refresh()
            self.redraw_db(db, _iter, new_tables)
        elif what == "drop_database":
            if not dialogs.confirm("drop database",
                                   "do you really want to drop the <b>%s</b> database on <b>%s</b>?" % (
                                   db.name, db.host.name), self.emma.mainwindow):
                return
            host = db.host
            if host.query("drop database`%s`" % db.name):
                host.refresh()
                self.redraw_host(host, self.emma.connections_tv.get_host_iter(host))
        elif what == "new_table":
            name = dialogs.input_dialog("New table", "Please enter the name of the new table:",
                                        window=self.emma.mainwindow)
            if not name:
                return
            if db.query("create table `%s` (`%s_id` int primary key auto_increment)" % (name, name)):
                new_tables = db.refresh()
                self.redraw_db(db, self.emma.connections_tv.get_db_iter(db), new_tables)
        elif what == "check_tables":
            self.current_host = db.host
            self.current_host.select_database(db)
            self.emma.current_query.on_execute_query_clicked(
                None,
                "check table %s" % (",".join(map(lambda s: "`%s`" % s, db.tables.keys()))))
        elif what == "repair_tables":
            self.current_host = db.host
            self.current_host.select_database(db)
            self.emma.current_query.on_execute_query_clicked(
                None,
                "repair table %s" % (",".join(map(lambda s: "`%s`" % s, db.tables.keys()))))
        elif what == "list_tables":
            self.emma.main_notebook.add_tables_list_tab()
コード例 #26
0
ファイル: ConnectionTreeView.py プロジェクト: Zaffy/emma
    def on_host_popup(self, popup, item):
        path, column = self.get_cursor()
        if path:
            _iter = self.connections_model.get_iter(path)
            host = self.connections_model.get_value(_iter, 0)
        else:
            _iter = None
            host = None
        what = item.name

        if what == "refresh_host":
            host.refresh()
            self.redraw_host(host, _iter)
        elif what == "new_database":
            name = dialogs.input_dialog("New database", "Please enter the name of the new database:",
                                        window=self.emma.mainwindow)
            if not name:
                return
            if host.query("Create database `%s`" % name):
                host.refresh()
                self.redraw_host(host, _iter)
        elif what == "modify_connection":
            self.connection_window.host = host
            self.connection_window.show("edit")
        elif what == "delete_connection":
            if not dialogs.confirm("Delete host", "Do you really want to drop the host <b>%s</b>?" % host.name,
                                   self.emma.mainwindow):
                return
            host.close()
            self.connections_model.remove(_iter)
            if self.current_host == host:
                self.current_host = None
            del self.emma.config.config["connection_%s" % host.name]
            del host
            self.emma.config.save()
        elif what == "new_connection":
            self.connection_window.show("new")
        elif what == "show_processes":
            self.emma.main_notebook.add_process_list_tab(host)
コード例 #27
0
    def on_save_result_sql_clicked(self, button):
        title = "save results as sql insert script"
        d = self.emma.assign_once(
            "save results dialog",
            gtk.FileChooserDialog, title, self.emma.mainwindow, gtk.FILE_CHOOSER_ACTION_SAVE,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT))

        d.set_default_response(gtk.RESPONSE_ACCEPT)
        answer = d.run()
        d.hide()
        if not answer == gtk.RESPONSE_ACCEPT:
            return
        filename = d.get_filename()
        if os.path.exists(filename):
            if not os.path.isfile(filename):
                dialogs.show_message(title, "%s already exists and is not a file!" % filename)
                return
            if not dialogs.confirm(
                    "overwrite file?",
                    "%s already exists! do you want to overwrite it?" % filename, self.emma.mainwindow):
                return
        q = self.query
        _iter = q.model.get_iter_first()
        indices = range(q.model.get_n_columns())

        # try to guess target table name from query
        table_name = ""
        query = self.query.last_source
        result = is_query_appendable(query)
        if result:
            table_list = result.group(7)
            table_list = table_list.replace(" join ", ",")
            table_list = re.sub("(?i)(?:order[ \t\r\n]by.*|limit.*|group[ \r\n\t]by.*|order[ \r\n\t]by.*|where.*)", "",
                                table_list)
            table_list = table_list.replace("`", "")
            tables = map(lambda s: s.strip(), table_list.split(","))
            table_name = "_".join(tables)
        table_name = dialogs.input_dialog(title, "Please enter the name of the target table:", table_name,
                                          self.emma.mainwindow)
        if table_name is None:
            return
        table_name = self.emma.current_host.escape_table(table_name)

        output_row = None
        try:
            fp = file(filename, "wb")
            fp.write("insert into %s values" % table_name)
            row_delim = "\n\t"
            while _iter:
                row = q.model.get(_iter, *indices)
                if not output_row:
                    output_row = range(len(row))
                for i, field in enumerate(row):
                    if field is None:
                        field = "NULL"
                    elif not field.isdigit():
                        field = "'%s'" % q.current_host.escape(field.encode(q.encoding))
                    output_row[i] = field
                fp.write("%s(%s)" % (row_delim, ",".join(output_row)))
                row_delim = ",\n\t"
                _iter = q.model.iter_next(_iter)
            fp.write("\n;\n")
            fp.close()
        except:
            dialogs.show_message(title, "error writing to file %s: %s" % (filename, sys.exc_value))
コード例 #28
0
ファイル: QueryTab.py プロジェクト: glushko311/emma
    def on_execute_query_clicked(self, button=None, query=None):
        field_count = 0
        if not query:
            b = self.textview.get_buffer()
            text = b.get_text(b.get_start_iter(), b.get_end_iter())
        else:
            text = query

        self.current_host = host = self.current_host
        if not host:
            dialogs.show_message(
                "error executing this query!", "could not execute query, because there is no selected host!"
            )
            return

        self.current_db = self.current_db
        if self.current_db:
            host.select_database(self.current_db)
        elif host.current_db:
            if not dialogs.confirm(
                "query without selected db",
                """warning: this query tab has no database selected
                    but the host-connection already has the database '%s' selected.
                    the author knows no way to deselect this database.
                    do you want to continue?"""
                % host.current_db.name,
                self.emma.mainwindow,
            ):
                return

        update = False
        select = False
        self.editable = False
        # single popup
        self.add_record.set_sensitive(False)
        self.delete_record.set_sensitive(False)
        # per query buttons
        self.add_record.set_sensitive(False)
        self.delete_record.set_sensitive(False)
        self.apply_record.set_sensitive(False)
        self.local_search.set_sensitive(False)
        self.remove_order.set_sensitive(False)
        self.save_result.set_sensitive(False)
        self.save_result_sql.set_sensitive(False)

        affected_rows = 0
        last_insert_id = 0
        num_rows = 0

        query_time = 0
        download_time = 0
        display_time = 0
        query_count = 0
        total_start = time.time()

        # cleanup last query model and treeview
        for col in self.treeview.get_columns():
            self.treeview.remove_column(col)
        if self.model:
            self.model.clear()

        _start = 0
        while _start < len(text):
            # search query end
            query_start, end = read_query(text, _start)
            if query_start is None:
                break
            thisquery = text[query_start:end]
            print "about to execute query %r" % thisquery
            _start = end + 1

            thisquery.strip(" \r\n\t;")
            if not thisquery:
                continue  # empty query
            query_count += 1
            query_hint = re.sub("[\n\r\t ]+", " ", thisquery[:40])
            self.label.set_text("executing query %d %s..." % (query_count, query_hint))
            self.label.window.process_updates(False)

            appendable = False
            appendable_result = is_query_appendable(thisquery)
            if appendable_result:
                appendable = True
                self.editable = self.is_query_editable(thisquery, appendable_result)
            print "appendable: %s, editable: %s" % (appendable, self.editable)

            ret = host.query(thisquery, encoding=self.encoding)
            query_time += host.query_time

            # if stop on error is enabled
            if not ret:
                print "mysql error: %r" % (host.last_error,)
                message = "error at: %s" % host.last_error.replace(
                    "You have an error in your SQL syntax.  "
                    "Check the manual that corresponds to your MySQL server version for the right syntax to use near ",
                    "",
                )
                message = "error at: %s" % message.replace(
                    "You have an error in your SQL syntax; "
                    "check the manual that corresponds to your MySQL server "
                    "version for the right syntax to use near ",
                    "",
                )

                line_pos = 0
                pos = message.find("at line ")
                if pos != -1:
                    line_no = int(message[pos + 8 :])
                    while 1:
                        line_no -= 1
                        if line_no < 1:
                            break
                        p = thisquery.find("\n", line_pos)
                        if p == -1:
                            break
                        line_pos = p + 1

                i = self.textview.get_buffer().get_iter_at_offset(query_start + line_pos)

                match = re.search("error at: '(.*)'", message, re.DOTALL)
                if match and match.group(1):
                    # set focus and cursor!
                    # print "search for ->%s<-" % match.group(1)
                    pos = text.find(match.group(1), query_start + line_pos, query_start + len(thisquery))
                    if not pos == -1:
                        i.set_offset(pos)
                else:
                    match = re.match("Unknown column '(.*?')", message)
                    if match:
                        # set focus and cursor!
                        pos = thisquery.find(match.group(1))
                        if not pos == 1:
                            i.set_offset(query_start + pos)

                self.textview.get_buffer().place_cursor(i)
                self.textview.scroll_to_iter(i, 0.0)
                self.textview.grab_focus()
                self.label.set_text(re.sub("[\r\n\t ]+", " ", message))
                return

            field_count = host.handle.field_count()
            if field_count == 0:
                # query without result
                update = True
                affected_rows += host.handle.affected_rows()
                last_insert_id = host.handle.insert_id()
                continue

            # query with result
            self.append_iter = None
            self.local_search.set_sensitive(True)
            self.add_record.set_sensitive(appendable)
            self.delete_record.set_sensitive(self.editable)
            select = True
            self.last_source = thisquery
            # get sort order!
            sortable = True  # todo
            current_order = get_order_from_query(thisquery)
            sens = False
            if len(current_order) > 0:
                sens = True
            self.remove_order.set_sensitive(sens and sortable)

            sort_fields = dict()
            for c, o in current_order:
                sort_fields[c.lower()] = o
            self.label.set_text("downloading resultset...")
            self.label.window.process_updates(False)

            start_download = time.time()
            result = host.handle.store_result()
            download_time = time.time() - start_download
            if download_time < 0:
                download_time = 0

            self.label.set_text("displaying resultset...")
            self.label.window.process_updates(False)

            # store field info
            self.result_info = result.describe()
            num_rows = result.num_rows()

            for col in self.treeview.get_columns():
                self.treeview.remove_column(col)

            columns = [gobject.TYPE_STRING] * field_count
            self.model = gtk.ListStore(*columns)
            self.treeview.set_model(self.model)
            self.treeview.set_rules_hint(True)
            self.treeview.set_headers_clickable(True)
            for i in range(field_count):
                title = self.result_info[i][0].replace("_", "__").replace("[\r\n\t ]+", " ")
                text_renderer = gtk.CellRendererText()
                if self.editable:
                    text_renderer.set_property("editable", True)
                    text_renderer.connect("edited", self.on_query_change_data, i)
                l = self.treeview.insert_column_with_data_func(
                    -1, title, text_renderer, widgets.ResultCellRenders.render_mysql_string, i
                )

                col = self.treeview.get_column(l - 1)

                if self.emma.config.get_bool("result_view_column_resizable"):
                    col.set_resizable(True)
                else:
                    col.set_resizable(False)
                    col.set_min_width(int(self.emma.config.get("result_view_column_width_min")))
                    col.set_max_width(int(self.emma.config.get("result_view_column_width_max")))

                if sortable:
                    col.set_clickable(True)
                    col.connect("clicked", self.on_query_column_sort, i)
                    # set sort indicator
                    field_name = self.result_info[i][0].lower()
                    try:
                        sort_col = sort_fields[field_name]
                        col.set_sort_indicator(True)
                        if sort_col:
                            col.set_sort_order(gtk.SORT_ASCENDING)
                        else:
                            col.set_sort_order(gtk.SORT_DESCENDING)
                    except:
                        col.set_sort_indicator(False)
                else:
                    col.set_clickable(False)
                    col.set_sort_indicator(False)

            cnt = 0
            start_display = time.time()
            last_display = start_display
            for row in result.fetch_row(0):

                def to_string(f):
                    if type(f) == str:
                        f = f.decode(self.encoding, "replace")
                    elif f is None:
                        pass
                    else:
                        f = str(f)
                    return f

                self.model.append(map(to_string, row))
                cnt += 1
                if not cnt % 100 == 0:
                    continue

                now = time.time()
                if (now - last_display) < 0.2:
                    continue

                self.label.set_text("displayed %d rows..." % cnt)
                self.label.window.process_updates(False)
                last_display = now

            display_time = time.time() - start_display
            if display_time < 0:
                display_time = 0

        result = []
        if select:
            # there was a query with a result
            result.append("rows: %d" % num_rows)
            result.append("fields: %d" % field_count)
            self.save_result.set_sensitive(True)
            self.save_result_sql.set_sensitive(True)
        if update:
            # there was a query without a result
            result.append("affected rows: %d" % affected_rows)
            result.append("insert_id: %d" % last_insert_id)
        total_time = time.time() - total_start
        result.append("| total time: %.2fs (query: %.2fs" % (total_time, query_time))
        if select:
            result.append("download: %.2fs display: %.2fs" % (download_time, display_time))
        result.append(")")

        self.label.set_text(" ".join(result))
        self.emma.blob_view.tv.set_editable(self.editable)
        self.emma.blob_view.blob_update.set_sensitive(self.editable)
        self.emma.blob_view.blob_load.set_sensitive(self.editable)
        # todo update_buttons()
        gc.collect()
        return True
コード例 #29
0
    def on_execute_query_clicked(self, button=None, query=None):
        field_count = 0
        if not query:
            b = self.textview.get_buffer()
            text = b.get_text(b.get_start_iter(), b.get_end_iter())
        else:
            text = query

        self.current_host = host = self.current_host
        if not host:
            dialogs.show_message(
                "error executing this query!",
                "could not execute query, because there is no selected host!")
            return

        self.current_db = self.current_db
        if self.current_db:
            host.select_database(self.current_db)
        elif host.current_db:
            if not dialogs.confirm(
                    "query without selected db",
                    """warning: this query tab has no database selected
                    but the host-connection already has the database '%s' selected.
                    the author knows no way to deselect this database.
                    do you want to continue?""" % host.current_db.name,
                    self.emma.mainwindow):
                return

        update = False
        select = False
        self.editable = False
        # single popup
        self.add_record.set_sensitive(False)
        self.delete_record.set_sensitive(False)
        # per query buttons
        self.add_record.set_sensitive(False)
        self.delete_record.set_sensitive(False)
        self.apply_record.set_sensitive(False)
        self.local_search.set_sensitive(False)
        self.remove_order.set_sensitive(False)
        self.save_result.set_sensitive(False)
        self.save_result_sql.set_sensitive(False)

        affected_rows = 0
        last_insert_id = 0
        num_rows = 0

        query_time = 0
        download_time = 0
        display_time = 0
        query_count = 0
        total_start = time.time()

        # cleanup last query model and treeview
        for col in self.treeview.get_columns():
            self.treeview.remove_column(col)
        if self.model:
            self.model.clear()

        _start = 0
        while _start < len(text):
            # search query end
            query_start, end = read_query(text, _start)
            if query_start is None:
                break
            thisquery = text[query_start:end]
            print "about to execute query %r" % thisquery
            _start = end + 1

            thisquery.strip(" \r\n\t;")
            if not thisquery:
                continue  # empty query
            query_count += 1
            query_hint = re.sub("[\n\r\t ]+", " ", thisquery[:40])
            self.label.set_text("executing query %d %s..." %
                                (query_count, query_hint))
            self.label.window.process_updates(False)

            appendable = False
            appendable_result = is_query_appendable(thisquery)
            if appendable_result:
                appendable = True
                self.editable = self.is_query_editable(thisquery,
                                                       appendable_result)
            print "appendable: %s, editable: %s" % (appendable, self.editable)

            ret = host.query(thisquery, encoding=self.encoding)
            query_time += host.query_time

            # if stop on error is enabled
            if not ret:
                print "mysql error: %r" % (host.last_error, )
                message = "error at: %s" % host.last_error.replace(
                    "You have an error in your SQL syntax.  "
                    "Check the manual that corresponds to your MySQL server version for the right syntax to use near ",
                    "")
                message = "error at: %s" % message.replace(
                    "You have an error in your SQL syntax; "
                    "check the manual that corresponds to your MySQL server "
                    "version for the right syntax to use near ", "")

                line_pos = 0
                pos = message.find("at line ")
                if pos != -1:
                    line_no = int(message[pos + 8:])
                    while 1:
                        line_no -= 1
                        if line_no < 1:
                            break
                        p = thisquery.find("\n", line_pos)
                        if p == -1:
                            break
                        line_pos = p + 1

                i = self.textview.get_buffer().get_iter_at_offset(query_start +
                                                                  line_pos)

                match = re.search("error at: '(.*)'", message, re.DOTALL)
                if match and match.group(1):
                    # set focus and cursor!
                    #print "search for ->%s<-" % match.group(1)
                    pos = text.find(match.group(1), query_start + line_pos,
                                    query_start + len(thisquery))
                    if not pos == -1:
                        i.set_offset(pos)
                else:
                    match = re.match("Unknown column '(.*?')", message)
                    if match:
                        # set focus and cursor!
                        pos = thisquery.find(match.group(1))
                        if not pos == 1:
                            i.set_offset(query_start + pos)

                self.textview.get_buffer().place_cursor(i)
                self.textview.scroll_to_iter(i, 0.0)
                self.textview.grab_focus()
                self.label.set_text(re.sub("[\r\n\t ]+", " ", message))
                return

            field_count = host.handle.field_count()
            if field_count == 0:
                # query without result
                update = True
                affected_rows += host.handle.affected_rows()
                last_insert_id = host.handle.insert_id()
                continue

            # query with result
            self.append_iter = None
            self.local_search.set_sensitive(True)
            self.add_record.set_sensitive(appendable)
            self.delete_record.set_sensitive(self.editable)
            select = True
            self.last_source = thisquery
            # get sort order!
            sortable = True  # todo
            current_order = get_order_from_query(thisquery)
            sens = False
            if len(current_order) > 0:
                sens = True
            self.remove_order.set_sensitive(sens and sortable)

            sort_fields = dict()
            for c, o in current_order:
                sort_fields[c.lower()] = o
            self.label.set_text("downloading resultset...")
            self.label.window.process_updates(False)

            start_download = time.time()
            result = host.handle.store_result()
            download_time = time.time() - start_download
            if download_time < 0:
                download_time = 0

            self.label.set_text("displaying resultset...")
            self.label.window.process_updates(False)

            # store field info
            self.result_info = result.describe()
            num_rows = result.num_rows()

            for col in self.treeview.get_columns():
                self.treeview.remove_column(col)

            columns = [gobject.TYPE_STRING] * field_count
            self.model = gtk.ListStore(*columns)
            self.treeview.set_model(self.model)
            self.treeview.set_rules_hint(True)
            self.treeview.set_headers_clickable(True)
            for i in range(field_count):
                title = self.result_info[i][0].replace("_", "__").replace(
                    "[\r\n\t ]+", " ")
                text_renderer = gtk.CellRendererText()
                if self.editable:
                    text_renderer.set_property("editable", True)
                    text_renderer.connect("edited", self.on_query_change_data,
                                          i)
                l = self.treeview.insert_column_with_data_func(
                    -1, title, text_renderer,
                    widgets.ResultCellRenders.render_mysql_string, i)

                col = self.treeview.get_column(l - 1)

                if self.emma.config.get_bool("result_view_column_resizable"):
                    col.set_resizable(True)
                else:
                    col.set_resizable(False)
                    col.set_min_width(
                        int(
                            self.emma.config.get(
                                "result_view_column_width_min")))
                    col.set_max_width(
                        int(
                            self.emma.config.get(
                                "result_view_column_width_max")))

                if sortable:
                    col.set_clickable(True)
                    col.connect("clicked", self.on_query_column_sort, i)
                    # set sort indicator
                    field_name = self.result_info[i][0].lower()
                    try:
                        sort_col = sort_fields[field_name]
                        col.set_sort_indicator(True)
                        if sort_col:
                            col.set_sort_order(gtk.SORT_ASCENDING)
                        else:
                            col.set_sort_order(gtk.SORT_DESCENDING)
                    except:
                        col.set_sort_indicator(False)
                else:
                    col.set_clickable(False)
                    col.set_sort_indicator(False)

            cnt = 0
            start_display = time.time()
            last_display = start_display
            for row in result.fetch_row(0):

                def to_string(f):
                    if type(f) == str:
                        f = f.decode(self.encoding, "replace")
                    elif f is None:
                        pass
                    else:
                        f = str(f)
                    return f

                self.model.append(map(to_string, row))
                cnt += 1
                if not cnt % 100 == 0:
                    continue

                now = time.time()
                if (now - last_display) < 0.2:
                    continue

                self.label.set_text("displayed %d rows..." % cnt)
                self.label.window.process_updates(False)
                last_display = now

            display_time = time.time() - start_display
            if display_time < 0:
                display_time = 0

        result = []
        if select:
            # there was a query with a result
            result.append("rows: %d" % num_rows)
            result.append("fields: %d" % field_count)
            self.save_result.set_sensitive(True)
            self.save_result_sql.set_sensitive(True)
        if update:
            # there was a query without a result
            result.append("affected rows: %d" % affected_rows)
            result.append("insert_id: %d" % last_insert_id)
        total_time = time.time() - total_start
        result.append("| total time: %.2fs (query: %.2fs" %
                      (total_time, query_time))
        if select:
            result.append("download: %.2fs display: %.2fs" %
                          (download_time, display_time))
        result.append(")")

        self.label.set_text(' '.join(result))
        self.emma.blob_view.tv.set_editable(self.editable)
        self.emma.blob_view.blob_update.set_sensitive(self.editable)
        self.emma.blob_view.blob_load.set_sensitive(self.editable)
        # todo update_buttons()
        gc.collect()
        return True