001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Nuxeo - initial API and implementation
011 *
012 * $Id$
013 */
014
015package org.nuxeo.ecm.core.query.sql;
016
017import java.io.Reader;
018import java.io.StringReader;
019
020import org.nuxeo.common.utils.ExceptionUtils;
021import org.nuxeo.ecm.core.query.QueryParseException;
022import org.nuxeo.ecm.core.query.sql.model.SQLQuery;
023import org.nuxeo.ecm.core.query.sql.parser.Scanner;
024import org.nuxeo.ecm.core.query.sql.parser.parser;
025
026/**
027 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
028 */
029public final class SQLQueryParser {
030
031    // Utility class
032    private SQLQueryParser() {
033    }
034
035    public static SQLQuery parse(Reader reader) throws QueryParseException {
036        try {
037            Scanner scanner = new Scanner(reader);
038            parser parser = new parser(scanner);
039            return (SQLQuery) parser.parse().value;
040        } catch (QueryParseException e) {
041            throw e;
042        } catch (Exception e) { // stupid CUPS API throws Exception
043            throw new QueryParseException(ExceptionUtils.runtimeException(e));
044        }
045    }
046
047    public static SQLQuery parse(String string) throws QueryParseException {
048        SQLQuery query = parse(new StringReader(string));
049        query.setQueryString(string);
050        return query;
051    }
052
053    /**
054     * Returns the string literal in a form ready to embed in an NXQL statement.
055     *
056     * @deprecated since 5.7, 5.6.0-HF08 use {{@link NXQL#escapeString} instead
057     */
058    @Deprecated
059    public static String prepareStringLiteral(String s) {
060        return NXQL.escapeString(s);
061    }
062
063}