package com.quantum.sql.parser;

import java.util.Vector;


public class SQLParser {

	/**
	 * Parses a query string into executable units.
	 * @param query
	 * @return a Vector of Strings, with the individual executable units.
	 */
	public static Vector parse(String query) {
			Vector commands = new Vector();
			Vector groups = new Vector();
		try {
			Vector tokens = SQLLexx.parse(query);
			StringBuffer buffer = new StringBuffer();
			StringBuffer groupBuffer = new StringBuffer();
			for (int i = 0; i < tokens.size(); i++) {
				Token t = (Token) tokens.elementAt(i);
				if (t.getType() == Token.COMMENT) {
					// ignore comments
				} else if (t.getType() == Token.SEPARATOR) {
					groupBuffer.append(t.getValue());
					String newCommand = buffer.toString().trim();
					if (!newCommand.equals("")) { //$NON-NLS-1$
						commands.addElement(newCommand);
					}
					buffer = new StringBuffer();
				} else {	
					// We append the tokens to the buffer until it's a separator or group.
					buffer.append(t.getValue());
					groupBuffer.append(t.getValue());
				}
			}
			String newCommand = buffer.toString().trim();
			if (!newCommand.equals("")) { //$NON-NLS-1$
				commands.addElement(newCommand);
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
		Vector result = new Vector();
		result.addAll(groups);
		result.addAll(commands);
		return result;
	}
}