Search in sources :

Example 1 with DataSource

use of lucee.runtime.db.DataSource in project Lucee by lucee.

the class Query method doStartTag.

@Override
public int doStartTag() throws PageException {
    // default datasource
    if (datasource == null && (dbtype == null || !dbtype.equals("query"))) {
        Object obj = pageContext.getApplicationContext().getDefDataSource();
        if (StringUtil.isEmpty(obj)) {
            boolean isCFML = pageContext.getRequestDialect() == CFMLEngine.DIALECT_CFML;
            throw new ApplicationException("attribute [datasource] is required when attribute [dbtype] is not [query] and no default datasource is defined", "you can define a default datasource as attribute [defaultdatasource] of the tag " + (isCFML ? Constants.CFML_APPLICATION_TAG_NAME : Constants.LUCEE_APPLICATION_TAG_NAME) + " or as data member of the " + (isCFML ? Constants.CFML_APPLICATION_EVENT_HANDLER : Constants.LUCEE_APPLICATION_EVENT_HANDLER) + " (this.defaultdatasource=\"mydatasource\";)");
        }
        datasource = obj instanceof DataSource ? (DataSource) obj : pageContext.getDataSource(Caster.toString(obj));
    }
    // timeout
    if (datasource instanceof DataSourceImpl && ((DataSourceImpl) datasource).getAlwaysSetTimeout()) {
        TimeSpan remaining = PageContextUtil.remainingTime(pageContext, true);
        if (this.timeout == null || ((int) this.timeout.getSeconds()) <= 0 || timeout.getSeconds() > remaining.getSeconds()) {
            // not set
            this.timeout = remaining;
        }
    }
    // timezone
    if (timezone != null || (datasource != null && (timezone = datasource.getTimeZone()) != null)) {
        tmpTZ = pageContext.getTimeZone();
        pageContext.setTimeZone(timezone);
    }
    PageContextImpl pci = ((PageContextImpl) pageContext);
    // cache within
    if (StringUtil.isEmpty(cachedWithin)) {
        Object tmp = (pageContext).getCachedWithin(ConfigWeb.CACHEDWITHIN_QUERY);
        if (tmp != null)
            setCachedwithin(tmp);
    }
    // literal timestamp with TSOffset
    if (datasource instanceof DataSourceImpl)
        literalTimestampWithTSOffset = ((DataSourceImpl) datasource).getLiteralTimestampWithTSOffset();
    else
        literalTimestampWithTSOffset = false;
    previousLiteralTimestampWithTSOffset = pci.getTimestampWithTSOffset();
    pci.setTimestampWithTSOffset(literalTimestampWithTSOffset);
    return EVAL_BODY_BUFFERED;
}
Also used : TimeSpan(lucee.runtime.type.dt.TimeSpan) ApplicationException(lucee.runtime.exp.ApplicationException) DataSourceImpl(lucee.runtime.db.DataSourceImpl) PageContextImpl(lucee.runtime.PageContextImpl) DataSource(lucee.runtime.db.DataSource)

Example 2 with DataSource

use of lucee.runtime.db.DataSource in project Lucee by lucee.

the class StoredProc method doEndTag.

@Override
public int doEndTag() throws PageException {
    long startNS = System.nanoTime();
    Object ds = datasource;
    if (StringUtil.isEmpty(datasource)) {
        ds = pageContext.getApplicationContext().getDefDataSource();
        if (StringUtil.isEmpty(ds)) {
            boolean isCFML = pageContext.getRequestDialect() == CFMLEngine.DIALECT_CFML;
            throw new ApplicationException("attribute [datasource] is required, when no default datasource is defined", "you can define a default datasource as attribute [defaultdatasource] of the tag " + (isCFML ? Constants.CFML_APPLICATION_TAG_NAME : Constants.LUCEE_APPLICATION_TAG_NAME) + " or as data member of the " + (isCFML ? Constants.CFML_APPLICATION_EVENT_HANDLER : Constants.LUCEE_APPLICATION_EVENT_HANDLER) + " (this.defaultdatasource=\"mydatasource\";)");
        }
    }
    Struct res = new StructImpl();
    DataSourceManager manager = pageContext.getDataSourceManager();
    DatasourceConnection dc = ds instanceof DataSource ? manager.getConnection(pageContext, (DataSource) ds, username, password) : manager.getConnection(pageContext, Caster.toString(ds), username, password);
    // create returnValue
    returnValue(dc);
    String sql = createSQL();
    // add returnValue to params
    if (returnValue != null) {
        params.add(0, returnValue);
    }
    Log log = pageContext.getConfig().getLog("datasource");
    SQLImpl _sql = new SQLImpl(sql);
    CallableStatement callStat = null;
    try {
        if (// log entry added to troubleshoot LDEV-1147
        log.getLogLevel() >= Log.LEVEL_DEBUG)
            log.debug("LDEV1147", sql + " [" + params.size() + " params]");
        callStat = dc.getConnection().prepareCall(sql);
        if (blockfactor > 0)
            callStat.setFetchSize(blockfactor);
        if (timeout > 0)
            DataSourceUtil.setQueryTimeoutSilent(callStat, timeout);
        // set IN register OUT
        Iterator<ProcParamBean> it = params.iterator();
        ProcParamBean param;
        int index = 1;
        while (it.hasNext()) {
            param = it.next();
            param.setIndex(index);
            _sql.addItems(new SQLItemImpl(param.getValue()));
            if (param.getDirection() != ProcParamBean.DIRECTION_OUT) {
                SQLCaster.setValue(pageContext, pageContext.getTimeZone(), callStat, index, param);
            }
            if (param.getDirection() != ProcParamBean.DIRECTION_IN) {
                registerOutParameter(callStat, param);
            }
            index++;
        }
        String dsn = (ds instanceof DataSource) ? ((DataSource) ds).getName() : Caster.toString(ds);
        // cache
        boolean isFromCache = false;
        Object cacheValue = null;
        boolean useCache = (cachedWithin != null) || (cachedafter != null);
        String cacheId = null;
        CacheHandler cacheHandler = null;
        if (useCache) {
            cacheId = CacheHandlerCollectionImpl.createId(_sql, dsn, username, password, Query.RETURN_TYPE_STORED_PROC);
            cacheHandler = pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_QUERY, null).getInstanceMatchingObject(cachedWithin, null);
            if (cacheHandler instanceof CacheHandlerPro) {
                CacheItem cacheItem = ((CacheHandlerPro) cacheHandler).get(pageContext, cacheId, cachedWithin);
                if (cacheItem != null)
                    cacheValue = ((StoredProcCacheItem) cacheItem).getStruct();
            } else if (cacheHandler != null) {
                // TODO this else block can be removed when all cache handlers implement CacheHandlerPro
                CacheItem cacheItem = cacheHandler.get(pageContext, cacheId);
                if (cacheItem != null)
                    cacheValue = ((StoredProcCacheItem) cacheItem).getStruct();
            // cacheValue = pageContext.getQueryCache().get(pageContext,_sql,dsn,username,password,cachedafter);
            }
        }
        int count = 0;
        long start = System.currentTimeMillis();
        if (cacheValue == null) {
            // execute
            boolean isResult = callStat.execute();
            Struct cacheStruct = useCache ? new StructImpl() : null;
            // resultsets
            ProcResultBean result;
            index = 1;
            do {
                if (isResult) {
                    ResultSet rs = callStat.getResultSet();
                    if (rs != null) {
                        try {
                            result = (ProcResultBean) results.get(index++, null);
                            if (result != null) {
                                lucee.runtime.type.Query q = new QueryImpl(rs, result.getMaxrows(), result.getName(), pageContext.getTimeZone());
                                count += q.getRecordcount();
                                setVariable(result.getName(), q);
                                if (useCache)
                                    cacheStruct.set(KeyImpl.getInstance(result.getName()), q);
                            }
                        } finally {
                            IOUtil.closeEL(rs);
                        }
                    }
                }
            } while ((isResult = callStat.getMoreResults()) || (callStat.getUpdateCount() != -1));
            // params
            it = params.iterator();
            while (it.hasNext()) {
                param = it.next();
                if (param.getDirection() != ProcParamBean.DIRECTION_IN) {
                    Object value = null;
                    if (!StringUtil.isEmpty(param.getVariable())) {
                        try {
                            value = SQLCaster.toCFType(callStat.getObject(param.getIndex()));
                        } catch (Throwable t) {
                            ExceptionUtil.rethrowIfNecessary(t);
                        }
                        value = emptyIfNull(value);
                        if (param == STATUS_CODE)
                            res.set(STATUSCODE, value);
                        else
                            setVariable(param.getVariable(), value);
                        if (useCache)
                            cacheStruct.set(KeyImpl.getInstance(param.getVariable()), value);
                    }
                }
            }
            if (cacheHandler != null) {
                cacheStruct.set(COUNT, Caster.toDouble(count));
                cacheHandler.set(pageContext, cacheId, cachedWithin, new StoredProcCacheItem(cacheStruct, procedure, System.currentTimeMillis() - start));
            // pageContext.getQueryCache().set(pageContext,_sql,dsn,username,password,cache,cachedbefore);
            }
        } else if (cacheValue instanceof Struct) {
            Struct sctCache = (Struct) cacheValue;
            count = Caster.toIntValue(sctCache.removeEL(COUNT), 0);
            Iterator<Entry<Key, Object>> cit = sctCache.entryIterator();
            Entry<Key, Object> ce;
            while (cit.hasNext()) {
                ce = cit.next();
                if (STATUS_CODE.getVariable().equals(ce.getKey().getString()))
                    res.set(KEY_SC, ce.getValue());
                else
                    setVariable(ce.getKey().getString(), ce.getValue());
            }
            isFromCache = true;
        }
        // result
        long exe;
        setVariable(this.result, res);
        res.set(KeyConstants._executionTime, Caster.toDouble(exe = (System.nanoTime() - startNS)));
        res.set(KeyConstants._cached, Caster.toBoolean(isFromCache));
        if (pageContext.getConfig().debug() && debug) {
            boolean logdb = ((ConfigImpl) pageContext.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_DATABASE);
            if (logdb)
                pageContext.getDebugger().addQuery(null, dsn, procedure, _sql, count, pageContext.getCurrentPageSource(), (int) exe);
        }
        // log
        if (log.getLogLevel() >= Log.LEVEL_INFO) {
            log.info(StoredProc.class.getSimpleName(), "executed [" + sql.trim() + "] in " + DecimalFormat.call(pageContext, exe / 1000000D) + " ms");
        }
    } catch (SQLException e) {
        // log
        log.error(StoredProc.class.getSimpleName(), e);
        throw new DatabaseException(e, new SQLImpl(sql), dc);
    } catch (PageException pe) {
        // log
        log.error(StoredProc.class.getSimpleName(), pe);
        throw pe;
    } finally {
        if (callStat != null) {
            try {
                callStat.close();
            } catch (SQLException e) {
            }
        }
        manager.releaseConnection(pageContext, dc);
    }
    return EVAL_PAGE;
}
Also used : SQLImpl(lucee.runtime.db.SQLImpl) DatasourceConnection(lucee.runtime.db.DatasourceConnection) SQLException(java.sql.SQLException) DataSourceManager(lucee.runtime.db.DataSourceManager) Struct(lucee.runtime.type.Struct) StoredProcCacheItem(lucee.runtime.cache.tag.query.StoredProcCacheItem) QueryImpl(lucee.runtime.type.QueryImpl) Entry(java.util.Map.Entry) CallableStatement(java.sql.CallableStatement) CacheHandlerPro(lucee.runtime.cache.tag.CacheHandlerPro) ResultSet(java.sql.ResultSet) Iterator(java.util.Iterator) SQLItemImpl(lucee.runtime.db.SQLItemImpl) PageException(lucee.runtime.exp.PageException) Log(lucee.commons.io.log.Log) DataSource(lucee.runtime.db.DataSource) ApplicationException(lucee.runtime.exp.ApplicationException) StructImpl(lucee.runtime.type.StructImpl) CacheItem(lucee.runtime.cache.tag.CacheItem) StoredProcCacheItem(lucee.runtime.cache.tag.query.StoredProcCacheItem) CacheHandler(lucee.runtime.cache.tag.CacheHandler) DatabaseException(lucee.runtime.exp.DatabaseException) Key(lucee.runtime.type.Collection.Key) ConfigImpl(lucee.runtime.config.ConfigImpl)

Example 3 with DataSource

use of lucee.runtime.db.DataSource in project Lucee by lucee.

the class Update method doEndTag.

@Override
public int doEndTag() throws PageException {
    Object ds = DBInfo.getDatasource(pageContext, datasource);
    DataSourceManager manager = pageContext.getDataSourceManager();
    DatasourceConnection dc = ds instanceof DataSource ? manager.getConnection(pageContext, (DataSource) ds, username, password) : manager.getConnection(pageContext, Caster.toString(ds), username, password);
    try {
        Struct meta = null;
        try {
            meta = Insert.getMeta(dc, tablequalifier, tableowner, tablename);
        } catch (SQLException se) {
            meta = new StructImpl();
        }
        String[] pKeys = getPrimaryKeys(dc);
        SQL sql = createSQL(dc, pKeys, meta);
        if (sql != null) {
            lucee.runtime.type.Query query = new QueryImpl(pageContext, dc, sql, -1, -1, null, "query");
            if (pageContext.getConfig().debug()) {
                String dsn = ds instanceof DataSource ? ((DataSource) ds).getName() : Caster.toString(ds);
                boolean logdb = ((ConfigImpl) pageContext.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_DATABASE);
                if (logdb) {
                    boolean debugUsage = DebuggerUtil.debugQueryUsage(pageContext, query);
                    pageContext.getDebugger().addQuery(debugUsage ? query : null, dsn, "", sql, query.getRecordcount(), pageContext.getCurrentPageSource(), query.getExecutionTime());
                }
            }
            // log
            Log log = pageContext.getConfig().getLog("datasource");
            if (log.getLogLevel() >= Log.LEVEL_INFO) {
                log.info("update tag", "executed [" + sql.toString().trim() + "] in " + DecimalFormat.call(pageContext, query.getExecutionTime() / 1000000D) + " ms");
            }
        }
        return EVAL_PAGE;
    } catch (PageException pe) {
        pageContext.getConfig().getLog("datasource").error("update tag", pe);
        throw pe;
    } finally {
        manager.releaseConnection(pageContext, dc);
    }
}
Also used : PageException(lucee.runtime.exp.PageException) DatasourceConnection(lucee.runtime.db.DatasourceConnection) SQLException(java.sql.SQLException) Log(lucee.commons.io.log.Log) DataSourceManager(lucee.runtime.db.DataSourceManager) DataSource(lucee.runtime.db.DataSource) Struct(lucee.runtime.type.Struct) SQL(lucee.runtime.db.SQL) QueryImpl(lucee.runtime.type.QueryImpl) StructImpl(lucee.runtime.type.StructImpl) ConfigImpl(lucee.runtime.config.ConfigImpl)

Example 4 with DataSource

use of lucee.runtime.db.DataSource in project Lucee by lucee.

the class ORMUtil method getDataSource.

/**
 * if the given component has defined a datasource in the meta data, lucee is returning this datasource,
 * otherwise the default orm datasource is returned
 * @param pc
 * @param cfc
 * @return
 * @throws PageException
 */
public static DataSource getDataSource(PageContext pc, Component cfc, DataSource defaultValue) {
    pc = ThreadLocalPageContext.get(pc);
    // datasource defined with cfc
    try {
        Struct meta = cfc.getMetaData(pc);
        String datasourceName = Caster.toString(meta.get(KeyConstants._datasource, null), null);
        if (!StringUtil.isEmpty(datasourceName, true)) {
            DataSource ds = pc.getDataSource(datasourceName, null);
            if (ds != null)
                return ds;
        }
    } catch (Throwable t) {
        ExceptionUtil.rethrowIfNecessary(t);
    }
    return getDefaultDataSource(pc, defaultValue);
}
Also used : Struct(lucee.runtime.type.Struct) DataSource(lucee.runtime.db.DataSource)

Example 5 with DataSource

use of lucee.runtime.db.DataSource in project Lucee by lucee.

the class ORMUtil method getDataSourceName.

public static String getDataSourceName(PageContext pc, Component cfc, String defaultValue) {
    pc = ThreadLocalPageContext.get(pc);
    // datasource defined with cfc
    Struct meta = null;
    try {
        meta = cfc.getMetaData(pc);
        String datasourceName = Caster.toString(meta.get(KeyConstants._datasource, null), null);
        if (!StringUtil.isEmpty(datasourceName, true)) {
            return datasourceName.trim();
        }
    } catch (PageException e) {
    }
    DataSource ds = getDefaultDataSource(pc, null);
    if (ds != null)
        return ds.getName();
    return defaultValue;
}
Also used : PageException(lucee.runtime.exp.PageException) Struct(lucee.runtime.type.Struct) DataSource(lucee.runtime.db.DataSource)

Aggregations

DataSource (lucee.runtime.db.DataSource)27 PageException (lucee.runtime.exp.PageException)9 Struct (lucee.runtime.type.Struct)9 DatasourceConnection (lucee.runtime.db.DatasourceConnection)8 ApplicationException (lucee.runtime.exp.ApplicationException)8 ConfigImpl (lucee.runtime.config.ConfigImpl)7 StructImpl (lucee.runtime.type.StructImpl)7 SQLException (java.sql.SQLException)5 Map (java.util.Map)5 Log (lucee.commons.io.log.Log)5 Entry (java.util.Map.Entry)4 CacheConnection (lucee.runtime.cache.CacheConnection)4 ClassDefinition (lucee.runtime.db.ClassDefinition)4 DataSourceManager (lucee.runtime.db.DataSourceManager)4 DatasourceConnectionPool (lucee.runtime.db.DatasourceConnectionPool)4 ApplicationContext (lucee.runtime.listener.ApplicationContext)4 QueryImpl (lucee.runtime.type.QueryImpl)4 SQLExecutor (lucee.runtime.type.scope.storage.db.SQLExecutor)4 HashMap (java.util.HashMap)3 Iterator (java.util.Iterator)3