Example usage for java.sql Connection setReadOnly

List of usage examples for java.sql Connection setReadOnly

Introduction

In this page you can find the example usage for java.sql Connection setReadOnly.

Prototype

void setReadOnly(boolean readOnly) throws SQLException;

Source Link

Document

Puts this connection in read-only mode as a hint to the driver to enable database optimizations.

Usage

From source file:axiom.objectmodel.db.NodeManager.java

/**
 * Count the nodes contained in the child collection of the home node
 * which is defined by Relation rel.//from  w w w .j  a va 2s  .  com
 */
public int countNodes(Node home, Relation rel) throws Exception {
    // Transactor tx = (Transactor) Thread.currentThread ();
    // tx.timer.beginEvent ("countNodes "+home);
    if ((rel == null) || (rel.otherType == null) || !rel.otherType.isRelational()) {
        // this should never be called for embedded nodes
        throw new RuntimeException("NodeMgr.countNodes called for non-relational node " + home);
    } else {
        int retval = 0;
        Connection con = rel.otherType.getConnection();
        // set connection to read-only mode
        if (!con.isReadOnly())
            con.setReadOnly(true);

        String table = rel.otherType.getTableName();
        Statement stmt = null;
        long logTimeStart = logSql ? System.currentTimeMillis() : 0;
        String query = null;

        try {
            StringBuffer tables = new StringBuffer(table);

            rel.appendAdditionalTables(tables);

            // NOTE: we explicitly convert tables StringBuffer to a String
            // before appending to be compatible with JDK 1.3
            StringBuffer b = new StringBuffer("SELECT count(*) FROM ").append(tables.toString())
                    .append(rel.otherType.getTableJoinClause(1));

            if (home.getSubnodeRelation() != null) {
                // use the manually set subnoderelation of the home node
                query = b.append(" ").append(home.getSubnodeRelation()).toString();
            } else {
                // let relation object build the query
                query = b.append(rel.buildQuery(home, home.getNonVirtualParent(), null, " WHERE ", false))
                        .toString();
            }

            stmt = con.createStatement();

            ResultSet rs = stmt.executeQuery(query);

            if (!rs.next()) {
                retval = 0;
            } else {
                retval = rs.getInt(1);
            }
        } finally {
            if (logSql) {
                long logTimeStop = System.currentTimeMillis();
                logSqlStatement("SQL SELECT_COUNT", table, logTimeStart, logTimeStop, query);
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ex) {
                    app.logError(ErrorReporter.errorMsg(this.getClass(), "countNodes"), ex);
                }
            }
        }

        return (rel.maxSize > 0) ? Math.min(rel.maxSize, retval) : retval;
    }
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *  Similar to getNodeIDs, but returns a Vector that return's the nodes property names instead of IDs
 *///from www  . ja  v  a 2  s  .c  o m
public Vector getPropertyNames(Node home, Relation rel) throws Exception {
    // Transactor tx = (Transactor) Thread.currentThread ();
    // tx.timer.beginEvent ("getNodeIDs "+home);
    if ((rel == null) || (rel.otherType == null) || !rel.otherType.isRelational()) {
        // this should never be called for embedded nodes
        throw new RuntimeException("NodeMgr.getPropertyNames called for non-relational node " + home);
    } else {
        Vector retval = new Vector();

        // if we do a groupby query (creating an intermediate layer of groupby nodes),
        // retrieve the value of that field instead of the primary key
        String namefield = (rel.groupby == null) ? rel.accessName : rel.groupby;
        Connection con = rel.otherType.getConnection();
        // set connection to read-only mode
        if (!con.isReadOnly())
            con.setReadOnly(true);

        String table = rel.otherType.getTableName();
        StringBuffer tables = new StringBuffer(table);
        rel.appendAdditionalTables(tables);

        Statement stmt = null;
        long logTimeStart = logSql ? System.currentTimeMillis() : 0;
        String query = null;

        try {
            // NOTE: we explicitly convert tables StringBuffer to a String
            // before appending to be compatible with JDK 1.3
            StringBuffer b = new StringBuffer("SELECT ").append(namefield).append(" FROM ")
                    .append(tables.toString());

            if (home.getSubnodeRelation() != null) {
                b.append(" ").append(home.getSubnodeRelation());
            } else {
                // let relation object build the query
                b.append(rel.buildQuery(home, home.getNonVirtualParent(), null, " WHERE ", true));
            }

            stmt = con.createStatement();

            query = b.toString();

            ResultSet rs = stmt.executeQuery(query);

            while (rs.next()) {
                String n = rs.getString(1);

                if (n != null) {
                    retval.addElement(n);
                }
            }
        } finally {
            if (logSql) {
                long logTimeStop = System.currentTimeMillis();
                logSqlStatement("SQL SELECT_ACCESSNAMES", table, logTimeStart, logTimeStop, query);
            }

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ex) {
                    app.logError(ErrorReporter.errorMsg(this.getClass(), "getPropertyNames"), ex);
                }
            }
        }

        return retval;
    }
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *  Loades subnodes via subnode relation. This is similar to getNodeIDs, but it
 *  actually loades all nodes in one go, which is better for small node collections.
 *  This method is used when xxx.loadmode=aggressive is specified.
 *//*  w  ww.  j a  v  a2  s  .  c o  m*/
public Collection<NodeHandle> getNodes(Node home, Relation rel) throws Exception {
    // This does not apply for groupby nodes - use getNodeIDs instead
    if (rel.groupby != null) {
        return getNodeIDs(home, rel);
    }

    // Transactor tx = (Transactor) Thread.currentThread ();
    // tx.timer.beginEvent ("getNodes "+home);
    if ((rel == null) || (rel.otherType == null) || !rel.otherType.isRelational()) {
        // this should never be called for embedded nodes
        throw new RuntimeException("NodeMgr.getNodes called for non-relational node " + home);
    } else {
        Collection<NodeHandle> retval = home.createSubnodeList();
        DbMapping dbm = rel.otherType;

        Connection con = dbm.getConnection();
        // set connection to read-only mode
        if (!con.isReadOnly())
            con.setReadOnly(true);

        Statement stmt = con.createStatement();
        DbColumn[] columns = dbm.getColumns();
        Relation[] joins = dbm.getJoins();
        String query = null;
        long logTimeStart = logSql ? System.currentTimeMillis() : 0;

        try {
            StringBuffer b = dbm.getSelect(rel);

            if (home.getSubnodeRelation() != null) {
                b.append(home.getSubnodeRelation());
            } else {
                // let relation object build the query
                b.append(rel.buildQuery(home, home.getNonVirtualParent(), null, " WHERE ", true));
            }

            query = b.toString();

            if (rel.maxSize > 0) {
                stmt.setMaxRows(rel.maxSize);
            }

            ResultSet rs = stmt.executeQuery(query);

            while (rs.next()) {
                // create new Nodes.
                Node node = createNode(rel.otherType, rs, columns, 0);
                if (node == null) {
                    continue;
                }
                Key primKey = node.getKey();

                if (retval instanceof SubnodeList) {
                    ((SubnodeList) retval).addSorted(new NodeHandle(primKey));
                } else {
                    retval.add(new NodeHandle(primKey));
                }

                // do we need to synchronize on primKey here?
                synchronized (cache) {
                    Node oldnode = (Node) cache.put(primKey, node);

                    if ((oldnode != null) && (oldnode.getState() != INode.INVALID)) {
                        cache.put(primKey, oldnode);
                    }
                }

                fetchJoinedNodes(rs, joins, columns.length);
            }

        } finally {
            if (logSql) {
                long logTimeStop = System.currentTimeMillis();
                logSqlStatement("SQL SELECT_ALL", dbm.getTableName(), logTimeStart, logTimeStop, query);
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ignore) {
                    app.logEvent(ignore.getMessage());
                }
            }
        }

        return retval;
    }
}

From source file:com.funambol.foundation.items.dao.PIMCalendarDAO.java

/**
 * Retrieves the UID list of the calendars considered to be "twins" of a
 * given calendar.//from ww  w  .ja  v a2 s . c o m
 *
 * @param c the Calendar object representing the calendar whose twins
 *          need be found. In the present implementation, only the following
 *          data matter: 
 *          <BR>for events <UL><LI>date start<LI>date end<LI>subject</UL>
 *          for tasks <UL><LI>date end<LI>subject</UL>
 * @throws DAOException
 * @return a List of UIDs (as String objects) that may be empty but not null
 */
public List getTwinItems(Calendar c) throws DAOException {

    if (log.isTraceEnabled()) {
        log.trace("PIMCalendarDAO getTwinItems begin");
    }

    LinkedList<String> twins = new LinkedList<String>();
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    if (!isTwinSearchAppliableOn(c)) {
        if (log.isTraceEnabled()) {
            log.trace("Item with no dtStart, dtEnd, summary: twin search skipped.");
        }
        return twins;
    }

    try {

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);
        con.setReadOnly(true);

        Date dtStart;
        Date dtEnd;
        Date dueTomorrowNoon = null;
        Date dueYesterdayNoon = null;

        dtStart = getDateFromString(c.getCalendarContent().isAllDay(),
                Property.stringFrom(c.getCalendarContent().getDtStart()), "000000");
        dtEnd = getDateFromString(c.getCalendarContent().isAllDay(),
                Property.stringFrom(c.getCalendarContent().getDtEnd()), "235900");

        if ((dtEnd != null) && (c.getCalendarContent() instanceof Task)) {
            java.util.Calendar noon = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            noon.setTime(dtEnd);
            noon.set(java.util.Calendar.HOUR_OF_DAY, 12);
            noon.set(java.util.Calendar.MINUTE, 0);
            noon.set(java.util.Calendar.MILLISECOND, 0);
            noon.add(java.util.Calendar.DATE, +1);
            dueTomorrowNoon = noon.getTime();
            noon.add(java.util.Calendar.DATE, -2); // go back and another -1
            dueYesterdayNoon = noon.getTime();
        }

        StringBuffer sqlGetCalendarTwinList = new StringBuffer(SQL_GET_FNBL_PIM_CALENDAR_ID_LIST_BY_USER);

        String subject = Property.stringFrom(c.getCalendarContent().getSummary(), true); // Empty implies null;

        if ("null".equals(subject)) {
            subject = null;
        }
        if (subject == null) {
            sqlGetCalendarTwinList.append(SQL_AND_NO_SUBJECT_IS_SET);
        } else {
            sqlGetCalendarTwinList.append(SQL_AND_SUBJECT_EQUALS_QUESTIONMARK);
        }
        if (c.getCalendarContent() instanceof Event) {
            if (dtStart == null) {
                sqlGetCalendarTwinList.append(SQL_AND_NO_DSTART_IS_SET);
            } else {
                sqlGetCalendarTwinList.append(SQL_AND_DSTART_EQUALS_QUESTIONMARK);
            }
        }
        if (dtEnd == null) {
            // In method updateItems() while storing the Event in the db, if
            // the End Date is empty it is filled with the Start Date.
            // Filling the empty EndDate with the StartDate is done only for
            // Events and not for Tasks.
            // See "Fix for Siemens S56 end date issue" in method 
            // updateItems().
            // So in order to find the twins, if the incoming Event has an 
            // empty EndDate we seek into the db for Events with EndDate 
            // equal to the StartDate value.
            if (c.getCalendarContent() instanceof Task) {
                sqlGetCalendarTwinList.append(SQL_AND_NO_DEND_IS_SET);
            } else {
                sqlGetCalendarTwinList.append(SQL_AND_DEND_EQUALS_QUESTIONMARK);
            }
        } else {
            if (c.getCalendarContent() instanceof Task) {
                sqlGetCalendarTwinList.append(SQL_AND_DEND_IN_INTERVAL);
            } else {
                sqlGetCalendarTwinList.append(SQL_AND_DEND_EQUALS_QUESTIONMARK);
            }
        }

        if (c.getCalendarContent() instanceof Event) {
            sqlGetCalendarTwinList.append(SQL_FILTER_BY_TYPE[CALENDAR_EVENT_TYPE]);
        } else {
            sqlGetCalendarTwinList.append(SQL_FILTER_BY_TYPE[CALENDAR_TASK_TYPE]);
        }

        //
        // If funambol is not in the debug mode it is not possible to print 
        // the calendar info because it contains sensitive data.
        //
        if (Configuration.getConfiguration().isDebugMode()) {

            if (log.isTraceEnabled()) {

                StringBuilder sb = new StringBuilder(100);
                sb.append("Looking for items having: ");

                if (subject == null || subject.length() == 0) {
                    sb.append("\n> subject: <N/A>");
                } else {
                    sb.append("\n> subject: '").append(subject).append('\'');
                }
                if (c.getCalendarContent() instanceof Event) {
                    if (dtStart == null) {
                        sb.append("\n> start date: <N/A>");
                    } else {
                        sb.append("\n> start date: ").append(dtStart);
                    }
                    if (dtEnd == null) {
                        sb.append("\n> end date: <N/A>");
                    } else {
                        sb.append("\n> end date: ").append(dtEnd);
                    }
                } else { // It's a task
                    if (dtEnd == null) {
                        sb.append("\n> due date: <N/A>");
                    } else {
                        sb.append("\n> due date: between ").append(dueYesterdayNoon)
                                .append("\n>           and ").append(dueTomorrowNoon)
                                .append(",\n>           possibly ").append(dtEnd);
                    }
                }

                log.trace(sb.toString());
            }
        }

        sqlGetCalendarTwinList.append(SQL_ORDER_BY_ID);

        ps = con.prepareStatement(sqlGetCalendarTwinList.toString());

        int k = 1;
        ps.setString(k++, userId);
        if (subject != null) {
            ps.setString(k++, subject.toLowerCase(Locale.ENGLISH));
        }
        if (dtStart != null) {
            if (c.getCalendarContent() instanceof Event) {
                ps.setTimestamp(k++, new Timestamp(dtStart.getTime()));
            }
        }
        if (dtEnd != null) {
            if (c.getCalendarContent() instanceof Task) {
                ps.setTimestamp(k++, new Timestamp(dueYesterdayNoon.getTime()));
                ps.setTimestamp(k++, new Timestamp(dueTomorrowNoon.getTime()));
            } else {
                ps.setTimestamp(k++, new Timestamp(dtEnd.getTime()));
            }
        } else {
            // In method updateItems() while storing the Event in the db, if
            // the End Date is empty it is filled with the Start Date.
            // Filling the empty EndDate with the StartDate is done only for
            // Events and not for Tasks.
            // See "Fix for Siemens S56 end date issue" in method 
            // updateItems().
            // So in order to find the twins, if the incoming Event has an 
            // empty EndDate we seek into the db for Events with EndDate 
            // equal to the StartDate value.
            if (c.getCalendarContent() instanceof Event) {
                ps.setTimestamp(k++, new Timestamp(dtStart.getTime()));
            }
        }

        rs = ps.executeQuery();
        long twinId;
        Timestamp twinDueDate;
        while (rs.next()) {
            if (c.getCalendarContent() instanceof Event) {
                twinId = rs.getLong(1);
                // dend is not relevant in this case
                if (log.isTraceEnabled()) {
                    log.trace("Twin event found: " + twinId);
                }

                twins.add(Long.toString(twinId));

            } else { // it's a Task
                twinId = rs.getLong(1);
                twinDueDate = rs.getTimestamp(2);
                if (log.isTraceEnabled()) {
                    log.trace("Twin task found: " + twinId);
                }

                if ((dtEnd != null) && (twinDueDate != null) && twinDueDate.getTime() == dtEnd.getTime()) {
                    twins.addFirst(Long.toString(twinId));
                    if (log.isTraceEnabled()) {
                        log.trace("Item " + twinId + " is an exact due-date match.");
                    }
                } else {
                    twins.addLast(Long.toString(twinId));
                }
            }
        }

    } catch (Exception e) {
        throw new DAOException("Error retrieving twin. ", e);
    } finally {
        DBTools.close(con, ps, rs);
    }

    if (log.isTraceEnabled()) {
        log.trace("PIMCalendarDAO getTwinItems end");
    }

    return twins;
}

From source file:axiom.objectmodel.db.NodeManager.java

private Node getNodeByKey(ITransaction txn, DbKey key, String type, boolean multiLayers) throws Exception {
    // Note: Key must be a DbKey, otherwise will not work for relational objects
    Node node = null;//from w  w w. j av  a 2s. c om
    if (type == null) {
        type = key.getStorageName();
    }
    DbMapping dbm = app.getDbMapping(type);
    String kstr = key.getID();

    if ((dbm == null) || !dbm.isRelational()) {
        IDatabase db = this.getDatabaseForMapping(dbm);
        try {
            final int mode;
            if (key instanceof DbKey) {
                // andy maybe i don't know
                /*if(this.app.getCurrentRequestEvaluator().getMode() == DbKey.DRAFT_MODE){
                    mode = this.app.getCurrentRequestEvaluator().getMode();
                }
                else{*/
                mode = ((DbKey) key).getLayer();
                //}
            } else {
                mode = this.app.getCurrentRequestEvaluator().getLayer();
            }
            node = (Node) db.getNode(txn, kstr, mode, multiLayers);
        } catch (Exception ex) {
            if (multiLayers) {
                node = (Node) db.getNode(txn, kstr);
            }
        }
        if (node != null) {
            node.nmgr = safe;
        }

        if ((node != null) && (dbm != null)) {
            node.setDbMapping(dbm);
        }
    } else {
        String idfield = dbm.getIDField();

        Statement stmt = null;
        String query = null;
        long logTimeStart = logSql ? System.currentTimeMillis() : 0;

        try {
            Connection con = dbm.getConnection();
            // set connection to read-only mode
            if (!con.isReadOnly())
                con.setReadOnly(true);

            stmt = con.createStatement();

            DbColumn[] columns = dbm.getColumns();
            Relation[] joins = dbm.getJoins();
            StringBuffer b = dbm.getSelect(null).append("WHERE ")
                    //.append(dbm.getTableName(0))
                    //.append(".")
                    .append(idfield).append(" = ");

            if (dbm.needsQuotes(idfield)) {
                b.append("'");
                b.append(escape(kstr));
                b.append("'");
            } else {
                b.append(kstr);
            }

            dbm.addJoinConstraints(b, " AND ");

            query = b.toString();
            query += dbm.getTableJoinClause(0);

            ResultSet rs = stmt.executeQuery(query);

            if (!rs.next()) {
                return null;
            }

            node = createNode(dbm, rs, columns, 0);

            fetchJoinedNodes(rs, joins, columns.length);

            if (rs.next()) {
                app.logError(ErrorReporter.errorMsg(this.getClass(), "getNodeByKey")
                        + "More than one value returned for query " + query);
            }
        } finally {
            if (logSql) {
                long logTimeStop = System.currentTimeMillis();
                logSqlStatement("SQL SELECT_BYKEY", dbm.getTableName(), logTimeStart, logTimeStop, query);
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ex) {
                    app.logError(ErrorReporter.errorMsg(this.getClass(), "getNodeByKey"), ex);
                }
            }
        }
    }

    return node;
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *  Loades subnodes via subnode relation. Only the ID index is loaded, the nodes are
 *  loaded later on demand.//w  ww .ja v a2  s  . c o m
 */
public Collection<NodeHandle> getNodeIDs(Node home, Relation rel) throws Exception {
    // Transactor tx = (Transactor) Thread.currentThread ();
    // tx.timer.beginEvent ("getNodeIDs "+home);

    if ((rel == null) || (rel.otherType == null) || !rel.otherType.isRelational()) {
        // this should never be called for embedded nodes
        throw new RuntimeException("NodeMgr.getNodeIDs called for non-relational node " + home);
    } else {
        Collection<NodeHandle> retval = home.createSubnodeList();

        // if we do a groupby query (creating an intermediate layer of groupby nodes),
        // retrieve the value of that field instead of the primary key
        String idfield = (rel.groupby == null) ? rel.otherType.getIDField() : rel.groupby;
        Connection con = rel.otherType.getConnection();
        // set connection to read-only mode
        if (!con.isReadOnly())
            con.setReadOnly(true);

        String table = rel.otherType.getTableName();

        Statement stmt = null;
        long logTimeStart = logSql ? System.currentTimeMillis() : 0;
        String query = null;

        try {
            StringBuffer b = new StringBuffer("SELECT ");

            if (rel.queryHints != null) {
                b.append(rel.queryHints).append(" ");
            }

            /*if (idfield.indexOf('(') == -1 && idfield.indexOf('.') == -1) {
            b.append(table).append('.');
            }*/
            b/*.append(rel.otherType.getTableName(0)).append(".")*/.append(idfield).append(" FROM ")
                    .append(table);

            rel.appendAdditionalTables(b);

            if (home.getSubnodeRelation() != null) {
                // subnode relation was explicitly set
                query = b.append(" ").append(home.getSubnodeRelation()).toString();
            } else {
                // let relation object build the query
                query = b.append(rel.buildQuery(home, home.getNonVirtualParent(), null, " WHERE ", true))
                        .toString();
            }

            stmt = con.createStatement();
            int primary = 1;
            if (query.indexOf("WHERE") > -1) {
                primary = 0;
            }
            query += rel.otherType.getTableJoinClause(primary);

            if (rel.maxSize > 0) {
                stmt.setMaxRows(rel.maxSize);
            }

            ResultSet result = stmt.executeQuery(query);

            // problem: how do we derive a SyntheticKey from a not-yet-persistent Node?
            Key k = (rel.groupby != null) ? home.getKey() : null;

            while (result.next()) {
                String kstr = result.getString(1);

                // jump over null values - this can happen especially when the selected
                // column is a group-by column.
                if (kstr == null) {
                    continue;
                }

                // make the proper key for the object, either a generic DB key or a groupby key
                Key key = (rel.groupby == null)
                        ? (Key) new DbKey(rel.otherType, kstr, this.app.getCurrentRequestEvaluator().getLayer())
                        : (Key) new SyntheticKey(k, kstr);

                if (retval instanceof SubnodeList) {
                    ((SubnodeList) retval).addSorted(new NodeHandle(key));
                } else {
                    retval.add(new NodeHandle(key));
                }

                // if these are groupby nodes, evict nullNode keys
                if (rel.groupby != null) {
                    Node n = this.getNodeFromCache(key);

                    if ((n != null) && n.isNullNode()) {
                        evictKey(key);
                    }
                }
            }
        } finally {
            if (logSql) {
                long logTimeStop = System.currentTimeMillis();
                logSqlStatement("SQL SELECT_IDS", table, logTimeStart, logTimeStop, query);
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ignore) {
                }
            }
        }

        return retval;
    }
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *  Updates a modified node in the embedded db or an external relational database, depending
 * on its database mapping./*from www.j a v  a 2  s.  com*/
 *
 * @return true if the DbMapping of the updated Node is to be marked as updated via
 *              DbMapping.setLastDataChange
 */
public boolean updateNode(IDatabase db, ITransaction txn, Node node)
        throws IOException, SQLException, ClassNotFoundException {
    // Transactor tx = (Transactor) Thread.currentThread ();
    // tx.timer.beginEvent ("updateNode "+node);
    invokeOnPersist(node);
    DbMapping dbm = node.getDbMapping();
    boolean markMappingAsUpdated = false;

    if ((dbm == null) || !dbm.isRelational()) {
        String className = dbm.getClassName();
        IDatabase idb = null;
        if (className != null) {
            idb = (IDatabase) this.dbs.get(className);
        }
        if (idb == null) {
            idb = db;
        }
        idb.updateNode(txn, node.getID(), node);
    } else {
        Hashtable propMap = node.getPropMap();
        Property[] props;

        if (propMap == null) {
            props = new Property[0];
        } else {
            props = new Property[propMap.size()];
            propMap.values().toArray(props);
        }

        // make sure table meta info is loaded by dbmapping
        dbm.getColumns();

        StringBuffer b = dbm.getUpdate();

        // comma flag set after the first dirty column, also tells as
        // if there are dirty columns at all
        boolean comma = false;

        for (int i = 0; i < props.length; i++) {
            // skip clean properties
            if ((props[i] == null) || !props[i].dirty) {
                // null out clean property so we don't consider it later
                props[i] = null;

                continue;
            }

            Relation rel = dbm.propertyToRelation(props[i].getName());

            // skip readonly, virtual and collection relations
            if ((rel == null) || rel.readonly || rel.virtual
                    || ((rel.reftype != Relation.REFERENCE) && (rel.reftype != Relation.PRIMITIVE))) {
                // null out property so we don't consider it later
                props[i] = null;

                continue;
            }

            if (comma) {
                b.append(", ");
            } else {
                comma = true;
            }

            b.append(rel.getDbField());
            b.append(" = ?");
        }

        // if no columns were updated, return false
        if (!comma) {
            return false;
        }

        b.append(" WHERE ");
        //b.append(dbm.getTableName(0));
        //b.append(".");
        b.append(dbm.getIDField());
        b.append(" = ");

        if (dbm.needsQuotes(dbm.getIDField())) {
            b.append("'");
            b.append(escape(node.getID()));
            b.append("'");
        } else {
            b.append(node.getID());
        }
        b.append(dbm.getTableJoinClause(0));

        Connection con = dbm.getConnection();
        // set connection to write mode
        if (con.isReadOnly())
            con.setReadOnly(false);
        PreparedStatement stmt = con.prepareStatement(b.toString());

        int stmtNumber = 0;
        long logTimeStart = logSql ? System.currentTimeMillis() : 0;

        try {
            for (int i = 0; i < props.length; i++) {
                Property p = props[i];

                if (p == null) {
                    continue;
                }

                Relation rel = dbm.propertyToRelation(p.getName());

                stmtNumber++;
                this.setStatementValues(stmt, stmtNumber, p, rel.getColumnType());

                p.dirty = false;

                if (!rel.isPrivate()) {
                    markMappingAsUpdated = true;
                }
            }

            stmt.executeUpdate();

        } finally {
            if (logSql) {
                long logTimeStop = System.currentTimeMillis();
                logSqlStatement("SQL UPDATE", dbm.getTableName(), logTimeStart, logTimeStop, b.toString());
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ignore) {
                    app.logEvent(ignore.getMessage());
                }
            }
        }
    }

    // update may cause changes in the node's parent subnode array
    // TODO: is this really needed anymore?
    if (markMappingAsUpdated && node.isAnonymous()) {
        Node parent = node.getCachedParent();

        if (parent != null) {
            parent.setLastSubnodeChange(System.currentTimeMillis());
        }
    }

    return markMappingAsUpdated;
}

From source file:axiom.objectmodel.db.NodeManager.java

private Node getNodeByRelation(ITransaction txn, Node home, String kstr, Relation rel, String type)
        throws Exception {
    Node node = null;/*ww  w.  j a  v  a2s  .c o  m*/
    boolean updateTypeDirty = false;

    if ((rel != null) && rel.virtual) {
        if (rel.needsPersistence()) {
            node = (Node) home.createNode(kstr);
        } else {
            node = new Node(home, kstr, safe, rel.prototype);
        }

        // set prototype and dbmapping on the newly created virtual/collection node
        node.setPrototype(rel.prototype);
        node.setDbMapping(rel.getVirtualMapping());
    } else if ((rel != null) && (rel.groupby != null)) {
        node = home.getGroupbySubnode(kstr, false);

        if ((node == null) && ((rel.otherType == null) || !rel.otherType.isRelational())) {

            IDatabase db = this.getDatabaseForMapping(rel.otherType);
            try {
                node = (Node) db.getNode(txn, kstr, this.app.getCurrentRequestEvaluator().getLayer());
            } catch (Exception ex) {
                node = (Node) db.getNode(txn, kstr);
            }
            node.nmgr = safe;
        }

        return node;
    } else if ((rel == null) || (rel.otherType == null) || !rel.otherType.isRelational()) {

        IDatabase db = (rel == null) ? this.defaultDb : this.getDatabaseForMapping(rel.otherType);
        try {
            node = (Node) ((LuceneDatabase) db).getNode(txn, kstr,
                    this.app.getCurrentRequestEvaluator().getLayer());
        } catch (Exception ex) {
            node = (Node) db.getNode(txn, kstr);
        }
        node.nmgr = safe;
        node.setDbMapping(rel.otherType);

        return node;
    } else {
        //DbMapping dbm = rel.otherType;
        DbMapping dbm = rel.otherType;
        if (type != null) {
            dbm = this.getDbMapping(type);
            //set the DbMapping later?
            updateTypeDirty = true;
        }
        Statement stmt = null;
        String query = null;
        long logTimeStart = logSql ? System.currentTimeMillis() : 0;

        try {
            Connection con = dbm.getConnection();
            // set connection to read-only mode
            if (!con.isReadOnly())
                con.setReadOnly(true);
            DbColumn[] columns = dbm.getColumns();
            Relation[] joins = dbm.getJoins();
            StringBuffer b = dbm.getSelect(rel);
            if (home.getSubnodeRelation() != null && !rel.isComplexReference()) {
                // combine our key with the constraints in the manually set subnode relation
                b.append(" WHERE ");
                if (rel.accessName.indexOf('(') == -1 && rel.accessName.indexOf('.') == -1) {
                    b.append(dbm.getTableName(0));
                    b.append(".");
                }
                b.append(rel.accessName);
                b.append(" = '");
                b.append(escape(kstr));
                b.append("'");
                // add join contraints in case this is an old oracle style join
                dbm.addJoinConstraints(b, " AND ");
                // add potential constraints from manually set subnodeRelation
                String subrel = home.getSubnodeRelation().trim();
                if (subrel.length() > 5) {
                    b.append(" AND (");
                    b.append(subrel.substring(5).trim());
                    b.append(")");
                }
            } else {
                b.append(rel.buildQuery(home, home.getNonVirtualParent(), kstr, " WHERE ", false));
            }

            b.append(dbm.getTableJoinClause(0));

            stmt = con.createStatement();

            query = b.toString();

            ResultSet rs = stmt.executeQuery(query);

            if (!rs.next()) {
                return null;
            }

            //node = createNode(rel.otherType, rs, columns, 0);
            node = createNode(dbm, rs, columns, 0);

            fetchJoinedNodes(rs, joins, columns.length);

            if (rs.next()) {
                app.logError(ErrorReporter.errorMsg(this.getClass(), "getNodeByRelation")
                        + "More than one value returned for query " + query);
            }

            // Check if node is already cached with primary Key.
            if (!rel.usesPrimaryKey() && node != null) {
                Key pk = node.getKey();
                Node existing = this.getNodeFromCache(pk);

                if ((existing != null) && (existing.getState() != Node.INVALID) && (!updateTypeDirty)) { //Check for dirty bit!
                    node = existing;
                }
            }

        } finally {
            if (logSql) {
                long logTimeStop = System.currentTimeMillis();
                logSqlStatement("SQL SELECT_BYRELATION", dbm.getTableName(), logTimeStart, logTimeStop, query);
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ex) {
                    app.logError(ErrorReporter.errorMsg(this.getClass(), "getNodeByRelation"), ex);
                }
            }
        }
    }

    if ((node != null) && (updateTypeDirty)) {
        node.setTypeDirty(false);
    }

    return node;
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *
 *///  w w w .j  a v  a  2  s.co m
public void prefetchNodes(Node home, Relation rel, Key[] keys) throws Exception {
    DbMapping dbm = rel.otherType;

    if ((dbm == null) || !dbm.isRelational()) {
        // this does nothing for objects in the embedded database
        return;
    } else {
        boolean missing = missingFromCache(keys);

        if (missing) {
            Connection con = dbm.getConnection();
            // set connection to read-only mode
            if (!con.isReadOnly())
                con.setReadOnly(true);

            Statement stmt = con.createStatement();
            DbColumn[] columns = dbm.getColumns();
            Relation[] joins = dbm.getJoins();
            String query = null;
            long logTimeStart = logSql ? System.currentTimeMillis() : 0;

            try {
                StringBuffer b = dbm.getSelect(rel);

                String idfield = (rel.groupby != null) ? rel.groupby : dbm.getIDField();
                boolean needsQuotes = dbm.needsQuotes(idfield);

                b.append(" WHERE ");
                //b.append(dbm.getTableName());
                //b.append(".");
                b.append(idfield);
                b.append(" IN (");

                boolean first = true;

                for (int i = 0; i < keys.length; i++) {
                    if (keys[i] != null) {
                        if (!first) {
                            b.append(',');
                        } else {
                            first = false;
                        }

                        if (needsQuotes) {
                            b.append("'");
                            b.append(escape(keys[i].getID()));
                            b.append("'");
                        } else {
                            b.append(keys[i].getID());
                        }
                    }
                }

                b.append(") ");

                dbm.addJoinConstraints(b, " AND ");

                if (rel.groupby != null) {
                    rel.renderConstraints(b, home, home.getNonVirtualParent(), " AND ");

                    if (rel.order != null) {
                        b.append(" ORDER BY ");
                        b.append(rel.order);
                    }
                }

                query = b.toString();

                ResultSet rs = stmt.executeQuery(query);

                String groupbyProp = null;
                HashMap groupbySubnodes = null;

                if (rel.groupby != null) {
                    groupbyProp = dbm.columnNameToProperty(rel.groupby);
                    groupbySubnodes = new HashMap();
                }

                String accessProp = null;

                if ((rel.accessName != null) && !rel.usesPrimaryKey()) {
                    accessProp = dbm.columnNameToProperty(rel.accessName);
                }

                while (rs.next()) {
                    // create new Nodes.
                    Node node = createNode(dbm, rs, columns, 0);
                    if (node == null) {
                        continue;
                    }
                    Key primKey = node.getKey();

                    // for grouped nodes, collect subnode lists for the intermediary
                    // group nodes.
                    String groupName = null;

                    if (groupbyProp != null) {
                        groupName = node.getString(groupbyProp);

                        SubnodeList sn = (SubnodeList) groupbySubnodes.get(groupName);

                        if (sn == null) {
                            sn = new SubnodeList(safe, rel);
                            groupbySubnodes.put(groupName, sn);
                        }

                        sn.addSorted(new NodeHandle(primKey));
                    }

                    // if relation doesn't use primary key as accessName, get accessName value
                    String accessName = null;

                    if (accessProp != null) {
                        accessName = node.getString(accessProp);
                    }

                    // register new nodes with the cache. If an up-to-date copy
                    // existed in the cache, use that.
                    synchronized (cache) {
                        Node oldnode = (Node) cache.put(primKey, node);

                        if ((oldnode != null) && (oldnode.getState() != INode.INVALID)) {
                            // found an ok version in the cache, use it.
                            cache.put(primKey, oldnode);
                        } else if (accessName != null) {
                            // put the node into cache with its secondary key
                            if (groupName != null) {
                                cache.put(new SyntheticKey(new SyntheticKey(home.getKey(), groupName),
                                        accessName), node);
                            } else {
                                cache.put(new SyntheticKey(home.getKey(), accessName), node);
                            }
                        }
                    }

                    fetchJoinedNodes(rs, joins, columns.length);
                }

                // If these are grouped nodes, build the intermediary group nodes
                // with the subnod lists we created
                if (groupbyProp != null) {
                    for (Iterator i = groupbySubnodes.keySet().iterator(); i.hasNext();) {
                        String groupname = (String) i.next();

                        if (groupname == null) {
                            continue;
                        }

                        Node groupnode = home.getGroupbySubnode(groupname, true);

                        groupnode.setSubnodes((SubnodeList) groupbySubnodes.get(groupname));
                        groupnode.lastSubnodeFetch = System.currentTimeMillis();
                    }
                }
            } catch (Exception x) {
                System.err.println("Error in prefetchNodes(): " + x);
            } finally {
                if (logSql) {
                    long logTimeStop = System.currentTimeMillis();
                    logSqlStatement("SQL SELECT_PREFETCH", dbm.getTableName(), logTimeStart, logTimeStop,
                            query);
                }
                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (Exception ignore) {
                        app.logEvent(ignore.getMessage());
                    }
                }
            }
        }
    }
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 * Insert a node into a relational database.
 *//*from   ww w .j a v  a2s .com*/
protected void insertRelationalNodeInto(Node node, DbMapping dbm, Connection con, int tableNumber)
        throws ClassNotFoundException, SQLException {

    if (con == null) {
        throw new NullPointerException("Error inserting relational node: Connection is null");
    }

    // set connection to write mode
    if (con.isReadOnly())
        con.setReadOnly(false);

    String insertString = dbm.getInsert(tableNumber);

    PreparedStatement stmt = con.prepareStatement(insertString);

    DbColumn[] columns = dbm.getColumns(tableNumber);

    String nameField = dbm.getNameField();
    String prototypeField = dbm.getPrototypeField();
    String idField = dbm.getTableKey(tableNumber);

    long logTimeStart = logSql ? System.currentTimeMillis() : 0;

    try {
        int stmtNumber = 1;

        // first column of insert statement is always the primary key
        // Changed to get the primary key value from the db mapping,
        // in the case where a particular table's primary key is not the primary key
        // of the main table in the db mapping.
        stmt.setString(stmtNumber, dbm.getPrimaryKeyValue(node, tableNumber)); //node.getID());

        Hashtable propMap = node.getPropMap();

        for (int i = 0; i < columns.length; i++) {
            Relation rel = columns[i].getRelation();
            Property p = null;

            if (rel != null && propMap != null && (rel.isPrimitive() || rel.isReference())) {
                p = (Property) propMap.get(rel.getPropName());
            }

            String name = columns[i].getName();
            if (name.equals(idField)) {
                continue;
            } //Ensure the id is not repeated.

            if (!((rel != null) && (rel.isPrimitive() || rel.isReference()))
                    && !name.equalsIgnoreCase(nameField) && !name.equalsIgnoreCase(prototypeField)) {
                continue;
            }

            stmtNumber++;
            if (p != null) {
                this.setStatementValues(stmt, stmtNumber, p, columns[i].getType());
            } else if (name.equalsIgnoreCase(nameField)) {
                stmt.setString(stmtNumber, node.getName());
            } else if (name.equalsIgnoreCase(prototypeField)) {
                stmt.setString(stmtNumber, node.getPrototype());
            } else {
                stmt.setNull(stmtNumber, columns[i].getType());
            }
        }

        stmt.executeUpdate();
        //            node.setInteger("id", new Integer(node.getID()).longValue());

    } finally {
        if (logSql) {
            long logTimeStop = java.lang.System.currentTimeMillis();
            logSqlStatement("SQL INSERT", dbm.getTableName(), logTimeStart, logTimeStop, insertString);
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (Exception ex) {
                app.logError(ErrorReporter.errorMsg(this.getClass(), "insertRelationalNodeInto"), ex);
            }
        }
    }

}