use of lucee.runtime.type.QueryColumn in project Lucee by lucee.
the class AxisCaster method toLuceeType.
public static Object toLuceeType(PageContext pc, String customType, Object value) throws PageException {
pc = ThreadLocalPageContext.get(pc);
if (pc != null && value instanceof Pojo) {
if (!StringUtil.isEmpty(customType)) {
Component cfc = toComponent(pc, (Pojo) value, customType, null);
if (cfc != null)
return cfc;
}
/*
// try package/class name as component name
String compPath=value.getClass().getName();
Component cfc = toComponent(pc, (Pojo)value, compPath, null);
if(cfc!=null) return cfc;
// try class name as component name
compPath=ListUtil.last(compPath, '.');
cfc = toComponent(pc, (Pojo)value, compPath, null);
if(cfc!=null) return cfc;
*/
}
if (value instanceof Date || value instanceof Calendar) {
// do not change to caster.isDate
return Caster.toDate(value, null);
}
if (value instanceof Object[]) {
Object[] arr = (Object[]) value;
if (!ArrayUtil.isEmpty(arr)) {
boolean allTheSame = true;
// byte
if (arr[0] instanceof Byte) {
for (int i = 1; i < arr.length; i++) {
if (!(arr[i] instanceof Byte)) {
allTheSame = false;
break;
}
}
if (allTheSame) {
byte[] bytes = new byte[arr.length];
for (int i = 0; i < arr.length; i++) {
bytes[i] = Caster.toByteValue(arr[i]);
}
return bytes;
}
}
}
}
if (value instanceof Byte[]) {
Byte[] arr = (Byte[]) value;
if (!ArrayUtil.isEmpty(arr)) {
byte[] bytes = new byte[arr.length];
for (int i = 0; i < arr.length; i++) {
bytes[i] = arr[i].byteValue();
}
return bytes;
}
}
if (value instanceof byte[]) {
return value;
}
if (Decision.isArray(value)) {
Array a = Caster.toArray(value);
int len = a.size();
Object o;
String ct;
for (int i = 1; i <= len; i++) {
o = a.get(i, null);
if (o != null) {
ct = customType != null && customType.endsWith("[]") ? customType.substring(0, customType.length() - 2) : null;
a.setEL(i, toLuceeType(pc, ct, o));
}
}
return a;
}
if (value instanceof Map) {
Struct sct = new StructImpl();
Iterator it = ((Map) value).entrySet().iterator();
Map.Entry entry;
while (it.hasNext()) {
entry = (Entry) it.next();
sct.setEL(Caster.toString(entry.getKey()), toLuceeType(pc, null, entry.getValue()));
}
return sct;
// return StructUtil.copyToStruct((Map)value);
}
if (isQueryBean(value)) {
QueryBean qb = (QueryBean) value;
String[] strColumns = qb.getColumnList();
Object[][] data = qb.getData();
int recorcount = data.length;
Query qry = new QueryImpl(strColumns, recorcount, "QueryBean");
QueryColumn[] columns = new QueryColumn[strColumns.length];
for (int i = 0; i < columns.length; i++) {
columns[i] = qry.getColumn(strColumns[i]);
}
int row;
for (row = 1; row <= recorcount; row++) {
for (int i = 0; i < columns.length; i++) {
columns[i].set(row, toLuceeType(pc, null, data[row - 1][i]));
}
}
return qry;
}
if (Decision.isQuery(value)) {
Query q = Caster.toQuery(value);
int recorcount = q.getRecordcount();
String[] strColumns = q.getColumns();
QueryColumn col;
int row;
for (int i = 0; i < strColumns.length; i++) {
col = q.getColumn(strColumns[i]);
for (row = 1; row <= recorcount; row++) {
col.set(row, toLuceeType(pc, null, col.get(row, null)));
}
}
return q;
}
return value;
}
use of lucee.runtime.type.QueryColumn in project Lucee by lucee.
the class AxisCaster method toQueryBean.
private static QueryBean toQueryBean(TypeMapping tm, Object value, Set<Object> done) throws PageException {
Query query = Caster.toQuery(value);
int recordcount = query.getRecordcount();
String[] columnList = query.getColumns();
QueryColumn[] columns = new QueryColumn[columnList.length];
Object[][] data = new Object[recordcount][columnList.length];
for (int i = 0; i < columnList.length; i++) {
columns[i] = query.getColumn(columnList[i]);
}
int row;
for (row = 1; row <= recordcount; row++) {
for (int i = 0; i < columns.length; i++) {
data[row - 1][i] = _toAxisType(tm, null, null, null, null, columns[i].get(row, null), done);
}
}
QueryBean qb = new QueryBean();
qb.setColumnList(columnList);
qb.setData(data);
return qb;
}
use of lucee.runtime.type.QueryColumn in project Lucee by lucee.
the class Query method doEndTag.
@Override
public int doEndTag() throws PageException {
if (hasChangedPSQ)
pageContext.setPsq(orgPSQ);
String strSQL = bodyContent.getString().trim();
if (strSQL.isEmpty())
throw new DatabaseException("no sql string defined, inside query tag", null, null, null);
try {
// cannot use attribute params and queryparam tag
if (!items.isEmpty() && params != null)
throw new DatabaseException("you cannot use the attribute params and sub tags queryparam at the same time", null, null, null);
// create SQL
SQL sql;
if (params != null) {
if (params instanceof Argument)
sql = QueryParamConverter.convert(strSQL, (Argument) params);
else if (Decision.isArray(params))
sql = QueryParamConverter.convert(strSQL, Caster.toArray(params));
else if (Decision.isStruct(params))
sql = QueryParamConverter.convert(strSQL, Caster.toStruct(params));
else
throw new DatabaseException("value of the attribute [params] has to be a struct or a array", null, null, null);
} else {
sql = items.isEmpty() ? new SQLImpl(strSQL) : new SQLImpl(strSQL, items.toArray(new SQLItem[items.size()]));
}
// lucee.runtime.type.Query query=null;
QueryResult queryResult = null;
String cacheHandlerId = null;
String cacheId = null;
long exe = 0;
boolean useCache = (cachedWithin != null) || (cachedAfter != null);
CacheHandler cacheHandler = null;
if (useCache) {
cacheId = CacheHandlerCollectionImpl.createId(sql, datasource != null ? datasource.getName() : null, username, password, returntype);
CacheHandlerCollectionImpl coll = (CacheHandlerCollectionImpl) pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_QUERY, null);
cacheHandler = coll.getInstanceMatchingObject(cachedWithin, null);
if (cacheHandler == null && cachedAfter != null)
cacheHandler = coll.getTimespanInstance(null);
if (cacheHandler != null) {
// cacheHandlerId specifies to queryResult the cacheType and therefore whether the query is cached or
cacheHandlerId = cacheHandler.id();
if (cacheHandler instanceof CacheHandlerPro) {
CacheItem cacheItem = ((CacheHandlerPro) cacheHandler).get(pageContext, cacheId, (cachedWithin != null) ? cachedWithin : cachedAfter);
if (cacheItem instanceof QueryResultCacheItem)
queryResult = ((QueryResultCacheItem) cacheItem).getQueryResult();
} else {
// FUTURE this else block can be removed when all cache handlers implement CacheHandlerPro
CacheItem cacheItem = cacheHandler.get(pageContext, cacheId);
if (cacheItem instanceof QueryResultCacheItem) {
QueryResultCacheItem queryCachedItem = (QueryResultCacheItem) cacheItem;
Date cacheLimit = cachedAfter;
if (cacheLimit == null || queryCachedItem.isCachedAfter(cacheLimit))
queryResult = queryCachedItem.getQueryResult();
}
}
} else {
List<String> patterns = pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_QUERY, null).getPatterns();
throw new ApplicationException("cachedwithin value [" + cachedWithin + "] is invalid, valid values are for example [" + ListUtil.listToList(patterns, ", ") + "]");
}
// query=pageContext.getQueryCache().getQuery(pageContext,sql,datasource!=null?datasource.getName():null,username,password,cachedafter);
}
// cache not found, process and cache result if needed
if (queryResult == null) {
// QoQ
if ("query".equals(dbtype)) {
lucee.runtime.type.Query q = executeQoQ(sql);
if (returntype == RETURN_TYPE_ARRAY)
// TODO this should be done in queryExecute itself so we not have to convert afterwards
queryResult = QueryArray.toQueryArray(q);
else if (returntype == RETURN_TYPE_STRUCT) {
if (columnName == null)
throw new ApplicationException("attribute columnKey is required when return type is set to struct");
// TODO this should be done in queryExecute itself so we not have to convert
queryResult = QueryStruct.toQueryStruct(q, columnName);
// afterwards
} else
queryResult = (QueryResult) q;
} else // ORM and Datasource
{
long start = System.nanoTime();
Object obj;
if ("orm".equals(dbtype) || "hql".equals(dbtype))
obj = executeORM(sql, returntype, ormoptions);
else
obj = executeDatasoure(sql, result != null, pageContext.getTimeZone());
if (obj instanceof QueryResult) {
queryResult = (QueryResult) obj;
} else {
if (setReturnVariable) {
rtn = obj;
} else if (!StringUtil.isEmpty(name)) {
pageContext.setVariable(name, obj);
}
if (result != null) {
Struct sct = new StructImpl();
sct.setEL(KeyConstants._cached, Boolean.FALSE);
long time = System.nanoTime() - start;
sct.setEL(KeyConstants._executionTime, Caster.toDouble(time / 1000000));
sct.setEL(KeyConstants._executionTimeNano, Caster.toDouble(time));
sct.setEL(KeyConstants._SQL, sql.getSQLString());
if (Decision.isArray(obj)) {
} else
sct.setEL(KeyConstants._RECORDCOUNT, Caster.toDouble(1));
pageContext.setVariable(result, sct);
} else
setExecutionTime((System.nanoTime() - start) / 1000000);
return EVAL_PAGE;
}
}
if (cachedWithin != null) {
CacheItem cacheItem = QueryResultCacheItem.newInstance(queryResult, tags, datasource, null);
if (cacheItem != null)
cacheHandler.set(pageContext, cacheId, cachedWithin, cacheItem);
}
exe = queryResult.getExecutionTime();
} else {
queryResult.setCacheType(cacheHandlerId);
}
if (pageContext.getConfig().debug() && debug) {
boolean logdb = ((ConfigImpl) pageContext.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_DATABASE);
if (logdb) {
boolean debugUsage = DebuggerImpl.debugQueryUsage(pageContext, queryResult);
DebuggerImpl di = (DebuggerImpl) pageContext.getDebugger();
di.addQuery(debugUsage ? queryResult : null, datasource != null ? datasource.getName() : null, name, sql, queryResult.getRecordcount(), getPageSource(), exe);
}
}
if (setReturnVariable) {
rtn = queryResult;
} else if ((queryResult.getColumncount() + queryResult.getRecordcount()) > 0 && !StringUtil.isEmpty(name)) {
pageContext.setVariable(name, queryResult);
}
// Result
if (result != null) {
Struct sct = new StructImpl();
sct.setEL(KeyConstants._cached, Caster.toBoolean(queryResult.isCached()));
if ((queryResult.getColumncount() + queryResult.getRecordcount()) > 0) {
String list = ListUtil.arrayToList(queryResult instanceof lucee.runtime.type.Query ? ((lucee.runtime.type.Query) queryResult).getColumnNamesAsString() : CollectionUtil.toString(queryResult.getColumnNames(), false), ",");
sct.setEL(KeyConstants._COLUMNLIST, list);
}
int rc = queryResult.getRecordcount();
if (rc == 0)
rc = queryResult.getUpdateCount();
sct.setEL(KeyConstants._RECORDCOUNT, Caster.toDouble(rc));
sct.setEL(KeyConstants._executionTime, Caster.toDouble(queryResult.getExecutionTime() / 1000000));
sct.setEL(KeyConstants._executionTimeNano, Caster.toDouble(queryResult.getExecutionTime()));
sct.setEL(KeyConstants._SQL, sql.getSQLString());
// GENERATED KEYS
lucee.runtime.type.Query qi = Caster.toQuery(queryResult, null);
if (qi != null) {
lucee.runtime.type.Query qryKeys = qi.getGeneratedKeys();
if (qryKeys != null) {
StringBuilder generatedKey = new StringBuilder(), sb;
Collection.Key[] columnNames = qryKeys.getColumnNames();
QueryColumn column;
for (int c = 0; c < columnNames.length; c++) {
column = qryKeys.getColumn(columnNames[c]);
sb = new StringBuilder();
int size = column.size();
for (int row = 1; row <= size; row++) {
if (row > 1)
sb.append(',');
sb.append(Caster.toString(column.get(row, null)));
}
if (sb.length() > 0) {
sct.setEL(columnNames[c], sb.toString());
if (generatedKey.length() > 0)
generatedKey.append(',');
generatedKey.append(sb);
}
}
if (generatedKey.length() > 0)
sct.setEL(GENERATEDKEY, generatedKey.toString());
}
}
// sqlparameters
SQLItem[] params = sql.getItems();
if (params != null && params.length > 0) {
Array arr = new ArrayImpl();
sct.setEL(SQL_PARAMETERS, arr);
for (int i = 0; i < params.length; i++) {
arr.append(params[i].getValue());
}
}
pageContext.setVariable(result, sct);
} else // cfquery.executiontime
{
setExecutionTime(exe / 1000000);
}
// listener
((ConfigWebImpl) pageContext.getConfig()).getActionMonitorCollector().log(pageContext, "query", "Query", exe, queryResult);
// log
Log log = pageContext.getConfig().getLog("datasource");
if (log.getLogLevel() >= Log.LEVEL_INFO) {
log.info("query tag", "executed [" + sql.toString().trim() + "] in " + DecimalFormat.call(pageContext, exe / 1000000D) + " ms");
}
} catch (PageException pe) {
// log
pageContext.getConfig().getLog("datasource").error("query tag", pe);
throw pe;
} finally {
((PageContextImpl) pageContext).setTimestampWithTSOffset(previousLiteralTimestampWithTSOffset);
if (tmpTZ != null) {
pageContext.setTimeZone(tmpTZ);
}
}
return EVAL_PAGE;
}
use of lucee.runtime.type.QueryColumn in project Lucee by lucee.
the class HSQLDBHandler method addTable.
/**
* adds a table to the memory database
* @param conn
* @param pc
* @param name name of the new table
* @param query data source for table
* @throws SQLException
* @throws PageException
*/
private static void addTable(Connection conn, PageContext pc, String name, Query query, boolean doSimpleTypes, ArrayList<String> usedTables) throws SQLException, PageException {
Statement stat;
usedTables.add(name);
stat = conn.createStatement();
Key[] keys = CollectionUtil.keys(query);
int[] types = query.getTypes();
int[] innerTypes = toInnerTypes(types);
// CREATE STATEMENT
String comma = "";
StringBuilder create = new StringBuilder("CREATE TABLE " + name + " (");
StringBuilder insert = new StringBuilder("INSERT INTO " + name + " (");
StringBuilder values = new StringBuilder("VALUES (");
for (int i = 0; i < keys.length; i++) {
String key = keys[i].getString();
String type = (doSimpleTypes) ? "VARCHAR_IGNORECASE" : toUsableType(types[i]);
create.append(comma + key);
create.append(" ");
create.append(type);
insert.append(comma + key);
values.append(comma + "?");
comma = ",";
}
create.append(")");
insert.append(")");
values.append(")");
stat.execute(create.toString());
PreparedStatement prepStat = conn.prepareStatement(insert.toString() + values.toString());
// INSERT STATEMENT
// HashMap integerTypes=getIntegerTypes(types);
int count = query.getRecordcount();
QueryColumn[] columns = new QueryColumn[keys.length];
for (int i = 0; i < keys.length; i++) {
columns[i] = query.getColumn(keys[i]);
}
for (int y = 0; y < count; y++) {
for (int i = 0; i < keys.length; i++) {
int type = innerTypes[i];
Object value = columns[i].get(y + 1, null);
// print.out("*** "+type+":"+Caster.toString(value));
if (doSimpleTypes) {
prepStat.setObject(i + 1, Caster.toString(value));
} else {
if (value == null)
prepStat.setNull(i + 1, types[i]);
else if (type == BINARY)
prepStat.setBytes(i + 1, Caster.toBinary(value));
else if (type == DATE) {
// print.out(new java.util.Date(new Date(DateCaster.toDateAdvanced(value,pc.getTimeZone()).getTime()).getTime()));
prepStat.setTimestamp(i + 1, (value.equals("")) ? null : new Timestamp(DateCaster.toDateAdvanced(query.getAt(keys[i], y + 1), pc.getTimeZone()).getTime()));
// prepStat.setObject(i+1,Caster.toDate(value,null));
// prepStat.setDate(i+1,(value==null || value.equals(""))?null:new Date(DateCaster.toDateAdvanced(value,pc.getTimeZone()).getTime()));
} else if (type == TIME)
prepStat.setTime(i + 1, (value.equals("")) ? null : new Time(DateCaster.toDateAdvanced(query.getAt(keys[i], y + 1), pc.getTimeZone()).getTime()));
else if (type == TIMESTAMP)
prepStat.setTimestamp(i + 1, (value.equals("")) ? null : new Timestamp(DateCaster.toDateAdvanced(query.getAt(keys[i], y + 1), pc.getTimeZone()).getTime()));
else if (type == DOUBLE)
prepStat.setDouble(i + 1, (value.equals("")) ? 0 : Caster.toDoubleValue(query.getAt(keys[i], y + 1)));
else if (type == INT)
prepStat.setLong(i + 1, (value.equals("")) ? 0 : Caster.toLongValue(query.getAt(keys[i], y + 1)));
else if (type == STRING)
prepStat.setObject(i + 1, Caster.toString(value));
}
}
prepStat.execute();
}
}
use of lucee.runtime.type.QueryColumn in project Lucee by lucee.
the class UndefinedImpl method getScopeFor.
/**
* returns the scope that contains a specific key
* @param key
* @return
*/
public Collection getScopeFor(Collection.Key key, Scope defaultValue) {
Object rtn = null;
if (checkArguments) {
rtn = local.get(key, NullSupportHelper.NULL());
if (rtn != NullSupportHelper.NULL())
return local;
rtn = argument.getFunctionArgument(key, NullSupportHelper.NULL());
if (rtn != NullSupportHelper.NULL())
return argument;
}
// get data from queries
if (allowImplicidQueryCall && pc.getCurrentTemplateDialect() == CFMLEngine.DIALECT_CFML && !qryStack.isEmpty()) {
QueryColumn qc = qryStack.getColumnFromACollection(key);
if (qc != null)
return (Query) qc.getParent();
}
// variable
rtn = variable.get(key, NullSupportHelper.NULL());
if (rtn != NullSupportHelper.NULL()) {
return variable;
}
// thread scopes
if (pc.hasFamily()) {
Threads t = (Threads) pc.getThreadScope(key, NullSupportHelper.NULL());
if (rtn != NullSupportHelper.NULL())
return t;
}
// get a scope value (only cfml is searcing additional scopes)
if (pc.getCurrentTemplateDialect() == CFMLEngine.DIALECT_CFML) {
for (int i = 0; i < scopes.length; i++) {
rtn = scopes[i].get(key, NullSupportHelper.NULL());
if (rtn != NullSupportHelper.NULL()) {
return scopes[i];
}
}
}
return defaultValue;
}
Aggregations