/*
(non-Javadoc)

@see javax.persistence.EntityManager#createNativeQuery(java.lang.String)
178348
@Override
    public final Query createNativeQuery(String sqlString)
    {
        checkClosed();
        return getPersistenceDelegator().createQuery(sqlString, getPersistenceUnit());
    }
157114
Query createQuery(String jpaQuery, final String persistenceUnit)
    {
        Client client = getClient(persistenceUnit);
        EntityMetadata metadata = null;
        try
        {
            metadata = KunderaMetadataManager.getMetamodel(kunderaMetadata, client.getPersistenceUnit())
                    .getEntityMetadataMap().values().iterator().next();
        }
        catch (Exception e)
        {
            log.info("Entity metadata is null. Proceeding as Scalar Query.");
        }

        Query query = new QueryResolver().getQueryImplementation(jpaQuery, getClient(persistenceUnit)
                .getQueryImplementor(), this, metadata, persistenceUnit);
        return query;
    }
929655
public static @NotNull SqlQuery namedQuery(@NotNull @SQL String sql, @NotNull Object bean) {
        return namedQuery(sql, VariableResolver.forBean(bean));
    }
650272
public static Query create(String query) 
		throws QueryParserException
	{
		QueryTokenizer tokenizer = new QueryTokenizerImpl();
		QueryParser parser = new QueryParserImpl();

		return parser.parse(tokenizer.tokenize(query));
	}
37409
@Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Cursor result = null;

        if (!controller.hasPreinitialized()) {
            throw new IllegalStateException("Controller has not been initialized.");
        }

        int patternCode = controller.getUriMatcher().match(uri);
        MatcherPattern pattern = controller.findMatcherPattern(patternCode);
        if (pattern == null) {
            throw new IllegalArgumentException("unknown uri : " + uri.toString());
        }

        Parameter parameter = new Parameter(uri, projection, selection, selectionArgs, sortOrder);
        SQLiteDatabase db = this.getHelper().getReadableDatabase();

        result = onQuery(this.getHelper(), db, pattern, parameter);
        if (result != null) {
            this.onQueryCompleted(result, uri, pattern, parameter);
        }
        return result;
    }
785610
@Override
    public List executeQuery(Class clazz, List<String> relationalField, boolean isNative, String cqlQuery) {
        ResultSet rSet = (ResultSet) this.execute(cqlQuery, null);
        if (clazz == null) {
		// XXX
            if (isNative)
                return iterateAndReturnNative(rSet);
            return iterateAndReturn(rSet);
        }
        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);
        return iterateAndReturn(rSet, metadata);
    }
1116252
@Override
    public <T> TypedQuery<T> createQuery(CriteriaQuery<T> arg0) {
        try
        {
            return ivEm.createQuery(arg0);
        } finally
        {
            if (!inJTATransaction())
            {
                ivEm.clear();
            }
        }
    }
1327819
public QueryHint<NamedNativeQuery<T>> getOrCreateHint()
   {
      List<Node> nodeList = childNode.get("hint");
      if (nodeList != null &&  nodeList.size() > 0)
      {
         return new QueryHintImpl<NamedNativeQuery<T>>(this, "hint", childNode, nodeList.get(0));
      }
      return createHint();
   }
1091093
@Override
    public Node visitQuery(SqlBaseParser.QueryContext context)
    {
        Query body = (Query) visit(context.queryNoWith());

        return new Query(
                getLocation(context),
                visitIfPresent(context.with(), With.class),
                body.getQueryBody(),
                body.getOrderBy(),
                body.getLimit());
    }
382551
public boolean isNative(String name)
    {
        QueryWrapper wrapper = namedNativeQueries != null && name != null ? namedNativeQueries.get(name) : null;
        return wrapper != null ? wrapper.isNativeQuery() : false;
    }
346902
KeyFactory newNativeKeyFactory() {
    KeyFactory keyFactory = datastore.newKeyFactory();
    String namespace = Tenant.getNamespace();
    if (namespace != null) {
      keyFactory.setNamespace(namespace);
    }
    return keyFactory;
  }
641282
public String query(String query) {
        try {
            Connection conn = this.tx().getConnection();
            ObjectNode result = this.mapper.createObjectNode();
            ArrayNode dataNode = this.mapper.createArrayNode();
            ArrayNode metaNode = this.mapper.createArrayNode();
            Statement statement = conn.createStatement();
            if (logger.isDebugEnabled()) {
                logger.debug(query);
            }
            ResultSet rs = statement.executeQuery(query);
            ResultSetMetaData rsmd = rs.getMetaData();
            boolean first = true;
            while (rs.next()) {
                int numColumns = rsmd.getColumnCount();
                ObjectNode obj = this.mapper.createObjectNode();
                for (int i = 1; i < numColumns + 1; i++) {
                    String columnName = rsmd.getColumnLabel(i);
                    int type = rsmd.getColumnType(i);
                    //make sure to obtain array using getArray()
                    //At least in H2, this makes a difference...
                    Object o = type == Types.ARRAY ? rs.getArray(i) : rs.getObject(i);
                    this.sqlDialect.putJsonObject(obj, columnName, type, o);
                    if (first) {
                        this.sqlDialect.putJsonMetaObject(this.mapper, metaNode, columnName, type, o);
                    }
                }
                first = false;
                dataNode.add(obj);
            }
            result.set("data", dataNode);
            result.set("meta", metaNode);
            return result.toString();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            this.tx().rollback();
        }
    }
869905
SQLExecutableQuery generateSourceQuery(IntermediateQuery intermediateQuery)
			throws OntopReformulationException {

		IQ normalizedQuery = normalizeIQ(intermediateQuery);

		DatalogProgram queryProgram = iq2DatalogTranslator.translate(normalizedQuery);

		for (CQIE cq : queryProgram.getRules()) {
			datalogNormalizer.addMinimalEqualityToLeftOrNestedInnerJoin(cq);
		}
		log.debug("Program normalized for SQL translation:\n" + queryProgram);

		MutableQueryModifiers queryModifiers = queryProgram.getQueryModifiers();
		isDistinct = queryModifiers.hasModifiers() && queryModifiers.isDistinct();
		isOrderBy = queryModifiers.hasModifiers() && !queryModifiers.getSortConditions().isEmpty();

		DatalogDependencyGraphGenerator depGraph = new DatalogDependencyGraphGenerator(queryProgram.getRules());
		Multimap<Predicate, CQIE> ruleIndex = depGraph.getRuleIndex();
		List<Predicate> predicatesInBottomUp = depGraph.getPredicatesInBottomUp();
		List<Predicate> extensionalPredicates = depGraph.getExtensionalPredicates();

		ImmutableList<String> signature = intermediateQuery.getProjectionAtom().getArguments().stream()
				.map(Variable::getName)
				.collect(ImmutableCollectors.toList());

		final String resultingQuery;
		String queryString = generateQuery(signature, ruleIndex, predicatesInBottomUp, extensionalPredicates);
		if (queryModifiers.hasModifiers()) {
			//List<Variable> groupby = queryProgram.getQueryModifiers().getGroupConditions();
			// if (!groupby.isEmpty()) {
			// subquery += "\n" + sqladapter.sqlGroupBy(groupby, "") + " " +
			// havingStr + "\n";
			// }
			// List<OrderCondition> conditions =
			// query.getQueryModifiers().getSortConditions();

			long limit = queryModifiers.getLimit();
			long offset = queryModifiers.getOffset();
			List<OrderCondition> conditions = queryModifiers.getSortConditions();

			final String modifier;
			if (!conditions.isEmpty()) {
				modifier = sqladapter.sqlOrderByAndSlice(conditions, OUTER_VIEW_NAME, limit, offset) + "\n";
			}
			else if (limit != -1 || offset != -1) {
				modifier = sqladapter.sqlSlice(limit, offset) + "\n";
			}
			else {
				modifier = "";
			}

			resultingQuery = "SELECT *\n" +
					"FROM " + inBrackets("\n" + queryString + "\n") + " " + OUTER_VIEW_NAME + "\n" +
					modifier;
		}
		else {
			resultingQuery = queryString;
		}
		return new SQLExecutableQuery(resultingQuery, signature);
	}
874960
@Override
    public SqlQuery createSqlQuery(String sql) {
        Assert.hasText(sql, "sql must has text");
        return ebeanServer.createSqlQuery(sql);
    }
738743
@SuppressWarnings("unchecked")
	static void findByNativeQuery(final EntityManager em, final String query)
    {

        Query q = em.createNativeQuery(query, Tweets.class);

        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();
        ThriftClient client = (ThriftClient) clients.get("twissandra");
        client.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);

        logger.info("[On Find Tweets by CQL3]");
        List<Tweets> tweets = q.getResultList();

        System.out.println("#######################START##########################################");
        logger.info("\t\t User's total tweets:" + tweets.size());
        onPrintTweets(tweets);
        logger.info("\n");
        // logger.info("First tweet:" users.get(0).getTweets().);
        System.out.println("#######################END############################################");
        logger.info("\n");
    }
630498
public static String createResultCountQuery(String query) {
        String resultCountQueryString = null;

        int select = query.toLowerCase().indexOf("select");
        int from = query.toLowerCase().indexOf("from");
        if (select == -1 || from == -1) {
            return null;
        }

        resultCountQueryString = "select count(" + query.substring(select + 6, from).trim() + ") " + query.substring(from);

        // remove order by
        // TODO: remove more parts
        if (resultCountQueryString.toLowerCase().contains("order by")) {
            resultCountQueryString = resultCountQueryString.substring(0, resultCountQueryString.toLowerCase().indexOf("order by"));
        }

        log.debug("Created query for counting results '{}'", resultCountQueryString);
        return resultCountQueryString;
    }
465197
List createAndExecuteQuery(CouchDBQueryInterpreter interpreter)
    {
        EntityMetadata m = interpreter.getMetadata();
        List results = new ArrayList();
        try
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());
            StringBuilder q = new StringBuilder();
            String _id = CouchDBConstants.URL_SEPARATOR + m.getSchema().toLowerCase() + CouchDBConstants.URL_SEPARATOR
                    + CouchDBConstants.DESIGN + m.getTableName() + CouchDBConstants.VIEW;
            if ((interpreter.isIdQuery() && !interpreter.isRangeQuery() && interpreter.getOperator() == null)
                    || interpreter.isQueryOnCompositeKey())
            {
                Object object = null;
                if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))
                {
                    EmbeddableType embeddableType = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());
                    if (KunderaCoreUtils.countNonSyntheticFields(m.getIdAttribute().getBindableJavaType()) == interpreter
                            .getKeyValues().size())
                    {
                        Object key = CouchDBObjectMapper.getObjectFromJson(gson.toJsonTree(interpreter.getKeyValues())
                                .getAsJsonObject(), m.getIdAttribute().getBindableJavaType(), embeddableType
                                .getAttributes());
                        object = find(m.getEntityClazz(), key);
                        if (object != null)
                        {
                            results.add(object);
                        }
                        return results;
                    }
                    else if (m.getIdAttribute().getName().equals(interpreter.getKeyName())
                            && interpreter.getKeyValues().size() == 1)
                    {
                        object = find(m.getEntityClazz(), interpreter.getKeyValue());
                        if (object != null)
                        {
                            results.add(object);
                        }
                        return results;
                    }
                    else
                    {
                        log.error("There should be each and every field of composite key.");
                        throw new QueryHandlerException("There should be each and every field of composite key.");
                    }
                }
                object = find(m.getEntityClazz(), interpreter.getKeyValue());
                if (object != null)
                {
                    results.add(object);
                }
                return results;
            }

            // creating query.
            _id = createQuery(interpreter, m, q, _id);

            if (interpreter.getLimit() > 0)
            {
                q.append("&limit=" + interpreter.getLimit());
            }
            if (interpreter.isDescending())
            {
                q.append("&descending=" + false);
            }

            // execute query.
            executeQueryAndGetResults(q, _id, m, results, interpreter);
        }
        catch (Exception e)
        {
            log.error("Error while executing query, Caused by {}.", e);
            throw new KunderaException(e);
        }
        return results;
    }