Search in sources :

Example 31 with AtomSetException

use of fr.lirmm.graphik.graal.api.core.AtomSetException in project graal by graphik-team.

the class AdHocRdbmsStore method add.

// /////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
// /////////////////////////////////////////////////////////////////////////
private void add(Statement statement, Term term) throws AtomSetException {
    try {
        List<DBColumn> cols = TERMS_TABLE.getColumns();
        Map<String, String> data = new TreeMap<String, String>();
        data.put(cols.get(0).getName(), '\'' + StringUtils.addSlashes(term.getIdentifier().toString()) + '\'');
        data.put(cols.get(1).getName(), '\'' + getType(term) + '\'');
        String query = this.getDriver().getInsertOrIgnoreQuery(TERMS_TABLE, data);
        statement.executeUpdate(query);
    } catch (SQLException e) {
        throw new AtomSetException("Error during insertion of a term: " + term, e);
    }
}
Also used : SQLException(java.sql.SQLException) AtomSetException(fr.lirmm.graphik.graal.api.core.AtomSetException) DBColumn(fr.lirmm.graphik.graal.store.rdbms.util.DBColumn) TreeMap(java.util.TreeMap)

Example 32 with AtomSetException

use of fr.lirmm.graphik.graal.api.core.AtomSetException in project graal by graphik-team.

the class AdHocRdbmsStore method match.

@Override
public CloseableIterator<Atom> match(Atom atom) throws AtomSetException {
    ConjunctiveQuery query = DefaultConjunctiveQueryFactory.instance().create(new LinkedListAtomSet(atom));
    SqlHomomorphism solver = SqlHomomorphism.instance();
    try {
        return new SubstitutionIterator2AtomIterator(atom, solver.execute(query, this));
    } catch (HomomorphismException e) {
        throw new AtomSetException(e);
    }
}
Also used : HomomorphismException(fr.lirmm.graphik.graal.api.homomorphism.HomomorphismException) AtomSetException(fr.lirmm.graphik.graal.api.core.AtomSetException) LinkedListAtomSet(fr.lirmm.graphik.graal.core.atomset.LinkedListAtomSet) SqlHomomorphism(fr.lirmm.graphik.graal.store.rdbms.homomorphism.SqlHomomorphism) SubstitutionIterator2AtomIterator(fr.lirmm.graphik.graal.core.stream.SubstitutionIterator2AtomIterator) ConjunctiveQuery(fr.lirmm.graphik.graal.api.core.ConjunctiveQuery)

Example 33 with AtomSetException

use of fr.lirmm.graphik.graal.api.core.AtomSetException in project graal by graphik-team.

the class AdHocConjunctiveQueryTranslator method translate.

// /////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS
// /////////////////////////////////////////////////////////////////////////
@Override
public SQLQuery translate(ConjunctiveQuery cquery) throws AtomSetException {
    if (cquery.getAtomSet().isEmpty()) {
        return SQLQuery.emptyInstance();
    }
    AtomSet atomSet = cquery.getAtomSet();
    StringBuilder fields = new StringBuilder();
    StringBuilder tables = new StringBuilder();
    StringBuilder where = new StringBuilder();
    HashMap<Atom, String> tableNames = new HashMap<Atom, String>();
    HashMap<String, String> lastOccurrence = new HashMap<String, String>();
    ArrayList<String> constants = new ArrayList<String>();
    ArrayList<String> equivalences = new ArrayList<String>();
    TreeMap<Term, String> columns = new TreeMap<Term, String>();
    int count = -1;
    CloseableIterator<Atom> it = atomSet.iterator();
    try {
        while (it.hasNext()) {
            Atom atom = it.next();
            String tableName = "atom" + ++count;
            tableNames.put(atom, tableName);
        }
        // Create WHERE clause
        it = atomSet.iterator();
        while (it.hasNext()) {
            Atom atom = it.next();
            String currentAtom = tableNames.get(atom) + ".";
            int position = 0;
            for (Term term : atom.getTerms()) {
                String thisTerm = currentAtom + AbstractRdbmsConjunctiveQueryTranslator.PREFIX_TERM_FIELD + position;
                if (term.isConstant()) {
                    constants.add(thisTerm + " = '" + term.getIdentifier().toString() + "'");
                } else {
                    if (lastOccurrence.containsKey(term.getIdentifier().toString())) {
                        equivalences.add(lastOccurrence.get(term.getIdentifier().toString()) + " = " + thisTerm);
                    }
                    lastOccurrence.put(term.getIdentifier().toString(), thisTerm);
                    if (cquery.getAnswerVariables().contains(term))
                        columns.put(term, thisTerm + " as " + term.getIdentifier().toString());
                }
                ++position;
            }
        }
    } catch (IteratorException e) {
        throw new AtomSetException(e);
    }
    for (String equivalence : equivalences) {
        if (where.length() != 0)
            where.append(" AND ");
        where.append(equivalence);
    }
    for (String constant : constants) {
        if (where.length() != 0)
            where.append(" AND ");
        where.append(constant);
    }
    // Create FROM clause
    DBTable table = null;
    for (Map.Entry<Atom, String> entries : tableNames.entrySet()) {
        if (tables.length() != 0)
            tables.append(", ");
        table = store.getPredicateTableIfExist(entries.getKey().getPredicate());
        if (table == null)
            return SQLQuery.hasSchemaErrorInstance();
        else
            tables.append(table.getName());
        tables.append(" as ");
        tables.append(entries.getValue());
    }
    // Create SELECT clause
    for (Term t : cquery.getAnswerVariables()) {
        if (fields.length() != 0)
            fields.append(", ");
        if (t.isConstant()) {
            fields.append("'");
            fields.append(t.getIdentifier());
            fields.append("'");
        } else {
            fields.append(columns.get(t));
        }
    }
    StringBuilder query = new StringBuilder("SELECT DISTINCT ");
    if (fields.length() > 0)
        query.append(fields);
    else
        query.append("1");
    query.append(" FROM ");
    if (tables.length() > 0)
        query.append(tables);
    else
        query.append(AdHocRdbmsStore.TEST_TABLE_NAME);
    if (where.length() > 0)
        query.append(" WHERE ").append(where);
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Generated SQL query :" + cquery + " --> " + query.toString());
    return new SQLQuery(query.toString());
}
Also used : IteratorException(fr.lirmm.graphik.util.stream.IteratorException) DBTable(fr.lirmm.graphik.graal.store.rdbms.util.DBTable) HashMap(java.util.HashMap) AtomSet(fr.lirmm.graphik.graal.api.core.AtomSet) ArrayList(java.util.ArrayList) Term(fr.lirmm.graphik.graal.api.core.Term) TreeMap(java.util.TreeMap) SQLQuery(fr.lirmm.graphik.graal.store.rdbms.util.SQLQuery) Atom(fr.lirmm.graphik.graal.api.core.Atom) AtomSetException(fr.lirmm.graphik.graal.api.core.AtomSetException) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) Map(java.util.Map)

Example 34 with AtomSetException

use of fr.lirmm.graphik.graal.api.core.AtomSetException in project graal by graphik-team.

the class AdHocRdbmsStore method getTerm.

@Override
public Term getTerm(String label) throws AtomSetException {
    ResultSet results;
    Term term = null;
    try {
        this.getTermStatement.setString(1, label);
        results = this.getTermStatement.executeQuery();
        if (results.next()) {
            String type = results.getString(2);
            if ("V".equals(type)) {
                term = DefaultTermFactory.instance().createVariable(results.getString(1));
            } else if ("L".equals(type)) {
                term = DefaultTermFactory.instance().createLiteral(results.getString(1));
            } else if ("C".equals(type)) {
                term = DefaultTermFactory.instance().createConstant(results.getString(1));
            } else {
                throw new AtomSetException("Unrecognized type: " + type);
            }
        }
        results.close();
    } catch (SQLException e) {
        throw new AtomSetException(e);
    }
    return term;
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) AtomSetException(fr.lirmm.graphik.graal.api.core.AtomSetException) Term(fr.lirmm.graphik.graal.api.core.Term)

Example 35 with AtomSetException

use of fr.lirmm.graphik.graal.api.core.AtomSetException in project graal by graphik-team.

the class AdHocRdbmsStore method createDatabaseSchema.

@Override
protected void createDatabaseSchema() throws AtomSetException {
    final String createPredicateTableQuery = "CREATE TABLE " + PREDICATE_TABLE_NAME + "(predicate_label varchar(" + VARCHAR_SIZE + "), predicate_arity int, " + "predicate_table_name varchar(" + VARCHAR_SIZE + "), PRIMARY KEY (predicate_label, predicate_arity));";
    final String createTermTableQuery = "CREATE TABLE " + TERMS_TABLE_NAME + " (term varchar(" + VARCHAR_SIZE + "), term_type varchar(" + VARCHAR_SIZE + "), PRIMARY KEY (term));";
    final String termTypeTableName = "term_type";
    final String createTermTypeTableQuery = "CREATE TABLE " + termTypeTableName + " (term_type varchar(" + VARCHAR_SIZE + "), PRIMARY KEY (term_type));";
    final String insertTermTypeQuery = "INSERT INTO " + termTypeTableName + " values (?);";
    Statement statement = null;
    PreparedStatement pstat = null;
    try {
        statement = this.createStatement();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Create database schema");
        statement.executeUpdate("create table " + TEST_TABLE_NAME + " (i int)");
        statement.executeUpdate("insert into " + TEST_TABLE_NAME + " values (1)");
        statement.executeUpdate("create table " + EMPTY_TABLE_NAME + " (i int)");
        if (LOGGER.isDebugEnabled())
            LOGGER.debug(createPredicateTableQuery);
        statement.executeUpdate(createPredicateTableQuery);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug(createTermTypeTableQuery);
        statement.executeUpdate(createTermTypeTableQuery);
        pstat = this.getConnection().prepareStatement(insertTermTypeQuery);
        String[] types = { "V", "C", "L" };
        for (int i = 0; i < types.length; ++i) {
            pstat.setString(1, types[i].toString());
            pstat.addBatch();
        }
        pstat.executeBatch();
        pstat.close();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug(createTermTableQuery);
        statement.executeUpdate(createTermTableQuery);
        final String createCounterTableQuery = "CREATE TABLE " + COUNTER_TABLE_NAME + " (counter_name varchar(64), value BIGINT, PRIMARY KEY (counter_name));";
        if (LOGGER.isDebugEnabled())
            LOGGER.debug(createCounterTableQuery);
        statement.executeUpdate(createCounterTableQuery);
    } catch (SQLException e) {
        throw new AtomSetException(e.getMessage(), e);
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new AtomSetException(e);
            }
        }
    }
    try {
        final String insertCounterTableQuery = "INSERT INTO " + COUNTER_TABLE_NAME + " values (?, -1);";
        final String[] counters = { MAX_PREDICATE_ID_COUNTER, MAX_VARIABLE_ID_COUNTER };
        pstat = this.getConnection().prepareStatement(insertCounterTableQuery);
        for (int i = 0; i < counters.length; ++i) {
            pstat.setString(1, counters[i]);
            pstat.addBatch();
        }
        pstat.executeBatch();
        this.getConnection().commit();
    } catch (SQLException e) {
        throw new AtomSetException(e.getMessage(), e);
    } finally {
        if (pstat != null) {
            try {
                pstat.close();
            } catch (SQLException e) {
                throw new AtomSetException(e);
            }
        }
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) AtomSetException(fr.lirmm.graphik.graal.api.core.AtomSetException) PreparedStatement(java.sql.PreparedStatement)

Aggregations

AtomSetException (fr.lirmm.graphik.graal.api.core.AtomSetException)69 IteratorException (fr.lirmm.graphik.util.stream.IteratorException)26 SQLException (java.sql.SQLException)26 Atom (fr.lirmm.graphik.graal.api.core.Atom)25 Term (fr.lirmm.graphik.graal.api.core.Term)23 HomomorphismException (fr.lirmm.graphik.graal.api.homomorphism.HomomorphismException)12 Substitution (fr.lirmm.graphik.graal.api.core.Substitution)11 Statement (java.sql.Statement)11 DBTable (fr.lirmm.graphik.graal.store.rdbms.util.DBTable)10 Predicate (fr.lirmm.graphik.graal.api.core.Predicate)9 BacktrackException (fr.lirmm.graphik.graal.homomorphism.BacktrackException)9 ConjunctiveQuery (fr.lirmm.graphik.graal.api.core.ConjunctiveQuery)7 TreeSet (java.util.TreeSet)7 SQLQuery (fr.lirmm.graphik.graal.store.rdbms.util.SQLQuery)6 CloseableIteratorAdapter (fr.lirmm.graphik.util.stream.CloseableIteratorAdapter)6 RuleApplicationException (fr.lirmm.graphik.graal.api.forward_chaining.RuleApplicationException)5 LinkedListAtomSet (fr.lirmm.graphik.graal.core.atomset.LinkedListAtomSet)5 TreeMap (java.util.TreeMap)5 AtomSet (fr.lirmm.graphik.graal.api.core.AtomSet)4 Variable (fr.lirmm.graphik.graal.api.core.Variable)4