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

📄 sqlcache.java

📁 Jena推理机
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
     * All statements are executed even if one raises an error then the error is
     * reported at the end.
     */
    public void runSQLGroup(String opname) throws SQLException {
    	runSQLGroup(opname,(String[])null);
   }

	/**
     * Run a group of sql statements - normally used for db formating and clean up.
     * All statements are executed even if one raises an error then the error is
     * reported at the end.
     * 
     * Attribute version -- substitute the ${a} attribute macro
     * for the current attribute 
     */
    public void runSQLGroup(String opname, String attr) throws SQLException {
    	String[] param = {attr};
    	runSQLGroup(opname,param);
    }

	/**
     * Run a group of sql statements - normally used for db formating and clean up.
     * All statements are executed even if one raises an error then the error is
     * reported at the end.
     * 
     * Attribute version -- substitute the ${a} attribute macro
     * for the current attribute 
     */
    public void runSQLGroup(String opname, String attrA, String attrB) throws SQLException {
		String[] param = {attrA,attrB};
		runSQLGroup(opname,param);
    }



    /**
     * Close all prepared statements
     */
    public void close() throws SQLException {
        Iterator it = m_preparedStatements.values().iterator();
        while (it.hasNext()) {
            List psl = (List) it.next();
            Iterator itl = psl.iterator();
            while (itl.hasNext()) {
                PreparedStatement ps = (PreparedStatement)itl.next();
                ps.close();
            }
            it.remove();
        }
		it = m_cachedStmtInUse.values().iterator();
		while (it.hasNext()) {
			it.remove();
		}
    }

    /**
     * Load in a defined set of sql statements - see class comment for format.
     * The loaded file is return as a Property table. This call is static
     * to support the loading of a default sql mapping.
     * @param sqlFile the name of the file of sql statements to load, this is
     * loaded from the classpath.
     * @param defaultOps a Properties table of default sql definitions.
     * @param idType the sql string to use for id types (substitutes for $id in files)
     */
    public static Properties loadSQLFile(String sqlFile, Properties defaultOps, String idType) throws IOException {
        Properties sqlTable = new Properties(defaultOps);
        BufferedReader src = openResourceFile(sqlFile);
        String line = null;
        while ((line = src.readLine()) != null) {
            if (line.startsWith("#")) {
                continue; // Comment line so skip it
            }
            String opName = line.trim();
            StringBuffer sql = new StringBuffer();
            while (true) {
                line = src.readLine();
                if (line == null || line.trim().equals("")) {
                        // Blank line terminates sql block
                    sqlTable.setProperty(opName, sql.toString());
                    break;
                } else if (line.startsWith("#")) {
                    continue;
                } else {
                    sql.append(substitute(line.trim(), "${id}", idType));
                    sql.append("\n");
                }
            }
            if (line == null) break;        // Check if read to end of file
        }
        return sqlTable;
    }


	/** Helper function calculate op name given substitutions */
	public static String concatOpName(String opName, String attr) {
		return (opName + attr);
	}
	
	/** Helper function calculate op name given substitutions */
	public static String concatOpName(String opName, String attrA, String attrB) {
		return (opName  + attrA  + attrB);
	}

    /** Helper function substitute all occurances of macro with subs */
    public static String substitute(String line, String macro, String subs) {
        int loc = line.indexOf(macro);
        if (loc != -1) {
            return line.substring(0, loc) + subs + substitute(line.substring(loc+macro.length()),macro, subs);
        } else {
            return line;
        }
    }
    

//=======================================================================
// Internal support

    /**
     * Accessor. Returns the Properties table which maps operation names to
     * the plain text sql statements. This is using internally in the constructor.
     */
    protected Properties getSQLTable() {
        return m_sql;
    }

    /**
     * Open a resource file for reading. The file is found on the classpath.
     */
    public static BufferedReader openResourceFile(String filename) throws IOException {
        InputStream is = SQLCache.class.getClassLoader().getResourceAsStream(filename);
        if (is == null) 
            throw new IOException("Can't open resource " + filename);
        return new BufferedReader(new InputStreamReader(is, "US-ASCII"));
    }

    /**
     * Execute the given statement, return null if the statement appears to be
     * just an update or return an iterator for the result set if the statement appears
     * to be a query
     */
    protected ResultSetIterator executeSQL(PreparedStatement ps, String opname, ResultSetIterator iterator) throws SQLException {
        if (ps.execute()) {
            ResultSet rs = ps.getResultSet();
            iterator.reset(rs, ps, this, opname);
            return iterator;
        } else {
            returnPreparedSQLStatement(ps);
            return null;
        }
    }
    
    
    /**
     * Return dynamically generated SQL for the specified operation.
     * @param opname the command to generate; must start with "*", the opname and then op params.
     * @return the generated command as a String.
     */
    
    protected String genSQLStatement ( String opname ) throws SQLException {
    	/* for testing. for now, we only generate one operation, findReif,
    	 * to find reified statements from a triple match pattern.
    	 */
    	String sql = "";
    	boolean badop = false;
    	if ( opname.startsWith("*") ) {
    		// a space separate the operation name from its parameters.
    		int delim = opname.indexOf(' ');
    		String op = opname.substring(1,delim);
    		String args = opname.substring(delim+1);
    		if ( op.equals("findReif") ) {
    			sql = genSQLStmtFindReif(op,args);
    		} else badop = true;
    	} else badop = true;
    	if ( badop ) {
			logger.error("Unable to generate SQL for operation: " + opname);
			throw new JenaException("Unable to generate SQL for operation: " + opname);
    	}   	
    	return sql;    	
    }
    
	/**
	 * Return generate SQL for finding reified statements from a triple pattern.
	 * @param op the command to generate. should be findReif.
	 * @param args a string describing which command to generate. 
	 * it has the form [N][PS|PP|PO|PT][O[C]] where N means to search
	 * for the statement URI; Px means to search for reified subjects, properties,
	 * objects or types; O means to search for reified objects; OC means the object
	 * value is rdf:Statement.
	 */
    
	protected String genSQLStmtFindReif ( String op, String args ) throws SQLException {
		/* for a reified triple pattern <S,P,O>, there are 8 cases.
		 * 1. <-,-,->	this means retrieve all reified triples. args="".
		 * 2. <S,-,->	retrieve all reified triples for this subject. args="N".
		 * 3. <S,-,O>	retrieve all reified triples for this subject and
		 * 				object value. args="NO" or "NOC".
		 * 4. <-,-,O>	retrieve all reified triples with this object value.
		 * 				args="O" or "OC"
		 * 5. <-,P,->	retrieve all reified triples with this property. args="Px".
		 * 				property must be either rdf:subject, rdf:predicate,
		 * 				rdf:object, rdf:type.
		 * 6. <-,P,O>	retrieve all reified triples with this property and object
		 * 				value. args="PxO" or "PxOC".
		 * 7. <S,P,->	retrieve all reified triples with this subject and property.
		 * 				args="NPx".
		 * 8. <S,P,O>	retrieve all reified triples with this subject, property and
		 * 				object value. args="NPxO" or "NPxOC".
		 */

		String stmtStr = getSQLStatement("selectReified");
		String qual = "";
		IRDBDriver driver = m_connection.getDriver();
		
		if ( args.equals("") ) {
			// case 1 <-,-,->  nothing to do.
		} else {
			int ix = 0;
			boolean hasSubj = false;
			boolean hasProp = false;
			boolean hasObj = false;
			boolean objIsStmt = false;
			char reifProp = ' ';
			int argLen = args.length();
			
			if ( args.charAt(ix) == 'N' ) {
				hasSubj = true;
				ix++;
			}
			hasProp = (ix < argLen) && (args.charAt(ix) == 'P');
			if ( hasProp && (ix < argLen) ) {
				ix++;
				reifProp = args.charAt(ix++);
			}
			hasObj = (ix < argLen) && (args.charAt(ix) == 'O');
			if ( hasObj ) {
				ix++;
				objIsStmt = (ix < argLen) && (args.charAt(ix) == 'C');
			}
			if ( !hasProp ) {
				if ( hasSubj ) {
					// cases 2 and 3
					qual += driver.genSQLReifQualStmt();
					if ( hasObj ) {
						// case 3 above
						qual += " AND " + driver.genSQLReifQualAnyObj(objIsStmt);
					}			
				} else {
					// case 4 above
					qual += driver.genSQLReifQualAnyObj(objIsStmt);
				}
			} else {
				// have a reified property
				if ( hasSubj ) qual += driver.genSQLReifQualStmt() + " AND ";
				qual += driver.genSQLReifQualObj(reifProp,hasObj);
			}
			stmtStr += " AND " + qual;		
		}
		return stmtStr;
	}
	
}

/*
 *  (c) Copyright 2002, 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 + -