⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pset_triplestore_rdb.java

📁 Jena推理机
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
		String objURI;
		Object obj_val;
		boolean isReif = reifNode != null;

		//	if database doesn't perform duplicate check
		if (!SKIP_DUPLICATE_CHECK && !isReif) {
			// if statement already in table
			if (statementTableContains(graphID, t)) {
				return;
			}
		}
		
		String obj_res, obj_lex, obj_lit;
		// TODO: Node.NULL is only valid for reif triple stores. should check this.
		String subj =
			t.getSubject().equals(Node.NULL) ? null : m_driver.nodeToRDBString(t.getSubject(),true);
		String pred =
			t.getPredicate().equals(Node.NULL) ? null : m_driver.nodeToRDBString(t.getPredicate(),true);
		String obj =
			t.getObject().equals(Node.NULL) ? null : m_driver.nodeToRDBString(t.getObject(),true);
//		String gid = graphID.getID().toString();
		int gid = ((DBIDInt) graphID).getIntID();

		int argc = 1;
		String stmtStr;

		if ((subj == null) || (pred == null) || (obj == null)) {
			if (!isReif)
				throw new JenaException("Attempt to assert triple with missing values");
		}
		// get statement string

		PreparedStatement ps = null;
		stmtStr = isReif ? "insertReified" : "insertStatement";
		try {
			ps =
				getPreparedStatement(
					stmtStr,
					getTblName(),
					isBatch,
					batchedPreparedStatements);
			//ps.clearParameters();

		} catch (SQLException e1) {
			logger.debug("SQLException caught " + e1.getErrorCode(), e1);
                        throw new JenaException("Exception during database access", e1);    // Rethrow in case there is a recovery option
		}
		// now fill in parameters
		try {
			if (subj == null)
				ps.setNull(argc++, java.sql.Types.VARCHAR);
			else
				ps.setString(argc++, subj);
			if (pred == null)
				ps.setNull(argc++, java.sql.Types.VARCHAR);
			else
				ps.setString(argc++, pred);
			if (obj == null)
				ps.setNull(argc++, java.sql.Types.VARCHAR);
			else
				ps.setString(argc++, obj);

			// add graph id and, if reifying, stmturi and hastype
			ps.setInt(argc++, gid);
			if (isReif) {
				String stmtURI = m_driver.nodeToRDBString(reifNode,true);
				ps.setString(argc++, stmtURI);
				if (hasType == true)
					ps.setString(argc++, "T");
				else
					ps.setString(argc++, " "); // not nullable
			}

		} catch (SQLException e1) {
			logger.debug("SQLException caught " + e1.getErrorCode(), e1);
                        throw new JenaException("Exception during database access", e1);    // Rethrow in case there is a recovery option
		}

		try {
			if (isBatch) {
				ps.addBatch();
			} else {
				ps.executeUpdate();
				m_sql.returnPreparedSQLStatement(ps);
			}
			//ps.close();
		} catch (SQLException e1) {
			// we let Oracle handle duplicate checking
			if (!((e1.getErrorCode() == 1)
				&& (m_driver.getDatabaseType().equalsIgnoreCase("oracle")))) {
				logger.error(
					"SQLException caught during insert"
						+ e1.getErrorCode(),
						e1);
                          throw new JenaException("Exception during database access", e1 );
			}
		}
	}
	
	/**
	 * Attempt to add a list of triples to the specialized graph.
	 * 
	 * As each triple is successfully added it is removed from the List. If
	 * complete is true then the entire List was added and the List will be
	 * empty upon return. if complete is false, then at least one triple remains
	 * in the List.
	 * 
	 * If a triple can't be stored for any reason other than incompatability
	 * (for example, a lack of disk space) then the implemenation should throw a
	 * runtime exception.
	 * 
	 * @param triples
	 *            List of triples to be added. This is modified by the call.
	 * @param my_GID
	 *            ID of the graph.
	 */
	public void storeTripleList(List triples, IDBID my_GID) {
		// for relational dbs, there are two styles for bulk inserts.
		// JDBC 2.0 supports batched updates.
		// MySQL also supports a multiple-row insert.
		// For now, we support only jdbc 2.0 batched updates
		/** Set of PreparedStatements that need executeBatch() * */
		Triple t;
		String cmd;
		boolean autoState = false;
		DriverRDB drvr = (DriverRDB) m_driver;
		Iterator it = triples.iterator();
		Hashtable batchedPreparedStatements = null;

		if ( SKIP_DUPLICATE_CHECK == false ) {
//		if ( false ) {
			while (it.hasNext()) {
				t = (Triple) it.next();
				storeTriple(t, my_GID, false, null);
			}
		} else 
		try {
			autoState = drvr.xactOp(DriverRDB.xactAutoOff);
			batchedPreparedStatements = new Hashtable();
			while (it.hasNext()) {
				t = (Triple) it.next();
				storeTriple(t, my_GID, true, batchedPreparedStatements);
			}

			Enumeration en = batchedPreparedStatements.keys();
			while (en.hasMoreElements()) {
				String op = (String) en.nextElement();
				PreparedStatement p = (PreparedStatement) batchedPreparedStatements
						.get(op);
				p.executeBatch();
				batchedPreparedStatements.remove(op);
				m_sql.returnPreparedSQLStatement(p);
			}
			if (autoState) {
				drvr.xactOp(DriverRDB.xactCommit);
				drvr.xactOp(DriverRDB.xactAutoOn);
			}
			batchedPreparedStatements = null; 
		
		// WARNING: caught exceptions should drop through to return.
		// if not, be sure to reset autocommit before exiting.

		} catch (BatchUpdateException b) {
			System.err.println("SQLException: " + b.getMessage());
			System.err.println("SQLState: " + b.getSQLState());
			System.err.println("Message: " + b.getMessage());
			System.err.println("Vendor: " + b.getErrorCode());
			System.err.print("Update counts: ");
			int[] updateCounts = b.getUpdateCounts();
			for (int i = 0; i < updateCounts.length; i++) {
				System.err.print(updateCounts[i] + " ");
			}
			if (autoState) drvr.xactOp(DriverRDB.xactAutoOn);
		} catch (SQLException ex) {
			System.err.println("SQLException: " + ex.getMessage());
			System.err.println("SQLState: " + ex.getSQLState());
			System.err.println("Message: " + ex.getMessage());
			System.err.println("Vendor: " + ex.getErrorCode());
			if (autoState) drvr.xactOp(DriverRDB.xactAutoOn);
		} finally {
			if ( batchedPreparedStatements != null ) {
			Enumeration en = batchedPreparedStatements.keys();
			while (en.hasMoreElements()) {
				String op = (String) en.nextElement();
				PreparedStatement p = (PreparedStatement) batchedPreparedStatements
						.get(op);
				batchedPreparedStatements.remove(op);
				m_sql.returnPreparedSQLStatement(p);
			}
			}
		}
		ArrayList c = new ArrayList(triples);
		triples.removeAll(c);
	}

	/**
	 * Attempt to remove a list of triples from the specialized graph.
	 * 
	 * As each triple is successfully deleted it is removed from the List. If
	 * complete is true then the entire List was added and the List will be
	 * empty upon return. if complete is false, then at least one triple remains
	 * in the List.
	 * 
	 * If a triple can't be stored for any reason other than incompatability
	 * (for example, a lack of disk space) then the implemenation should throw a
	 * runtime exception.
	 * 
	 * @param triples
	 *            List of triples to be added. This is modified by the call.
	 * @param my_GID
	 *            ID of the graph.
	 */
	public void deleteTripleList(List triples, IDBID my_GID) {
		// for relational dbs, there are two styles for bulk operations.
		// JDBC 2.0 supports batched updates.
		// MySQL also supports a multiple-row update.
		// For now, we support only jdbc 2.0 batched updates

		/** Set of PreparedStatements that need executeBatch() * */
		Hashtable batchedPreparedStatements = null;
		Triple t;
		String cmd;
		boolean autoState = false;
		DriverRDB drvr = (DriverRDB) m_driver;
		Iterator it = triples.iterator();
		
		if ( SKIP_DUPLICATE_CHECK == false ) {
//		if ( false ) {

			while (it.hasNext()) {
				t = (Triple) it.next();
				deleteTriple(t, my_GID, false, null);
			}
		} else 
		try {
			autoState = drvr.xactOp(DriverRDB.xactAutoOff);
			batchedPreparedStatements = new Hashtable();
			while (it.hasNext()) {
				t = (Triple) it.next();
				deleteTriple(t, my_GID, true, batchedPreparedStatements);
			}

			Enumeration en = batchedPreparedStatements.keys();
			while (en.hasMoreElements()) {
				String op = (String) en.nextElement();
				PreparedStatement p = (PreparedStatement) batchedPreparedStatements
						.get(op);
				p.executeBatch();
				batchedPreparedStatements.remove(op);
				m_sql.returnPreparedSQLStatement(p);
			}
			if (autoState) {
				drvr.xactOp(DriverRDB.xactCommit);
				drvr.xactOp(DriverRDB.xactAutoOn);
			}
			batchedPreparedStatements = null;
			
		// WARNING: caught exceptions should drop through to return.
		// if not, be sure to reset autocommit before exiting.

	} catch (BatchUpdateException b) {
			System.err.println("SQLException: " + b.getMessage());
			System.err.println("SQLState: " + b.getSQLState());
			System.err.println("Message: " + b.getMessage());
			System.err.println("Vendor: " + b.getErrorCode());
			System.err.print("Update counts: ");
			int[] updateCounts = b.getUpdateCounts();
			for (int i = 0; i < updateCounts.length; i++) {
				System.err.print(updateCounts[i] + " ");
			}
			if (autoState) drvr.xactOp(DriverRDB.xactAutoOn);
		} catch (SQLException ex) {
			System.err.println("SQLException: " + ex.getMessage());
			System.err.println("SQLState: " + ex.getSQLState());
			System.err.println("Message: " + ex.getMessage());
			System.err.println("Vendor: " + ex.getErrorCode());
			if (autoState) drvr.xactOp(DriverRDB.xactAutoOn);
		}
		finally {
			if ( batchedPreparedStatements != null ) {
				Enumeration en = batchedPreparedStatements.keys();
				while (en.hasMoreElements()) {
					String op = (String) en.nextElement();
					PreparedStatement p = (PreparedStatement) batchedPreparedStatements
							.get(op);
					batchedPreparedStatements.remove(op);
					m_sql.returnPreparedSQLStatement(p);
				}
			}
		}
		ArrayList c = new ArrayList(triples);
		triples.removeAll(c);
	}

	/**
	 * Compute the number of unique triples added to the Specialized Graph.
	 * 
	 * @return int count.
	 */
	public int tripleCount(IDBID graphId) {
		int gid = ((DBIDInt) graphId).getIntID();
		return(rowCount(gid));
	}
    

	/**
	 * Tests if a triple is contained in the specialized graph.
	 * @param t is the triple to be tested
	 * @param graphID is the id of the graph.
	 * @return boolean result to indicte if the tripple was contained
	 */
	public boolean statementTableContains(IDBID graphID, Triple t) {
	   ExtendedIterator it = find( t,  graphID );
	   boolean res = it.hasNext();
	   it.close();
	   return res;
	}
	
	/* (non-Javadoc)
	 * @see com.hp.hpl.jena.db.impl.IPSet#find(com.hp.hpl.jena.graph.TripleMatch, com.hp.hpl.jena.db.impl.IDBID)
	 */
	public ExtendedIterator find(TripleMatch t, IDBID graphID) {
		String astName = getTblName();
		Node subj_node = t.getMatchSubject();
		Node pred_node = t.getMatchPredicate();
		Node obj_node = t.getMatchObject();
		Node_Literal objLit;
		//	   String gid = graphID.getID().toString();
		int gid = ((DBIDInt) graphID).getIntID();
		boolean notFound = false;
int hack = 0;

		ResultSetTripleIterator result =
			new ResultSetTripleIterator(this, graphID);

		PreparedStatement ps = null;

		String subj = null;
		String pred = null;
		String obj = null;
		String op = "selectStatement";
		String qual = "";
		int args = 1;
if ( hack != 0 ) {
	subj_node = pred_node = obj_node = null;
}
		if (subj_node != null) {
			subj = m_driver.nodeToRDBString(subj_node, false);
			if (subj == null)
				notFound = true;
			else
				qual += "S";
		}
		if (pred_node != null) {
			pred = m_driver.nodeToRDBString(pred_node, false);
			if (pred == null)
				notFound = true;
			else
				qual += "P";
		}
		if (obj_node != null) {
			obj = m_driver.nodeToRDBString(obj_node, false);
			if (obj == null)
				notFound = true;
			else
				qual += "O";
		}
		if (notFound == false)
			try {
				op += qual;
				/*
				ps = m_sql.getPreparedSQLStatement(op, getTblName());
				if ( qual.equals("") ) {
					ps = m_sql.getPreparedSQLStatement(op+"Limit", getTblName(),Integer.toString(gid));
				
					// Statement stmt = m_driver.getConnection().getConnection().createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
					//			  java.sql.ResultSet.CONCUR_READ_ONLY);
					// stmt.setFetchSize(10);
					// String qry = "SELECT S.Subj, S.Prop, S.Obj FROM " + getTblName() + " S WHERE S.GraphID = "
					// 	+ gid;
					// ResultSet res = stmt.executeQuery(qry);
					result = new ResultSetLimitTripleIter(this, graphID);
				} else {
				//*/
				ps = m_sql.getPreparedSQLStatement(op, getTblName());
				if (obj != null)
					ps.setString(args++, obj);
				if (subj != null)
					ps.setString(args++, subj);
				if (pred != null)
					ps.setString(args++, pred);

				ps.setInt(args++, gid);
				//*/ }
				m_sql.executeSQL(ps, op, result);

				//m_sql.returnPreparedSQLStatement(ps,op);
			} catch (Exception e) {
				notFound = true;
				logger.debug( "find encountered exception: args=" + args + " err: ",  e);
                                throw new JenaException("Exception during database access", e);    // Rethrow in case there is a recovery option
			}

		if ( notFound ) result.close();
		return (new TripleMatchIterator(t.asTriple(), result));
	}

		/* (non-Javadoc)
		 * @see com.hp.hpl.jena.graphRDB.IPSet#removeStatementsFromDB()
		 */
		public void removeStatementsFromDB(IDBID graphID) {
            // TODO optimise in the case where 
			String gid = graphID.getID().toString();
			
			try {
				  PreparedStatement ps = m_sql.getPreparedSQLStatement("removeRowsFromTable",getTblName());
				  ps.clearParameters();	
	
				  ps.setString(1,gid);
				  ps.executeUpdate();
				  m_sql.returnPreparedSQLStatement(ps);
				 } catch (SQLException e) {
					logger.error("Problem removing statements from table: ", e);
                                        throw new JenaException("Exception during database access", e);    // Rethrow in case there is a recovery option
				 }
		}
}

/*
 *  (c) Copyright 2003, 2004, 2005, 2006, 2007 Hewlett-Packard Development Company, LP
 *  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.

 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
	
 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -