/*
* This software and supporting documentation were developed by
*
* Siemens Corporate Technology
* Competence Center Knowledge Management and Business Transformation
* D-81730 Munich, Germany
*
* Authors (representing a really great team ;-) )
* Stefan B. Augustin, Thorbj�rn Hansen, Manfred Langen
*
* This software is Open Source under GNU General Public License (GPL).
* Read the text of this license in LICENSE.TXT
* or look at www.opensource.org/licenses/
*
* Once more we emphasize, that:
* THIS SOFTWARE IS MADE AVAILABLE, AS IS, WITHOUT ANY WARRANTY
* REGARDING THE SOFTWARE, ITS PERFORMANCE OR
* FITNESS FOR ANY PARTICULAR USE, FREEDOM FROM ANY COMPUTER DISEASES OR
* ITS CONFORMITY TO ANY SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND
* PERFORMANCE OF THE SOFTWARE IS WITH THE USER.
*
*/
// Parser
package mod.tsql;
import java.lang.StringBuffer;
public class Parser
{
/** Thrown by removeComments.
*
* @todo Add constructor with String parameter.
*/
public static class ParseException extends Exception {}
/** Eliminates comments.
*
* The preparser currently only eliminates comments, that is:
* everything after "--" up to newline is deleted, except inside strings.
*
* There are two kinds of strings:
* - SQL strings are delimited by single quotes. Single quotes within a SQL string are escpaed by another
* single quote.
* - Double quotes can be used to quote reserved words, e.g. to call a table "SELECT" or a column "DATE".
*
* @param aToParse An arbitrary string, intended for SQL-Statements
* @return aToParse without comments.
* @throws ParseException when closing single quote or double quote missing.
*/
static public String removeComments (String aToParse)
throws ParseException
{
boolean tInSingleQuote = false;
boolean tInDoubleQuote = false;
boolean tInComment = false;
StringBuffer tResult = new StringBuffer();
for (int i=0; i<aToParse.length(); i++) {
char c = aToParse.charAt(i);
if (tInSingleQuote) {
tResult.append(c);
if (c=='\'') {
tInSingleQuote=false;
}
} else if (tInDoubleQuote) {
tResult.append(c);
if (c == '\"') {
tInDoubleQuote=false;
}
} else if(tInComment) {
if(c=='\n') {
tResult.append('\n');
tInComment = false;
}
} else if (aToParse.startsWith("\n--", i)) {
// Sonderfall: bei "\n--" entfernen wir auch "\n".
tInComment = true;
} else if(aToParse.startsWith("--", i)) {
tInComment = true;
} else if(c == '\'') {
tInSingleQuote = true;
tResult.append(c);
} else if(c == '\"') {
tInDoubleQuote = true;
tResult.append(c);
} else {
tResult.append(c);
}
}
if(tInSingleQuote) throw new ParseException();
if(tInDoubleQuote) throw new ParseException();
return tResult.toString();
}
/** @return true if and only if aToParse ends with an unclosed string. */
public boolean insideString(String aToParse)
{
try {
removeComments(aToParse);
return false;
} catch(ParseException e) {
return true;
}
}
}