KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > db > impl > PSet_TripleStore_RDB


1 /*
2   (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
3   [See end of file]
4   $Id: PSet_TripleStore_RDB.java,v 1.51 2005/03/17 10:11:14 chris-dollin Exp $
5 */

6
7 package com.hp.hpl.jena.db.impl;
8
9 import java.sql.PreparedStatement JavaDoc;
10 import java.sql.ResultSet JavaDoc;
11 import java.sql.SQLException JavaDoc;
12 import java.util.*;
13
14 import com.hp.hpl.jena.db.RDFRDBException;
15 import com.hp.hpl.jena.db.impl.DriverRDB;
16 import com.hp.hpl.jena.graph.*;
17 import com.hp.hpl.jena.shared.*;
18 import com.hp.hpl.jena.util.iterator.ExtendedIterator;
19
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22
23 //=======================================================================
24
/**
25 * Handles Physical storage for implementing SpecializedGraphs.
26 * Different PSet classes are needed for different databases and different
27 * layout schemes.
28 * <p>
29 * This class is a base implemention from which database-specific
30 * drivers can inherit. It is not generic in the sense that it will work
31 * on any minimal SQL store and so should be treated as if it were
32 * an abstract class.
33 * <p>The SQL statements which implement each of the functions are
34 * loaded in a separate file etc/[layout]_[database].sql from the classpath.
35 * See {@link SQLCache SQLCache documentation} for more information on the
36 * format of this file.
37 *
38 * Based on Driver* classes by Dave Reynolds.
39 *
40 * @author <a HREF="mailto:harumi.kuno@hp.com">Harumi Kuno</a>
41 * @version $Revision: 1.51 $ on $Date: 2005/03/17 10:11:14 $
42 */

43
44 public class PSet_TripleStore_RDB implements IPSet {
45
46 //=======================================================================
47
// Cutomization variables
48

49    /**
50     * Holds name of AssertedStatement table (defaults to JENA_SYS_AssStatements).
51     * Every triple store has at least one tables for AssertedStatements.
52     */

53    public String JavaDoc m_tblName = null;
54    
55     /** The SQL type to use for storing ids (compatible with wrapDBID) */
56     protected String JavaDoc ID_SQL_TYPE = null;
57
58     /** Set to true if the insert operations already check for duplications */
59     protected boolean SKIP_DUPLICATE_CHECK = false;
60
61     /** Set to true to enable cache of pre-prepared statements */
62     protected boolean CACHE_PREPARED_STATEMENTS = true;
63
64     /** The table of sql driver statements */
65     protected SQLCache m_sql = null;
66     
67 //=======================================================================
68
// Internal variables
69

70     /** default size for literal and resource caches */
71     protected final static int DEFAULT_CACHE = 1000;
72
73     /** Cache of literals */
74     protected ICache literalCache = new SimpleCache(DEFAULT_CACHE);
75
76     /** Cache of resources */
77     protected ICache resourceCache = new SimpleCache(DEFAULT_CACHE);
78     
79     /**
80      * The IRDBDriver for the database.
81      */

82     protected IRDBDriver m_driver = null;
83     
84 //=======================================================================
85
// Constructors and accessors
86

87     /**
88      * Constructor.
89      */

90     public PSet_TripleStore_RDB(){
91     }
92             
93     /**
94      * Link an existing instance of the IPSet to a specific driver
95      */

96     public void setDriver(IRDBDriver driver) throws RDFRDBException {
97         m_driver = driver;
98     }
99
100     protected static Log logger = LogFactory.getLog(PSet_TripleStore_RDB.class);
101     
102     public void setSQLType(String JavaDoc value) { ID_SQL_TYPE = value; }
103     public void setSkipDuplicateCheck(boolean value) { SKIP_DUPLICATE_CHECK = value;}
104     public void setSQLCache(SQLCache cache ) { m_sql = cache; }
105     public SQLCache getSQLCache() { return m_sql; }
106     public void setCachePreparedStatements(boolean value) { CACHE_PREPARED_STATEMENTS = value; }
107     
108     
109     /**
110      * Sets m_tblName variable.
111      * @param tblName the name of the Statement Table
112      */

113     public void setTblName(String JavaDoc tblName){
114         m_tblName = tblName;
115     }
116     
117     /**
118      * Accessor for m_tblName.
119      * @return name of the Statement table.
120      */

121     public String JavaDoc getTblName() {
122         return m_tblName;
123     }
124     
125
126     /**
127      * Close this PSet
128      */

129     public void close() {
130         // no need to do anything here for now
131
}
132     
133     /**
134      * @return the database driver.
135      */

136
137     public IRDBDriver driver() {
138         return m_driver;
139     }
140
141     
142     /**
143      * Remove all RDF information about this pset from a database.
144      */

145     public void cleanDB() {
146         
147         // drop my own table(s)
148
try {
149             m_sql.runSQLGroup("dropStatementTable",getTblName());
150         } catch (SQLException JavaDoc e) {
151             logger.warn( "Problem dropping table " + getTblName(), e );
152             throw new RDFRDBException("Failed to drop table ", e);
153         }
154                     
155     }
156
157      /**
158       * Printable name for the driver configuration
159       */

160      public String JavaDoc toString() {
161         return this.getClass().getPackage().getName();
162      }
163      
164     /**
165      * Fetch a literal from the cache just knowing its literal rdb-id.
166      * If it is not in the cache, do not attempt to retrieve it from the database.
167      */

168     public Node_Literal getLiteralFromCache(IDBID id) {
169         return (Node_Literal) literalCache.get(id);
170     }
171
172     /**
173      * Convert the raw SQL object used to store a database identifier into a java object
174      * which meets the IDBID interface.
175      */

176     public IDBID wrapDBID(Object JavaDoc id) throws RDFRDBException {
177         if (id instanceof Number JavaDoc) {
178             return new DBIDInt(((Number JavaDoc)id).intValue());
179         } else if (id == null) {
180             return null;
181         } else {
182             throw new RDFRDBException("Unexpected DB identifier type: " + id);
183             //return null;
184
}
185     }
186     
187     /**
188      * Compute the number of rows in a table.
189      *
190      * @return int count.
191      */

192     public int rowCount(String JavaDoc tName) {
193
194     try {
195         int result = 0;
196          String JavaDoc op = "getRowCount";
197          PreparedStatement JavaDoc ps = m_sql.getPreparedSQLStatement(op,tName);
198          ResultSet JavaDoc rs = ps.executeQuery();
199          while ( rs.next() ) result = rs.getInt(1);
200          rs.close();
201         m_sql.returnPreparedSQLStatement(ps);
202         return result;
203     } catch (SQLException JavaDoc e) {
204        logger.debug("tried to count rows in " + tName);
205        logger.debug("Caught exception: ", e);
206            throw new JenaException("Exception during database access", e); // Rethrow in case there is a recovery option
207
}
208     }
209
210     //=======================================================================
211
// Patched functions to adapt to oracle jdbc driver expectations
212

213     /**
214      * Convert the current row of a result set from a ResultSet
215      * to a Triple.
216      * Expects row to contain:
217      * S.SubjRes, S.PropRes, S.ObjRes, S.ObjStr, S.ObjLiteral
218      * @param rs the resultSet to be processed.
219      */

220     public Triple extractTripleFromRowData(
221         String JavaDoc subj,
222         String JavaDoc pred,
223         String JavaDoc obj) {
224         
225         Node subjNode = subj == null ? null : m_driver.RDBStringToNode(subj);
226         Node predNode = pred == null ? null : m_driver.RDBStringToNode(pred);
227         Node objNode = obj == null ? null : m_driver.RDBStringToNode(obj);
228
229         return ( Triple.create(subjNode, predNode, objNode) );
230     }
231
232
233
234     /**
235      * Wrap up a boolean flag as a object which the jdbc driver can assert into a boolean/short column.
236      */

237     public Object JavaDoc wrapFlag(boolean flag) {
238         return flag ? new Short JavaDoc((short)1) : new Short JavaDoc((short)0);
239     }
240     
241     /**
242      *
243      * Attempt to remove a statement from an Asserted_Statement table,
244      * if it is present. Return without error if the statement is not
245      * present.
246      *
247      * @param subj_uri is the URI of the subject
248      * @param pred_uri is the URI of the predicate (property)
249      * @param obj_node is the URI of the object (can be URI or literal)
250      * @param graphID is the ID of the graph
251      * @param complete is true if this handler is capable of adding this triple.
252      *
253      **/

254   public void deleteTriple(Triple t, IDBID graphID) {
255     deleteTriple(t, graphID, false, null);
256   }
257     
258   /**
259    *
260    * Attempt to remove a statement from an Asserted_Statement table,
261    * if it is present. Return without error if the statement is not
262    * present.
263    *
264    * @param subj_uri is the URI of the subject
265    * @param pred_uri is the URI of the predicate (property)
266    * @param obj_node is the URI of the object (can be URI or literal)
267    * @param graphID is the ID of the graph
268    * @param complete is true if this handler is capable of adding this triple.
269    *
270    **/

271     public void deleteTriple(Triple t, IDBID graphID, boolean isBatch,
272         Hashtable batchedPreparedStatements) {
273             deleteTripleAR(t,graphID,null,isBatch,batchedPreparedStatements);
274         }
275     /**
276      *
277      * Attempt to remove a statement from an Asserted_Statement table,
278      * if it is present. Return without error if the statement is not
279      * present.
280      *
281      * @param subj_uri is the URI of the subject
282      * @param pred_uri is the URI of the predicate (property)
283      * @param obj_node is the URI of the object (can be URI or literal)
284      * @param stmtURI is the URI of the statement if reified, null for asserted
285      * @param graphID is the ID of the graph
286      * @param complete is true if this handler is capable of adding this triple.
287      *
288      **/

289 public void deleteTripleAR(
290     Triple t,
291     IDBID graphID,
292     Node reifNode,
293     boolean isBatch,
294     Hashtable batchedPreparedStatements) {
295     boolean isReif = reifNode != null;
296
297     String JavaDoc subj =
298         t.getSubject().equals(Node.NULL) ? null : m_driver.nodeToRDBString(t.getSubject(),false);
299     String JavaDoc pred =
300         t.getPredicate().equals(Node.NULL) ? null : m_driver.nodeToRDBString(t.getPredicate(),false);
301     String JavaDoc obj =
302         t.getObject() == Node.ANY ? null : m_driver.nodeToRDBString(t.getObject(),false);
303 // String gid = graphID.getID().toString();
304
int gid = ((DBIDInt) graphID).getIntID();
305     int argc = 1;
306     String JavaDoc stmtStr;
307     
308     if ((subj == null) || (pred == null) || (obj == null)) {
309 // throw new JenaException("Attempt to delete triple with missing values");
310
// used to think this was an exception. i guess it's not.
311
return;
312     }
313
314     // get statement string
315
PreparedStatement JavaDoc ps = null;
316     stmtStr = isReif ? "deleteReified" : "deleteStatement";
317     try {
318         ps =
319             getPreparedStatement(
320                 stmtStr,
321                 getTblName(),
322                 isBatch,
323                 batchedPreparedStatements);
324         //ps.clearParameters();
325

326     } catch (SQLException JavaDoc e1) {
327         logger.debug( "SQLException caught " + e1.getErrorCode(), e1);
328             throw new JenaException("Exception during database access", e1); // Rethrow in case there is a recovery option
329
}
330
331     // now fill in parameters
332
try {
333         ps.setString(argc++, subj);
334         ps.setString(argc++, pred);
335         ps.setString(argc++, obj);
336
337         ps.setInt(argc++, gid);
338
339         if (isReif) {
340             String JavaDoc stmtURI = m_driver.nodeToRDBString(reifNode,false);
341             ps.setString(argc++, stmtURI);
342             ps.setString(argc++,"T");
343         }
344     } catch (SQLException JavaDoc e1) {
345         logger.debug("(in delete) SQLException caught ", e1);
346             throw new JenaException("Exception during database access", e1); // Rethrow in case there is a recovery option
347
}
348
349     try {
350         if (isBatch) {
351             ps.addBatch();
352         } else {
353             ps.executeUpdate();
354             m_sql.returnPreparedSQLStatement(ps);
355         }
356     } catch (SQLException JavaDoc e1) {
357         logger.error("Exception executing delete: ", e1);
358                 throw new JenaException("Exception during database access", e1); // Rethrow in case there is a recovery option
359
}
360 }
361
362         /**
363          *
364          * Attempt to store a statement into an Asserted_Statement table.
365          *
366          * @param subj_uri is the URI of the subject
367          * @param pred_uri is the URI of the predicate (property)
368          * @param obj_node is the URI of the object (can be URI or literal)
369          * @param graphID is the ID of the graph
370          * @param complete is true if this handler is capable of adding this triple.
371          *
372          **/

373       public void storeTriple(Triple t, IDBID graphID) {
374         storeTriple(t,graphID,false, null);
375       }
376       
377       /**
378        * Given an operation name, a table name, whether or not this operation is part of a batched update, and
379        * a table of batched prepared statements, find or create an appropriate PreparedStatement.
380        *
381        * @param op
382        * @param tableName
383        * @param isBatch
384        * @param batchedPreparedStatements
385        * @return the prepared statement
386        * @throws SQLException
387        */

388       public PreparedStatement JavaDoc getPreparedStatement(String JavaDoc op,
389                     String JavaDoc tableName,
390                     boolean isBatch,
391                     Hashtable batchedPreparedStatements) throws SQLException JavaDoc {
392         PreparedStatement JavaDoc ps = null;
393         String JavaDoc opname = SQLCache.concatOpName(op,tableName);
394         if (isBatch) {
395             ps = (PreparedStatement JavaDoc) batchedPreparedStatements.get(opname);
396             if (ps == null) {
397                 ps = m_sql.getPreparedSQLStatement(op,tableName);
398                 batchedPreparedStatements.put(opname,ps);
399             }
400         } else {
401             ps = m_sql.getPreparedSQLStatement(op,tableName);
402         }
403          
404         if (ps == null) {
405             logger.error("prepared statement not found for " + opname);
406         }
407         return ps;
408       }
409
410
411         /**
412          *
413          * Attempt to store a statement into an Asserted_Statement table.
414          *
415          * @param subj_uri is the URI of the subject
416          * @param pred_uri is the URI of the predicate (property)
417          * @param obj_node is the URI of the object (can be URI or literal)
418          * @param graphID is the ID of the graph
419          * @param isBatch is true if this request is part of a batch operation.
420          *
421          **/

422       public void storeTriple(Triple t,
423                             IDBID graphID,
424                             boolean isBatch,
425                             Hashtable batchedPreparedStatements) {
426              storeTripleAR(t,graphID,null,false,isBatch,batchedPreparedStatements);
427       }
428       
429         /**
430          *
431          * Attempt to store a statement into an Asserted_Statement table.
432          *
433          * @param subj_uri is the URI of the subject
434          * @param pred_uri is the URI of the predicate (property)
435          * @param obj_node is the URI of the object (can be URI or literal)
436          * @param stmtURI is the URI of the statement if reified, null for asserted
437          * @param hasType is true if the hasType flag should be set for a reified stmt
438          * @param graphID is the ID of the graph
439          * @param isBatch is true if this request is part of a batch operation.
440          *
441          **/

442     public void storeTripleAR(
443         Triple t,
444         IDBID graphID,
445         Node reifNode,
446         boolean hasType,
447         boolean isBatch,
448         Hashtable batchedPreparedStatements) {
449         String JavaDoc objURI;
450         Object JavaDoc obj_val;
451         boolean isReif = reifNode != null;
452
453         // if database doesn't perform duplicate check
454
if (!SKIP_DUPLICATE_CHECK && !isReif) {
455             // if statement already in table
456
if (statementTableContains(graphID, t)) {
457                 return;
458             }
459         }
460         
461         String JavaDoc obj_res, obj_lex, obj_lit;
462         // TODO: Node.NULL is only valid for reif triple stores. should check this.
463
String JavaDoc subj =
464             t.getSubject().equals(Node.NULL) ? null : m_driver.nodeToRDBString(t.getSubject(),true);
465         String JavaDoc pred =
466             t.getPredicate().equals(Node.NULL) ? null : m_driver.nodeToRDBString(t.getPredicate(),true);
467         String JavaDoc obj =
468             t.getObject().equals(Node.NULL) ? null : m_driver.nodeToRDBString(t.getObject(),true);
469 // String gid = graphID.getID().toString();
470
int gid = ((DBIDInt) graphID).getIntID();
471
472         int argc = 1;
473         String JavaDoc stmtStr;
474
475         if ((subj == null) || (pred == null) || (obj == null)) {
476             if (!isReif)
477                 throw new JenaException("Attempt to assert triple with missing values");
478         }
479         // get statement string
480

481         PreparedStatement JavaDoc ps = null;
482         stmtStr = isReif ? "insertReified" : "insertStatement";
483         try {
484             ps =
485                 getPreparedStatement(
486                     stmtStr,
487                     getTblName(),
488                     isBatch,
489                     batchedPreparedStatements);
490             //ps.clearParameters();
491

492         } catch (SQLException JavaDoc e1) {
493             logger.debug("SQLException caught " + e1.getErrorCode(), e1);
494                         throw new JenaException("Exception during database access", e1); // Rethrow in case there is a recovery option
495
}
496         // now fill in parameters
497
try {
498             if (subj == null)
499                 ps.setNull(argc++, java.sql.Types.VARCHAR);
500             else
501                 ps.setString(argc++, subj);
502             if (pred == null)
503                 ps.setNull(argc++, java.sql.Types.VARCHAR);
504             else
505                 ps.setString(argc++, pred);
506             if (obj == null)
507                 ps.setNull(argc++, java.sql.Types.VARCHAR);
508             else
509                 ps.setString(argc++, obj);
510
511             // add graph id and, if reifying, stmturi and hastype
512
ps.setInt(argc++, gid);
513             if (isReif) {
514                 String JavaDoc stmtURI = m_driver.nodeToRDBString(reifNode,true);
515                 ps.setString(argc++, stmtURI);
516                 if (hasType == true)
517                     ps.setString(argc++, "T");
518                 else
519                     ps.setString(argc++, " "); // not nullable
520
}
521
522         } catch (SQLException JavaDoc e1) {
523             logger.debug("SQLException caught " + e1.getErrorCode(), e1);
524                         throw new JenaException("Exception during database access", e1); // Rethrow in case there is a recovery option
525
}
526
527         try {
528             if (isBatch) {
529                 ps.addBatch();
530             } else {
531                 ps.executeUpdate();
532                 m_sql.returnPreparedSQLStatement(ps);
533             }
534             //ps.close();
535
} catch (SQLException JavaDoc e1) {
536             // we let Oracle handle duplicate checking
537
if (!((e1.getErrorCode() == 1)
538                 && (m_driver.getDatabaseType().equalsIgnoreCase("oracle")))) {
539                 logger.error(
540                     "SQLException caught during insert"
541                         + e1.getErrorCode(),
542                         e1);
543                           throw new JenaException("Exception during database access", e1 );
544             }
545         }
546     }
547     
548     /**
549      * Attempt to add a list of triples to the specialized graph.
550      *
551      * As each triple is successfully added it is removed from the List. If
552      * complete is true then the entire List was added and the List will be
553      * empty upon return. if complete is false, then at least one triple remains
554      * in the List.
555      *
556      * If a triple can't be stored for any reason other than incompatability
557      * (for example, a lack of disk space) then the implemenation should throw a
558      * runtime exception.
559      *
560      * @param triples
561      * List of triples to be added. This is modified by the call.
562      * @param my_GID
563      * ID of the graph.
564      */

565     public void storeTripleList(List triples, IDBID my_GID) {
566         // for relational dbs, there are two styles for bulk inserts.
567
// JDBC 2.0 supports batched updates.
568
// MySQL also supports a multiple-row insert.
569
// For now, we support only jdbc 2.0 batched updates
570
/** Set of PreparedStatements that need executeBatch() * */
571 // Hashtable batchedPreparedStatements = new Hashtable();
572
Triple t;
573         String JavaDoc cmd;
574         boolean autoState = false;
575         DriverRDB drvr = (DriverRDB) m_driver;
576 // try {
577
autoState = drvr.xactOp(DriverRDB.xactAutoOff);
578
579             Iterator it = triples.iterator();
580
581             while (it.hasNext()) {
582                 t = (Triple) it.next();
583                 // storeTriple(t, my_GID, true, batchedPreparedStatements);
584
storeTriple(t, my_GID, false, null);
585             }
586 /*
587             Enumeration enum = batchedPreparedStatements.keys();
588             while (enum.hasMoreElements()) {
589                 String op = (String) enum.nextElement();
590                 PreparedStatement p = (PreparedStatement) batchedPreparedStatements
591                         .get(op);
592                 p.executeBatch();
593                 m_sql.returnPreparedSQLStatement(p);
594             }
595 */

596             if (autoState)
597                 drvr.xactOp(DriverRDB.xactCommit);
598
599 // batchedPreparedStatements = new Hashtable();
600
ArrayList c = new ArrayList(triples);
601             triples.removeAll(c);
602         
603         // WARNING: caught exceptions should drop through to return.
604
// if not, be sure to reset autocommit before exiting.
605
/*
606         } catch (BatchUpdateException b) {
607             System.err.println("SQLException: " + b.getMessage());
608             System.err.println("SQLState: " + b.getSQLState());
609             System.err.println("Message: " + b.getMessage());
610             System.err.println("Vendor: " + b.getErrorCode());
611             System.err.print("Update counts: ");
612             int[] updateCounts = b.getUpdateCounts();
613             for (int i = 0; i < updateCounts.length; i++) {
614                 System.err.print(updateCounts[i] + " ");
615             }
616         } catch (SQLException ex) {
617             System.err.println("SQLException: " + ex.getMessage());
618             System.err.println("SQLState: " + ex.getSQLState());
619             System.err.println("Message: " + ex.getMessage());
620             System.err.println("Vendor: " + ex.getErrorCode());
621         }
622 */

623         if (autoState)
624             drvr.xactOp(DriverRDB.xactAutoOn);
625     }
626
627     /**
628      * Attempt to remove a list of triples from the specialized graph.
629      *
630      * As each triple is successfully deleted it is removed from the List. If
631      * complete is true then the entire List was added and the List will be
632      * empty upon return. if complete is false, then at least one triple remains
633      * in the List.
634      *
635      * If a triple can't be stored for any reason other than incompatability
636      * (for example, a lack of disk space) then the implemenation should throw a
637      * runtime exception.
638      *
639      * @param triples
640      * List of triples to be added. This is modified by the call.
641      * @param my_GID
642      * ID of the graph.
643      */

644     public void deleteTripleList(List triples, IDBID my_GID) {
645         // for relational dbs, there are two styles for bulk operations.
646
// JDBC 2.0 supports batched updates.
647
// MySQL also supports a multiple-row update.
648
// For now, we support only jdbc 2.0 batched updates
649

650         /** Set of PreparedStatements that need executeBatch() * */
651 // Hashtable batchedPreparedStatements = new Hashtable();
652
Triple t;
653         String JavaDoc cmd;
654         boolean autoState = false;
655         DriverRDB drvr = (DriverRDB) m_driver;
656 // try {
657
autoState = drvr.xactOp(DriverRDB.xactAutoOff);
658             Iterator it = triples.iterator();
659
660             while (it.hasNext()) {
661                 t = (Triple) it.next();
662                 // deleteTriple(t, my_GID, true, batchedPreparedStatements);
663
deleteTriple(t, my_GID, false, null);
664             }
665
666 /*
667             Enumeration enum = batchedPreparedStatements.keys();
668             while (enum.hasMoreElements()) {
669                 String op = (String) enum.nextElement();
670                 PreparedStatement p = (PreparedStatement) batchedPreparedStatements
671                         .get(op);
672                 p.executeBatch();
673                 // m_sql.returnPreparedSQLStatement(p,op);
674             }
675 */

676
677             if (autoState)
678                 drvr.xactOp(DriverRDB.xactCommit);
679
680             // batchedPreparedStatements = new Hashtable();
681
ArrayList c = new ArrayList(triples);
682             triples.removeAll(c);
683             
684         // WARNING: caught exceptions should drop through to return.
685
// if not, be sure to reset autocommit before exiting.
686
/*
687     } catch (BatchUpdateException b) {
688             System.err.println("SQLException: " + b.getMessage());
689             System.err.println("SQLState: " + b.getSQLState());
690             System.err.println("Message: " + b.getMessage());
691             System.err.println("Vendor: " + b.getErrorCode());
692             System.err.print("Update counts: ");
693             int[] updateCounts = b.getUpdateCounts();
694             for (int i = 0; i < updateCounts.length; i++) {
695                 System.err.print(updateCounts[i] + " ");
696             }
697         } catch (SQLException ex) {
698             System.err.println("SQLException: " + ex.getMessage());
699             System.err.println("SQLState: " + ex.getSQLState());
700             System.err.println("Message: " + ex.getMessage());
701             System.err.println("Vendor: " + ex.getErrorCode());
702         }
703 */

704         if (autoState)
705             drvr.xactOp(DriverRDB.xactAutoOn);
706     }
707
708     /**
709      * Compute the number of unique triples added to the Specialized Graph.
710      *
711      * @return int count.
712      */

713     public int tripleCount() {
714         return(rowCount(getTblName()));
715     }
716     
717
718     /**
719      * Tests if a triple is contained in the specialized graph.
720      * @param t is the triple to be tested
721      * @param graphID is the id of the graph.
722      * @return boolean result to indicte if the tripple was contained
723      */

724     public boolean statementTableContains(IDBID graphID, Triple t) {
725        ExtendedIterator it = find( t, graphID );
726        boolean res = it.hasNext();
727        it.close();
728        return res;
729     }
730     
731     /* (non-Javadoc)
732      * @see com.hp.hpl.jena.db.impl.IPSet#find(com.hp.hpl.jena.graph.TripleMatch, com.hp.hpl.jena.db.impl.IDBID)
733      */

734     public ExtendedIterator find(TripleMatch t, IDBID graphID) {
735         String JavaDoc astName = getTblName();
736         Node subj_node = t.getMatchSubject();
737         Node pred_node = t.getMatchPredicate();
738         Node obj_node = t.getMatchObject();
739         Node_Literal objLit;
740         // String gid = graphID.getID().toString();
741
int gid = ((DBIDInt) graphID).getIntID();
742         boolean notFound = false;
743 int hack = 0;
744
745         ResultSetTripleIterator result =
746             new ResultSetTripleIterator(this, graphID);
747
748         PreparedStatement JavaDoc ps = null;
749
750         String JavaDoc subj = null;
751         String JavaDoc pred = null;
752         String JavaDoc obj = null;
753         String JavaDoc op = "selectStatement";
754         String JavaDoc qual = "";
755         int args = 1;
756 if ( hack != 0 ) {
757     subj_node = pred_node = obj_node = null;
758 }
759         if (subj_node != null) {
760             subj = m_driver.nodeToRDBString(subj_node, false);
761             if (subj == null)
762                 notFound = true;
763             else
764                 qual += "S";
765         }
766         if (pred_node != null) {
767             pred = m_driver.nodeToRDBString(pred_node, false);
768             if (pred == null)
769                 notFound = true;
770             else
771                 qual += "P";
772         }
773         if (obj_node != null) {
774             obj = m_driver.nodeToRDBString(obj_node, false);
775             if (obj == null)
776                 notFound = true;
777             else
778                 qual += "O";
779         }
780         if (notFound == false)
781             try {
782                 op += qual;
783                 /*
784                 ps = m_sql.getPreparedSQLStatement(op, getTblName());
785                 if ( qual.equals("") ) {
786                     ps = m_sql.getPreparedSQLStatement(op+"Limit", getTblName(),Integer.toString(gid));
787                 
788                     // Statement stmt = m_driver.getConnection().getConnection().createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
789                     // java.sql.ResultSet.CONCUR_READ_ONLY);
790                     // stmt.setFetchSize(10);
791                     // String qry = "SELECT S.Subj, S.Prop, S.Obj FROM " + getTblName() + " S WHERE S.GraphID = "
792                     // + gid;
793                     // ResultSet res = stmt.executeQuery(qry);
794                     result = new ResultSetLimitTripleIter(this, graphID);
795                 } else {
796                 //*/

797                 ps = m_sql.getPreparedSQLStatement(op, getTblName());
798                 if (obj != null)
799                     ps.setString(args++, obj);
800                 if (subj != null)
801                     ps.setString(args++, subj);
802                 if (pred != null)
803                     ps.setString(args++, pred);
804
805                 ps.setInt(args++, gid);
806                 //*/ }
807
m_sql.executeSQL(ps, op, result);
808
809                 //m_sql.returnPreparedSQLStatement(ps,op);
810
} catch (Exception JavaDoc e) {
811                 notFound = true;
812                 logger.debug( "find encountered exception: args=" + args + " err: ", e);
813                                 throw new JenaException("Exception during database access", e); // Rethrow in case there is a recovery option
814
}
815
816         if ( notFound ) result.close();
817         return (new TripleMatchIterator(t.asTriple(), result));
818     }
819
820         /* (non-Javadoc)
821          * @see com.hp.hpl.jena.graphRDB.IPSet#removeStatementsFromDB()
822          */

823         public void removeStatementsFromDB(IDBID graphID) {
824             String JavaDoc gid = graphID.getID().toString();
825             
826             try {
827                   PreparedStatement JavaDoc ps = m_sql.getPreparedSQLStatement("removeRowsFromTable",getTblName());
828                   ps.clearParameters();
829     
830                   ps.setString(1,gid);
831                   ps.executeUpdate();
832                  } catch (SQLException JavaDoc e) {
833                     logger.error("Problem removing statements from table: ", e);
834                                         throw new JenaException("Exception during database access", e); // Rethrow in case there is a recovery option
835
}
836         }
837 }
838
839 /*
840  * (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
841  * All rights reserved.
842  *
843  * Redistribution and use in source and binary forms, with or without
844  * modification, are permitted provided that the following conditions
845  * are met:
846  * 1. Redistributions of source code must retain the above copyright
847  * notice, this list of conditions and the following disclaimer.
848  * 2. Redistributions in binary form must reproduce the above copyright
849  * notice, this list of conditions and the following disclaimer in the
850  * documentation and/or other materials provided with the distribution.
851  * 3. The name of the author may not be used to endorse or promote products
852  * derived from this software without specific prior written permission.
853
854  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
855  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
856  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
857  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
858  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
859  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
860  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
861  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
862  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
863  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
864  */

865     
866  
867
Popular Tags