Quantum version 2.4.1
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / actions / PHPOpenSQLTableEditorAction.java
1 /*******************************************************************************
2  * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This
3  * program and the accompanying materials are made available under the terms of
4  * the Common Public License v1.0 which accompanies this distribution, and is
5  * available at http://www.eclipse.org/legal/cpl-v10.html
6  * 
7  * Contributors: Klaus Hartlage - www.eclipseproject.de
8  ******************************************************************************/
9 package net.sourceforge.phpeclipse.actions;
10
11 import java.sql.Connection;
12 import java.sql.DatabaseMetaData;
13 import java.sql.ResultSet;
14 import java.sql.SQLException;
15 import java.util.ArrayList;
16
17 import net.sourceforge.phpeclipse.IPreferenceConstants;
18 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
19 import net.sourceforge.phpeclipse.overlaypages.Util;
20 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
21
22 import org.eclipse.core.resources.IContainer;
23 import org.eclipse.core.resources.IFile;
24 import org.eclipse.core.resources.IProject;
25 import org.eclipse.core.runtime.CoreException;
26 import org.eclipse.core.runtime.Path;
27 import org.eclipse.jface.action.IAction;
28 import org.eclipse.jface.text.BadLocationException;
29 import org.eclipse.jface.text.IDocument;
30 import org.eclipse.jface.text.ITextSelection;
31 import org.eclipse.jface.text.TextSelection;
32 import org.eclipse.jface.viewers.ISelection;
33 import org.eclipse.jface.viewers.LabelProvider;
34 import org.eclipse.jface.window.Window;
35 import org.eclipse.swt.graphics.Point;
36 import org.eclipse.ui.IEditorActionDelegate;
37 import org.eclipse.ui.IEditorPart;
38 import org.eclipse.ui.IFileEditorInput;
39 import org.eclipse.ui.IViewPart;
40 import org.eclipse.ui.IWorkbenchPage;
41 import org.eclipse.ui.IWorkbenchWindow;
42 import org.eclipse.ui.PartInitException;
43 import org.eclipse.ui.actions.ActionDelegate;
44 import org.eclipse.ui.dialogs.ListSelectionDialog;
45 import org.eclipse.ui.internal.dialogs.ListContentProvider;
46
47 import com.quantum.QuantumPlugin;
48 import com.quantum.adapters.DatabaseAdapter;
49 import com.quantum.model.Bookmark;
50 import com.quantum.model.BookmarkCollection;
51 import com.quantum.model.Entity;
52 import com.quantum.model.EntityFactory;
53 import com.quantum.model.NotConnectedException;
54 import com.quantum.sql.MultiSQLServer;
55 import com.quantum.sql.SQLResultSetCollection;
56 import com.quantum.sql.SQLResultSetResults;
57 import com.quantum.sql.SQLResults;
58 import com.quantum.ui.dialog.ExceptionDisplayDialog;
59 import com.quantum.util.connection.ConnectionUtil;
60 import com.quantum.view.tableview.TableView;
61
62 public class PHPOpenSQLTableEditorAction extends ActionDelegate implements
63     IEditorActionDelegate {
64
65   private IWorkbenchWindow fWindow;
66
67   private PHPEditor fEditor;
68
69   private IProject fProject;
70
71   public void dispose() {
72   }
73
74   public void init(IWorkbenchWindow window) {
75     this.fWindow = window;
76   }
77
78   public void selectionChanged(IAction action, ISelection selection) {
79     if (!selection.isEmpty()) {
80       if (selection instanceof TextSelection) {
81         action.setEnabled(true);
82       } else if (fWindow.getActivePage() != null
83           && fWindow.getActivePage().getActivePart() != null) {
84         //
85       }
86     }
87   }
88
89   private IWorkbenchPage getActivePage() {
90     fWindow = fEditor.getEditorSite()
91         .getWorkbenchWindow();
92     IWorkbenchPage page = fWindow.getActivePage();
93     return page;
94   }
95
96   public IContainer getWorkingLocation(IFileEditorInput editorInput) {
97     if (editorInput == null || editorInput.getFile() == null) {
98       return null;
99     }
100     return editorInput.getFile().getParent();
101   }
102
103   private IFile getIncludeFile(IProject project, IFileEditorInput editorInput,
104       String relativeFilename) {
105     //          IContainer container = getWorkingLocation(editorInput);
106     //          String fullPath = project.getLocation().toString();
107     Path path = new Path(relativeFilename);
108     IFile file = project.getFile(path);
109     return file;
110   }
111
112   public void run(IAction action) {
113     if (fEditor == null) {
114       IEditorPart targetEditor = fWindow.getActivePage().getActiveEditor();
115       if (targetEditor != null && (targetEditor instanceof PHPEditor)) {
116         fEditor = (PHPEditor) targetEditor;
117       }
118     }
119     if (fEditor != null) {
120       //                        TableView view = TableView.getInstance();
121
122       //                        determine the current Project from a (file-based) Editor
123       fWindow = fEditor.getEditorSite().getWorkbenchWindow();
124       IFile f = ((IFileEditorInput) fEditor.getEditorInput()).getFile();
125       fProject = f.getProject();
126
127       ITextSelection selection = (ITextSelection) fEditor
128           .getSelectionProvider().getSelection();
129       IDocument doc = fEditor.getDocumentProvider().getDocument(
130           fEditor.getEditorInput());
131       int pos = selection.getOffset();
132       //  System.out.println(selection.getText());
133       String tableName = getSQLTableName(doc, pos);
134
135       IViewPart viewPart = null;
136       String view = "com.quantum.view.tableview.TableView";
137       try {
138         IWorkbenchPage page = QuantumPlugin.getDefault().getActivePage();
139         viewPart = page.findView(view);
140         if (viewPart == null) {
141           viewPart = page.showView(view);
142         }
143         page.bringToTop(viewPart);
144         getTables((TableView) viewPart, fProject, tableName);
145       } catch (PartInitException e) {
146         e.printStackTrace();
147       }
148
149     }
150   }
151
152   public void setActiveEditor(IAction action, IEditorPart targetEditor) {
153     if (targetEditor != null && (targetEditor instanceof PHPEditor)) {
154       fEditor = (PHPEditor) targetEditor;
155     }
156   }
157
158   private String getSQLTableName(IDocument doc, int pos) {
159     Point word = null;
160     int start = -1;
161     int end = -1;
162
163     try {
164
165       int position = pos;
166       char character;
167
168       while (position >= 0) {
169         character = doc.getChar(position);
170         if (Character.isWhitespace(character) || (character == '\"')
171             || (character == '\'') || (character == '\r')
172             || (character == '\n'))
173           break;
174         --position;
175       }
176
177       start = position;
178
179       position = pos;
180       int length = doc.getLength();
181
182       while (position < length) {
183         character = doc.getChar(position);
184         if (Character.isWhitespace(character) || (character == '\"')
185             || (character == '\'') || (character == '\r')
186             || (character == '\n'))
187           break;
188         ++position;
189       }
190
191       start++;
192       end = position;
193
194       if (end > start)
195         word = new Point(start, end - start);
196
197     } catch (BadLocationException x) {
198     }
199
200     if (word != null) {
201       try {
202         return doc.get(word.x, word.y);
203       } catch (BadLocationException e) {
204       }
205     }
206     return "";
207   }
208
209   public void getTables(TableView tableView, IProject project, String tableName) {
210     // Get The Database bookmark from the Quantum SQL plugin:
211     BookmarkCollection sqlBookMarks = BookmarkCollection.getInstance();
212     if (sqlBookMarks != null) {
213       String bookmarkString = Util.getMiscProjectsPreferenceValue(project,
214           IPreferenceConstants.PHP_BOOKMARK_DEFAULT);
215       if (bookmarkString != null && !bookmarkString.equals("")) {
216         Bookmark bookmark = sqlBookMarks.find(bookmarkString);
217         ArrayList sqlList = new ArrayList();
218         if (bookmark != null && !bookmark.isConnected()) {
219           new ConnectionUtil().connect(bookmark, null);
220         }
221         if (bookmark != null && bookmark.isConnected()) {
222           try {
223             Connection connection = bookmark.getConnection();
224             DatabaseMetaData metaData = connection.getMetaData();
225             ConnectionUtil connectionUtil = new ConnectionUtil();
226             Entity entity;
227             DatabaseAdapter adapter;
228
229             if (metaData != null) {
230               String columnName;
231               String prefixWithoutDollar = tableName;
232               if (prefixWithoutDollar.charAt(0) == '$') {
233                 prefixWithoutDollar = prefixWithoutDollar.substring(1);
234               }
235               ResultSet set;
236               set = metaData.getTables(null, null, "%" + prefixWithoutDollar
237                   + "%", null);
238               while (set.next()) {
239                 tableName = set.getString("TABLE_NAME");
240                 tableName = (tableName == null) ? "" : tableName.trim();
241                 if (tableName != null && tableName.length() > 0) {
242                   sqlList.add(tableName);
243                 }
244               }
245               set.close();
246               EntityFactory entityFactory = EntityFactory.getInstance();
247               if (sqlList.size() == 1) {
248                 adapter = bookmark.getAdapter();
249                 entity = entityFactory.create(bookmark, null, (String) sqlList
250                     .get(0), Entity.TABLE_TYPE);
251                 String query = adapter.getTableQuery(entity.getQualifiedName());
252
253                 try {
254                   SQLResults results = MultiSQLServer.getInstance().execute(
255                       bookmark, connectionUtil.connect(bookmark, fWindow.getShell()),  
256                       entity, query);
257
258                   if (results != null && results.isResultSet()) {
259                     SQLResultSetCollection.getInstance().addSQLResultSet(
260                         (SQLResultSetResults) results);
261                   }
262                 } catch (SQLException e) {
263                   ExceptionDisplayDialog.openError(fWindow.getShell(), null, null, e);
264                 }
265                 //                                                              tableView.loadTable(entityFactory.create(
266                 //                                                                              bookmark, null,
267                 //                                                                              (String) sqlList.get(0),
268                 //                                                                              Entity.TABLE_TYPE));
269               } else if (sqlList.size() > 1) {
270                 ListSelectionDialog listSelectionDialog = new ListSelectionDialog(
271                     PHPeclipsePlugin.getDefault().getWorkbench()
272                         .getActiveWorkbenchWindow().getShell(), sqlList,
273                     new ListContentProvider(), new LabelProvider(),
274                     "Select the SQL table to open.");
275                 listSelectionDialog.setTitle("Multiple tablenames found");
276                 if (listSelectionDialog.open() == Window.OK) {
277                   Object[] locations = listSelectionDialog.getResult();
278                   if (locations != null) {
279                     for (int i = 0; i < locations.length; i++) {
280                       adapter = bookmark.getAdapter();
281                       entity = entityFactory.create(bookmark, null,
282                           (String) locations[i], Entity.TABLE_TYPE);
283                       String query = adapter.getTableQuery(entity
284                           .getQualifiedName());
285
286                       try {
287                         SQLResults results = MultiSQLServer.getInstance()
288                             .execute(bookmark,
289                                 connectionUtil.connect(bookmark, fWindow.getShell()),
290                                 entity, query);
291
292                         if (results != null && results.isResultSet()) {
293                           SQLResultSetCollection.getInstance().addSQLResultSet(
294                               (SQLResultSetResults) results);
295                         }
296                       } catch (SQLException e) {
297                         ExceptionDisplayDialog.openError(fWindow.getShell(), null, null, e);
298                       }
299
300                       //                                                                                        tableView
301                       //                                                                                                        .loadTable(entityFactory
302                       //                                                                                                                        .create(
303                       //                                                                                                                                        bookmark,
304                       //                                                                                                                                        null,
305                       //                                                                                                                                        (String) locations[i],
306                       //                                                                                                                                        Entity.TABLE_TYPE));
307                     }
308
309                   }
310                 }
311               }
312             }
313           } catch (NotConnectedException e) {
314             // ignore this - not mission critical
315           } catch (SQLException e) {
316             e.printStackTrace();
317           }
318         }
319       }
320     }
321   }
322
323 }