fixed additional catches block bug
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.quantum.sql / src / com / quantum / actions / ExecuteAction.java
index 295cfa3..26f869c 100644 (file)
 package com.quantum.actions;
 
+import java.io.IOException;
 import java.sql.Connection;
 import java.sql.SQLException;
+import java.util.Arrays;
+import java.util.List;
 import java.util.Vector;
 
+import com.quantum.ImageStore;
 import com.quantum.Messages;
 import com.quantum.QuantumPlugin;
 import com.quantum.model.Bookmark;
-import com.quantum.sql.MultiSQLServer;
-import com.quantum.sql.SQLParser;
-import com.quantum.sql.SQLResults;
-import com.quantum.view.LogProxy;
+import com.quantum.model.BookmarkCollection;
+import com.quantum.model.DisplayableComparator;
+import com.quantum.sql.parser.SQLParser;
 import com.quantum.view.SQLQueryView;
-import com.quantum.view.bookmark.BookmarkNode;
-import com.quantum.view.bookmark.BookmarkView;
-import com.quantum.view.tableview.DefaultSizes;
-import com.quantum.view.tableview.TableView;
 
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.action.IAction;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.ActionContributionItem;
+import org.eclipse.jface.action.IMenuCreator;
 import org.eclipse.jface.action.IStatusLineManager;
+import org.eclipse.jface.action.Separator;
 import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.events.MenuAdapter;
+import org.eclipse.swt.events.MenuEvent;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
 import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IViewActionDelegate;
-import org.eclipse.ui.IViewPart;
 
 /**
  * Executes a query from the QueryView
  *
  * @author panic
  */
-public class ExecuteAction extends BaseSQLAction implements IViewActionDelegate {
-       SQLQueryView view;
-       String execute1 = Messages.getString("ExecuteAction.Executing_Query3"); //$NON-NLS-1$
-       String execute2 = Messages.getString("ExecuteAction.Executing_Query2"); //$NON-NLS-1$
-    
-       public ExecuteAction() {
+public class ExecuteAction extends BaseExecuteAction implements IMenuCreator {
+       
+private static final String LAST_USED_BOOKMARK_PREFERENCE = ExecuteAction.class.getName() + ".bookmark";
+       private SQLQueryView view;
+       
+       public ExecuteAction(SQLQueryView view) {
+               this.view = view;
                setActionDefinitionId("com.quantum.actions.ExecuteAction");
-               setImageDescriptor(QuantumPlugin.getImageDescriptor("play.gif"));
-               setText(Messages.getString("sqlqueryview.executeQuery"));
-               setToolTipText(Messages.getString("sqlqueryview.executeQuery"));
+               setImageDescriptor(ImageStore.getImageDescriptor(ImageStore.PLAY));
+               initTextAndToolTip();
+               setMenuCreator(this);
        }
-    
-       public void init(IViewPart view) {
-               this.view = (SQLQueryView) view;
+
+       /**
+        * 
+        */
+       private void initTextAndToolTip() {
+               Bookmark lastUsedBookmark = getLastUsedBookmark();
+               if (lastUsedBookmark == null) {
+                       setText(Messages.getString(ExecuteAction.class, "textNoBookmark"));
+                       setToolTipText(Messages.getString(ExecuteAction.class, "textNoBookmark"));
+               } else {
+                       Object[] parameters = new Object[] { lastUsedBookmark.getName() };
+                       setText(Messages.getString(ExecuteAction.class, "text", parameters));
+                       setToolTipText(Messages.getString(ExecuteAction.class, "text", parameters));
+               }
        }
 
-       public void run(IAction action) {
-               run();
+       protected Bookmark getBookmark() {
+               Bookmark lastUsedBookmark = getLastUsedBookmark();
+               return lastUsedBookmark == null ? super.getBookmark() : lastUsedBookmark;
        }
-    
-       public void run() {
-               BookmarkNode current = BookmarkView.getInstance().getCurrentBookmark();
-               if (current == null)
-               {
-                        MessageDialog.openInformation(
-                          view.getSite().getShell(),"Sorry","Please select a bookmark to use as connection.");
-                        return;
-               }                  
-               getStatusLineManager().setErrorMessage(null);
-               Connection con = getConnection();
-               getStatusLineManager().setMessage(execute1);
-               MultiSQLServer server = MultiSQLServer.getInstance();
-               getStatusLineManager().setMessage(Messages.getString("ExecuteAction.Parsing_sql_script3")); //$NON-NLS-1$
-               Vector queries = new Vector();
-               String viewQuery = view.getQuery();
-               // We parse the executable units to send to the JDBC driver
-               queries = SQLParser.parse(viewQuery);
-               for (int i = 0; i < queries.size(); i++) {
-                       String query = (String) queries.elementAt(i);
-                       System.out.println(query);
-               }
-               int resultCount = 0;
-               int resultUpdateCount = 0;
-               int errorCount = 0;
-               int resultsDisplayed = 0;
-               double startTime = 0.0; // stores the time when query is started
-               double queryDuration= 0.0; // stores query's execution time
+       protected void execute(Bookmark bookmark, Connection connection) 
+                       throws IOException, CoreException, SQLException {
                
-               IProgressMonitor progressBar = getStatusLineManager().getProgressMonitor();
-               progressBar.beginTask("queries", queries.size());
-               for (int i = 0; i < queries.size(); i++) {
-                       if (i % 2 == 0) {
-                               getStatusLineManager().setMessage(execute1);
-                       } else {
-                               getStatusLineManager().setMessage(execute2);
+               try {
+                       boolean autoCommitPreference = this.view.isAutoCommitPreference();
+                       boolean changed = false;
+                       if (connection.getAutoCommit() != autoCommitPreference) {
+                               connection.setAutoCommit(autoCommitPreference);
+                               changed = true;
                        }
-                  
-                  String query = (String) queries.elementAt(i);
-                  System.out.println(">" + query + "<"); //$NON-NLS-1$ //$NON-NLS-2$
-                  if (con != null && !query.equals("")) { //$NON-NLS-1$
-       
-                       SQLResults results;
-                       try {
-                               startTime = System.currentTimeMillis(); // Start the measure of execution time
-                               results = server.execute(con, query, 1, DefaultSizes.PAGE_SIZE, DefaultSizes.MAX_COLUMN_SIZE);
-                               queryDuration = (System.currentTimeMillis() - startTime)/1000; // calculate the execution time (in seconds)                              
-                               current.getBookmark().addQuery(query);
-                       } catch (SQLException e) {
-                                errorCount++;
-                               LogProxy log = LogProxy.getInstance();
-                               log.addText(
-                                       LogProxy.ERROR,
-                                       "Error Executing: " + query + ":" + e.toString(), e); //$NON-NLS-1$ //$NON-NLS-2$
-                               MessageDialog.openConfirm(view.getSite().getShell(), "Database returned error", e.getLocalizedMessage());  //$NON-NLS-1$ 
-                               continue;
+                       
+                       super.execute(bookmark, connection);
+                       
+                       if (changed) {
+                               MessageDialog.openInformation(getShell(), 
+                                               Messages.getString(ExecuteAction.class, "autocommitTitle"), 
+                                               Messages.getString(ExecuteAction.class, "autocommitMessage", 
+                                                               new Object[] { bookmark.getName() }));
                        }
-                          resultCount++;
-                          if (results.isResultSet()) {
-                                TableView.getInstance().loadQuery(current.getBookmark(), results);
-                                resultsDisplayed++;
-                          } else {
-                                int count = results.getUpdateCount();
-                                if (count > 0) {
-                                       resultUpdateCount += results.getUpdateCount();
-                                }
-                          }
-                   }
-System.out.println(getStatusLineManager().getProgressMonitor() == null ? "not found" : "found!");
-                       progressBar.worked(i);
-//                 view.setProgress(i + 1, queries.size());
-               }
-               progressBar.done();
-               String message = Messages.getString("ExecuteAction.Done") + "(" + //$NON-NLS-1$ //$NON-NLS-2$
-                                               resultCount + Messages.getString("ExecuteAction.QueriesExecuted") +  //$NON-NLS-1$
-                                               resultUpdateCount + Messages.getString("ExecuteAction.RowsUpdated") +  //$NON-NLS-1$
-                                               resultsDisplayed + Messages.getString("ExecuteAction.ResultsDisplayed") +  //$NON-NLS-1$
-                                               errorCount + Messages.getString("ExecuteAction.Errors") +  //$NON-NLS-1$
-                                               queryDuration  + Messages.getString("ExecutAction.TimeExec") + ")"; //$NON-NLS-1$ //$NON-NLS-2$
-               if (errorCount > 0) {
-                       getStatusLineManager().setErrorMessage(
-                                       QuantumPlugin.getImage("stop.gif"), message);
-               } else {
-                       getStatusLineManager().setMessage(
-                                       QuantumPlugin.getImage("success.gif"), message);
+               } finally {
+                       QuantumPlugin.getDefault().getPreferenceStore().setValue(
+                                       LAST_USED_BOOKMARK_PREFERENCE, bookmark.getName());
+                       initTextAndToolTip();
                }
        }
+       /**
+        * @return
+        */
+       protected List getQueries() {
+               getStatusLineManager().setMessage(
+                               Messages.getString(ExecuteAction.class, "parsing")); //$NON-NLS-1$
+               Vector queries = SQLParser.parse(view.getQuery());
+               return queries;
+       }
 
        /**
         * @return
         */
-       private IStatusLineManager getStatusLineManager() {
+       protected IStatusLineManager getStatusLineManager() {
                return this.view.getViewSite().getActionBars().getStatusLineManager();
        }
 
-       public void selectionChanged(IAction action, ISelection selection) {
+       protected Shell getShell() {
+               return this.view.getViewSite().getShell();
+       }
+
+       public void dispose() {
        }
-       protected Bookmark getBookmark() {
-               BookmarkNode current = BookmarkView.getInstance().getCurrentBookmark();
-               return current.getBookmark();
+
+       public Menu getMenu(Control parent) {
+               Menu menu = new Menu(parent);
+               /**
+                * Add listener to repopulate the menu each time
+                * it is shown because the list of bookmarks may have changed.
+                */
+               menu.addMenuListener(new MenuAdapter() {
+                       public void menuShown(MenuEvent e) {
+                               Menu menu = (Menu)e.widget;
+                               MenuItem[] items = menu.getItems();
+                               for (int i=0; i < items.length; i++) {
+                                       items[i].dispose();
+                               }
+                               fillMenu(menu);
+                       }
+               });
+               return menu;
        }
 
-       /* (non-Javadoc)
-        * @see com.quantum.actions.BaseSQLAction#getShell()
+       public Menu getMenu(Menu parent) {
+               // never called...
+               return null;
+       }
+
+       protected void fillMenu(Menu menu) {
+               Bookmark lastUsedBookmark = getLastUsedBookmark();
+               
+               if (lastUsedBookmark != null) {
+                       createSubAction(menu, lastUsedBookmark);
+                       Separator separator = new Separator();
+                       separator.fill(menu, -1);
+               }
+               
+               Bookmark[] bookmarks = BookmarkCollection.getInstance().getBookmarks();
+               Arrays.sort(bookmarks, new DisplayableComparator());
+               for (int i = 0, length = bookmarks == null ? 0 : bookmarks.length; i < length; i++) {
+                       final Bookmark bookmark = bookmarks[i];
+                       createSubAction(menu, bookmark);
+               }
+       }
+
+
+
+       /**
+        * @return
         */
-       protected Shell getShell() {
-               return this.view.getViewSite().getShell();
+       private Bookmark getLastUsedBookmark() {
+               String lastUsedName = QuantumPlugin.getDefault().getPreferenceStore().getString(
+                               LAST_USED_BOOKMARK_PREFERENCE);
+               Bookmark lastUsedBookmark = lastUsedName == null 
+                               ? null 
+                               : BookmarkCollection.getInstance().find(lastUsedName);
+               return lastUsedBookmark;
+       }
+
+
+
+       /**
+        * @param menu
+        * @param bookmark
+        */
+       private void createSubAction(Menu menu, final Bookmark bookmark) {
+               Action action = new Action() {
+                       public void run() {
+                               ExecuteAction.this.execute(bookmark);
+                       }
+               };
+               action.setImageDescriptor(ImageStore.getImageDescriptor(ImageStore.BOOKMARK));
+               
+               // The last '@' sign is treated specially, so if the 
+               // bookmark name contains an '@', then add an extra one to the end
+               if (bookmark.getName().indexOf('@') >= 0) {
+                       action.setText(bookmark.getName() + '@');
+               } else {
+                       action.setText(bookmark.getName());
+               }
+               ActionContributionItem item = new ActionContributionItem(action);
+               item.fill(menu, -1);
        }
 }