Added SQL proposals
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / phpeditor / php / PHPCompletionProcessor.java
index ac3f814..7881cea 100644 (file)
@@ -32,11 +32,12 @@ import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparat
 import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine;
 import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine;
 import net.sourceforge.phpdt.internal.ui.text.template.IdentifierEngine;
-import net.sourceforge.phpdt.internal.ui.text.template.IdentifierProposal;
+import net.sourceforge.phpdt.internal.ui.text.template.SQLProposal;
 import net.sourceforge.phpdt.internal.ui.text.template.TemplateEngine;
 import net.sourceforge.phpeclipse.IPreferenceConstants;
 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
+import net.sourceforge.phpeclipse.overlaypages.Util;
 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
 import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
 import org.eclipse.core.resources.IFile;
@@ -56,7 +57,6 @@ import org.eclipse.jface.text.contentassist.IContextInformationValidator;
 import org.eclipse.swt.graphics.Image;
 import org.eclipse.ui.IEditorPart;
 import org.eclipse.ui.IFileEditorInput;
-import net.sourceforge.phpeclipse.overlaypages.Util;
 import com.quantum.model.Bookmark;
 import com.quantum.model.BookmarkCollection;
 import com.quantum.model.NotConnectedException;
@@ -133,6 +133,27 @@ public class PHPCompletionProcessor implements IContentAssistProcessor {
       fPosition = position;
     }
   };
+  private class TableName {
+    String fTableName;
+    TableName() {
+      fTableName = null;
+    }
+    /**
+     * @return Returns the tableName.
+     */
+    public String getTableName() {
+      if (fTableName==null) {
+        return "<!--no-table-->";
+      }
+      return fTableName;
+    }
+    /**
+     * @param tableName The tableName to set.
+     */
+    public void setTableName(String tableName) {
+      fTableName = tableName;
+    }
+  }
   private char[] fProposalAutoActivationSet;
   protected IContextInformationValidator fValidator = new Validator();
   private TemplateEngine fTemplateEngine;
@@ -175,7 +196,7 @@ public class PHPCompletionProcessor implements IContentAssistProcessor {
         contextInformationPosition);
   }
   private int getLastToken(ITextViewer viewer, int completionPosition,
-      PHPUnitContext context) {
+      PHPUnitContext context, TableName tableName) {
     IDocument document = viewer.getDocument();
     int start = context.getStart();
     int end = context.getEnd();
@@ -206,13 +227,11 @@ public class PHPCompletionProcessor implements IContentAssistProcessor {
           System.out.println(startText);
         }
         int token = ITerminalSymbols.TokenNameEOF;
-        
-        token = getLastSQLToken(startText);
-        
+//        token = getLastSQLToken(startText);
+        tableName.setTableName(getLastSQLTableName(startText));
         Scanner scanner = ToolFactory.createScanner(false, false, false);
         scanner.setSource(startText.toCharArray());
         scanner.setPHPMode(true);
-        
         int beforeLastToken = ITerminalSymbols.TokenNameEOF;
         int lastToken = ITerminalSymbols.TokenNameEOF;
         try {
@@ -245,6 +264,114 @@ public class PHPCompletionProcessor implements IContentAssistProcessor {
     return lastSignificantToken;
   }
   
+  String getSQLTableName(String sqlText, int start) {
+    int tableNameStart = -1;
+    int currentCharacterPosition = start+1;
+    char ch;
+    try {
+      while(true) {
+      ch = sqlText.charAt(currentCharacterPosition++);
+      if (tableNameStart==-1 && Character.isJavaIdentifierStart(ch)) {
+        tableNameStart = currentCharacterPosition-1;
+      } else {
+        if (!Character.isJavaIdentifierPart(ch)) {
+          return sqlText.substring(tableNameStart, currentCharacterPosition-1);
+        } 
+      }
+      }
+    } catch (IndexOutOfBoundsException e) {
+      if (tableNameStart>=0) {
+        return sqlText.substring(tableNameStart, currentCharacterPosition-1);
+      }
+    }
+    return "";
+  }
+  private String getLastSQLTableName(String startText) {
+    int token;
+    // scan for sql identifiers
+    char ch = ' ';
+    int currentSQLPosition = startText.length();
+    int identEnd = -1;
+    String ident = null;
+    boolean whiteSpace = true;
+    try {
+      while (true) {
+        ch = startText.charAt(--currentSQLPosition);
+        if (ch >= 'A' && ch <= 'Z') {
+          if (identEnd < 0) {
+            identEnd = currentSQLPosition + 1;
+          }
+        } else if (ch >= 'a' && ch <= 'z') {
+          if (identEnd < 0) {
+            identEnd = currentSQLPosition + 1;
+          }
+        } else if (identEnd >= 0) {
+          ident = startText.substring(currentSQLPosition + 1, identEnd);
+          // select -- from -- where --
+          // update -- set -- where --
+          // insert into -- ( -- ) values ( -- )
+          if (ident.length() >= 4 && ident.length() <= 6) {
+            ident = ident.toLowerCase();
+            switch (ident.length()) {
+//              case 3 :
+//                if (ident.equals("set")) {
+//                  //                  System.out.println("set");
+//                  token = ITerminalSymbols.TokenNameSQLset;
+//                  return token;
+//                }
+//                break;
+              case 4 :
+                if (ident.equals("from")) {
+                  //                  System.out.println("from");
+                  token = ITerminalSymbols.TokenNameSQLfrom;
+                  return getSQLTableName(startText, identEnd);
+                } else if (ident.equals("into")) {
+                  //                System.out.println("into");
+                  token = ITerminalSymbols.TokenNameSQLinto;
+                  return getSQLTableName(startText, identEnd);
+                }
+                break;
+//              case 5 :
+//                if (ident.equals("where")) {
+//                  //                  System.out.println("where");
+//                  token = ITerminalSymbols.TokenNameSQLwhere;
+//                  return token;
+//                }
+//                break;
+              case 6 :
+//                if (ident.equals("select")) {
+//                  //                  System.out.println("select");
+//                  token = ITerminalSymbols.TokenNameSQLselect;
+//                  return token;
+//                } else if (ident.equals("insert")) {
+//                  //                  System.out.println("insert");
+//                  token = ITerminalSymbols.TokenNameSQLinsert;
+//                  return token;
+//                } else 
+                if (ident.equals("update")) {
+                  //                  System.out.println("update");
+                  token = ITerminalSymbols.TokenNameSQLupdate;
+                  return getSQLTableName(startText, identEnd);
+                } 
+//                else if (ident.equals("values")) {
+//                  //                System.out.println("values");
+//                  token = ITerminalSymbols.TokenNameSQLvalues;
+//                  return token;
+//                }
+                break;
+            }
+          }
+          whiteSpace = false;
+          identEnd = -1;
+        } else if (Character.isWhitespace(ch)) {
+        } else {
+          whiteSpace = false;
+        }
+      }
+    } catch (IndexOutOfBoundsException e) {
+    }
+    return "<!--no-table-->";
+  }
   /**
    * Detect the last significant SQL token in the text before the completion
    * 
@@ -279,44 +406,45 @@ public class PHPCompletionProcessor implements IContentAssistProcessor {
             switch (ident.length()) {
               case 3 :
                 if (ident.equals("set")) {
-//                  System.out.println("set");
+                  //                  System.out.println("set");
                   token = ITerminalSymbols.TokenNameSQLset;
                   return token;
                 }
                 break;
               case 4 :
                 if (ident.equals("from")) {
-//                  System.out.println("from");
+                  //                  System.out.println("from");
                   token = ITerminalSymbols.TokenNameSQLfrom;
+                  //getSQLTableName();
                   return token;
                 } else if (ident.equals("into")) {
-//                System.out.println("into");
+                  //                System.out.println("into");
                   token = ITerminalSymbols.TokenNameSQLinto;
                   return token;
                 }
                 break;
               case 5 :
                 if (ident.equals("where")) {
-//                  System.out.println("where");
+                  //                  System.out.println("where");
                   token = ITerminalSymbols.TokenNameSQLwhere;
                   return token;
                 }
                 break;
               case 6 :
                 if (ident.equals("select")) {
-//                  System.out.println("select");
+                  //                  System.out.println("select");
                   token = ITerminalSymbols.TokenNameSQLselect;
                   return token;
                 } else if (ident.equals("insert")) {
-//                  System.out.println("insert");
+                  //                  System.out.println("insert");
                   token = ITerminalSymbols.TokenNameSQLinsert;
                   return token;
                 } else if (ident.equals("update")) {
-//                  System.out.println("update");
+                  //                  System.out.println("update");
                   token = ITerminalSymbols.TokenNameSQLupdate;
                   return token;
                 } else if (ident.equals("values")) {
-//                System.out.println("values");
+                  //                System.out.println("values");
                   token = ITerminalSymbols.TokenNameSQLvalues;
                   return token;
                 }
@@ -334,7 +462,6 @@ public class PHPCompletionProcessor implements IContentAssistProcessor {
     }
     return ITerminalSymbols.TokenNameEOF;
   }
-  
   private ICompletionProposal[] internalComputeCompletionProposals(
       ITextViewer viewer, int offset, int contextOffset) {
     IDocument document = viewer.getDocument();
@@ -363,7 +490,8 @@ public class PHPCompletionProcessor implements IContentAssistProcessor {
         document, offset, 0);
     PHPUnitContext context = (PHPUnitContext) phpContextType.createContext();
     String prefix = context.getKey();
-    int lastSignificantToken = getLastToken(viewer, offset, context);
+    TableName sqlTable = new TableName();
+    int lastSignificantToken = getLastToken(viewer, offset, context, sqlTable);
     boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER)
         || (lastSignificantToken == ITerminalSymbols.TokenNameVariable)
         || (lastSignificantToken == ITerminalSymbols.TokenNamenew);
@@ -426,7 +554,7 @@ public class PHPCompletionProcessor implements IContentAssistProcessor {
               IPreferenceConstants.PHP_BOOKMARK_DEFAULT);
           if (bookmarkString != null && !bookmarkString.equals("")) {
             Bookmark bookmark = sqlBookMarks.find(bookmarkString);
-            ArrayList list = new ArrayList();
+            ArrayList sqlList = new ArrayList();
             if (bookmark != null && !bookmark.isConnected()) {
               new ConnectionUtil().connect(bookmark, null);
             }
@@ -434,43 +562,68 @@ public class PHPCompletionProcessor implements IContentAssistProcessor {
               try {
                 Connection connection = bookmark.getConnection();
                 DatabaseMetaData metaData = connection.getMetaData();
+                
                 if (metaData != null) {
                   int start = context.getStart();
                   int end = context.getEnd();
+                  String foundSQLTableName = sqlTable.getTableName();
+                  String tableName;
+                  String columnName;
+                  String prefixWithoutDollar = prefix;
+                  boolean isDollarPrefix = false;
+                  if (prefix.length() > 0 && prefix.charAt(0) == '$') {
+                    prefixWithoutDollar = prefix.substring(1);
+                    isDollarPrefix = true;
+                  }
                   IRegion region = new Region(start, end - start);
-                  ResultSet set = metaData.getTables(null, null, prefix + "%",
-                      null);
-                  while (set.next()) {
-                    //                  String tempSchema = set.getString("TABLE_SCHEM");
-                    //                  tempSchema = (tempSchema == null) ? "" :
-                    // tempSchema.trim();
-                    String tableName = set.getString("TABLE_NAME");
-                    tableName = (tableName == null) ? "" : tableName.trim();
-                    if (tableName != null && tableName.length() > 0) {
-                      list.add(tableName);
+                  ResultSet set; 
+                  if (!isDollarPrefix) {
+                    set = metaData.getTables(null, null, prefixWithoutDollar
+                        + "%", null);
+                    while (set.next()) {
+                      //                  String tempSchema = set.getString("TABLE_SCHEM");
+                      //                  tempSchema = (tempSchema == null) ? "" :
+                      // tempSchema.trim();
+                      tableName = set.getString("TABLE_NAME");
+                      tableName = (tableName == null) ? "" : tableName.trim();
+                      if (tableName != null && tableName.length() > 0) {
+                        sqlList.add(new SQLProposal(tableName, context, region,
+                            viewer, PHPUiImages.get(PHPUiImages.IMG_TABLE)));
+                      }
                     }
+                    set.close();
                   }
-                  set.close();
-                  set = metaData.getColumns(null, null, "%", prefix + "%");
+                  set = metaData.getColumns(null, null, "%",
+                      prefixWithoutDollar + "%");
+                  SQLProposal sqlProposal;
                   while (set.next()) {
-                    String tableName = set.getString("COLUMN_NAME");
-                    tableName = (tableName == null) ? "" : tableName.trim();
-                    if (tableName != null && tableName.length() > 0) {
-                      list.add(tableName);
-                    }
+                    columnName = set.getString("COLUMN_NAME");
+                    columnName = (columnName == null) ? "" : columnName.trim();
                     tableName = set.getString("TABLE_NAME");
                     tableName = (tableName == null) ? "" : tableName.trim();
-                    if (tableName != null && tableName.length() > 0) {
-                      list.add(tableName);
+                    if (tableName != null && tableName.length() > 0
+                        && columnName != null && columnName.length() > 0) {
+                      if (isDollarPrefix) {
+                        sqlProposal = new SQLProposal(tableName,
+                            "$" + columnName, context, region, viewer,
+                            PHPUiImages.get(PHPUiImages.IMG_COLUMN));
+                      } else {
+                        sqlProposal = new SQLProposal(tableName, columnName,
+                            context, region, viewer, PHPUiImages
+                                .get(PHPUiImages.IMG_COLUMN));
+                      }
+                      if (tableName.equals(foundSQLTableName)) {
+                        sqlProposal.setRelevance(90);
+                      } else if (tableName.indexOf(foundSQLTableName)>=0) {
+                        sqlProposal.setRelevance(75);
+                      }
+                      sqlList.add(sqlProposal);
                     }
                   }
                   set.close();
-                  sqlResults = new IPHPCompletionProposal[list.size()];
-                  for (int i = 0; i < list.size(); i++) {
-                    sqlResults[i] = new IdentifierProposal(
-                        (String) list.get(i), context, region, viewer,
-                        PHPUiImages.get(PHPUiImages.IMG_FUN), PHPUiImages
-                            .get(PHPUiImages.IMG_VAR));
+                  sqlResults = new IPHPCompletionProposal[sqlList.size()];
+                  for (int i = 0; i < sqlList.size(); i++) {
+                    sqlResults[i] = (SQLProposal) sqlList.get(i);
                   }
                 }
               } catch (NotConnectedException e) {