Package com.almworks.sqlite4java

Examples of com.almworks.sqlite4java.SQLiteConnection


  private SQLiteConnection db;

  private Db() throws SQLiteException
  {
    db = new SQLiteConnection(new File("projects"));
    db.open(true);
  }
View Full Code Here


  static {
    System.setProperty("sqlite4java.library.path", WinLinMacApi.locateExecutable());
  }

  public DataConnector(File databaseFile) throws SQLiteException {
    connection = new SQLiteConnection(databaseFile);
    connection.open(true);

    connection.prepare(
        "CREATE TABLE IF NOT EXISTS " + TABLE_USERS + " " +
            "("  +
View Full Code Here

    // have some pending connections to close...
    if(pendingClose != null && pendingClose.size() > 0) {
      synchronized(pendingClose) {
        Iterator<SQLiteConnection> it = pendingClose.iterator();
        while(it.hasNext()) {
          SQLiteConnection conn = it.next();
          log.info("-- Closed a connection pending diposal: " + conn.getDatabaseFile());
          conn.dispose();
          it.remove();
        }
      }
    }

    SQLiteStatement st = null;
    try {
      SQLiteConnection conn = db.get();
      if(timeoutThread != null) {
        timeoutThread.startQuery(conn, query);
      }
      // We don't want to cache the statements here so we use "false"
      // Don't use the method without boolean because it will use cached = true!!!
      st = conn.prepare(query, false);
      if(timeoutThread != null) {
        timeoutThread.endQuery(conn);
      }
      List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
      if(st.step()) {
View Full Code Here

          try {
            Thread.sleep((long)(Math.random()*4000));
          } catch(InterruptedException e2) {
            e2.printStackTrace();
          }
          SQLiteConnection conn = mock(SQLiteConnection.class);
          timeoutThread.startQuery(conn, "MyQuery" + this.getName());
          try {
            Thread.sleep(2000);
          } catch(InterruptedException e1) {
            e1.printStackTrace();
View Full Code Here

          try {
            Thread.sleep((long)(Math.random()*4000));
          } catch(InterruptedException e2) {
            e2.printStackTrace();
          }
          SQLiteConnection conn = mock(SQLiteConnection.class);
          timeoutThread.startQuery(conn, "MyQuery" + this.getName());
          try {
            Thread.sleep(4000);
          } catch(InterruptedException e1) {
            e1.printStackTrace();
View Full Code Here

    try {
      while(true) {
        long now = System.currentTimeMillis();
        Iterator<SQLiteConnection> it = connections.iterator();
        while(it.hasNext()) {
          SQLiteConnection conn = it.next();
          QueryAndTime queryAndTime = currentQueries.get(conn);
          long time = queryAndTime.time;
          if(time < 0) { // means this connection is not active
            continue;
          }
          synchronized(conn) {
            if((now - time) > timeout) {
              // Timeout: we should interrupt this connection!

              try {

                /*
                 * Even though SQLiteConnections are not thread-safe, this method *IS* thread-safe and that's why we can
                 * implement this thread. The thread that launched the query is busy waiting for the result so another
                 * thread must interrupt it!
                 *
                 * SQLite4Java docs:
                 * http://almworks.com/sqlite4java/javadoc/com/almworks/sqlite4java/SQLiteConnection.html#interrupt()
                 * SQLite docs: http://www.sqlite.org/c3ref/interrupt.html
                 */
                log.info("Long running query [" + queryAndTime.query + "] ran for more than ["
                    + timeout + "] ms. Interrupting it!");
                conn.interrupt();
              } catch(SQLiteException e) {
                //
              } finally {
                queryAndTime.query = null;
                queryAndTime.time = -1l; // connection will not be considered until a new query is executed
View Full Code Here

  // This method is called one time per each partition
  public void initPartition(int partition, Path local) throws IOException, InterruptedException {
    try {
      LOG.info("Initializing SQL connection [" + partition + "]");
      SQLiteConnection conn = new SQLiteConnection(new File(local.toString()));
      // Change the default temp_store_directory, otherwise we may run out of disk space as it will go to /var/tmp
      // In EMR the big disks are at /mnt
      // It suffices to set it to . as it is the tasks' work directory
      // Warning: this pragma is deprecated and may be removed in further versions, however there is no choice
      // other than recompiling SQLite or modifying the environment.
      conn.open(true);
      conn.exec("PRAGMA temp_store_directory = '" + new File(".").getAbsolutePath() + "'");
      SQLiteStatement st = conn.prepare("PRAGMA temp_store_directory");
      st.step();
      LOG.info("Changed temp_store_directory to: " + st.columnString(0));
      // journal_mode=OFF speeds up insertions
      conn.exec("PRAGMA journal_mode=OFF");
      /*
       * page_size is one of of the most important parameters for speed up indexation. SQLite performs a merge sort for
       * sorting data before inserting it in an index. The buffer SQLites uses for sorting has a size equals to
       * page_size * SQLITE_DEFAULT_TEMP_CACHE_SIZE. Unfortunately, SQLITE_DEFAULT_TEMP_CACHE_SIZE is a compilation
       * parameter. That is then fixed to the sqlite4java library used. We have recompiled that library to increase
       * SQLITE_DEFAULT_TEMP_CACHE_SIZE (up to 32000 at the point of writing this lines), so, at runtime the unique way
       * to change the buffer size used for sorting is change the page_size. page_size must be changed BEFORE CREATE
       * STATEMENTS, otherwise it won't have effect. page_size should be a multiple of the sector size (1024 on linux)
       * in order to be efficient.
       */
      conn.exec("PRAGMA page_size=8192;");
      connCache.put(partition, conn);
      // Init transaction
      for(String sql : getPreSQL()) {
        LOG.info("Executing: " + sql);
        conn.exec(sql);
      }
      conn.exec("BEGIN");
      Map<String, SQLiteStatement> stMap = new HashMap<String, SQLiteStatement>();
      stCache.put(partition, stMap);
    } catch(SQLiteException e) {
      throw new IOException(e);
    } catch(SploutSQLOutputFormatException e) {
View Full Code Here

       */
      Map<String, SQLiteStatement> stMap = stCache.get(partition);

      SQLiteStatement pS = stMap.get(tuple.getSchema().getName());
      if(pS == null) {
        SQLiteConnection conn = connCache.get(partition);
        // Create a PreparedStatement according to the received Tuple
        String preparedStatement = "INSERT INTO " + tuple.getSchema().getName() + " VALUES (";
        // NOTE: tuple.getSchema().getFields().size() - 1 : quick way of skipping "_partition" fields here
        for(int i = 0; i < tuple.getSchema().getFields().size() - 1; i++) {
          preparedStatement += "?, ";
        }
        preparedStatement = preparedStatement.substring(0, preparedStatement.length() - 2) + ");";
        pS = conn.prepare(preparedStatement);
        stMap.put(tuple.getSchema().getName(), pS);
      }

      int count = 1, tupleCount = 0;
      for(Field field : tuple.getSchema().getFields()) {
        if(field.getName().equals(PARTITION_TUPLE_FIELD)) {
          tupleCount++;
          continue;
        }

        if(tuple.get(tupleCount) == null) {
          pS.bindNull(count);
        } else {
          switch(field.getType()) {

          case INT:
            pS.bind(count, (Integer) tuple.get(tupleCount));
            break;
          case LONG:
            pS.bind(count, (Long) tuple.get(tupleCount));
            break;
          case DOUBLE:
            pS.bind(count, (Double) tuple.get(tupleCount));
            break;
          case FLOAT:
            pS.bind(count, (Float) tuple.get(tupleCount));
            break;
          case STRING:
            pS.bind(count, tuple.get(tupleCount).toString());
            break;
          case BOOLEAN: // Remember: In SQLite there are no booleans
            pS.bind(count, ((Boolean) tuple.get(tupleCount)) == true ? 1 : 0);
          default:
            break;
          }
        }
        count++;
        tupleCount++;
      }
      pS.step();
      pS.reset();

      records++;
      if(records == getBatchSize()) {
        SQLiteConnection conn = connCache.get(partition);
        conn.exec("COMMIT");
        conn.exec("BEGIN");
        records = 0;
      }
    } catch(SQLiteException e) {
      throw new IOException(e);
    }
View Full Code Here

     *
     * @throws SQLiteException
     *             if the connection fails or a pragma could not be set
     */
    static SQLiteConnection openDB(String fileName, boolean readOnly) throws SQLiteException {
        SQLiteConnection db = new SQLiteConnection(new File(fileName));
        if (readOnly) {
            db.openReadonly();
        } else {
            db.open(true);
        }
        // set 1GB cache_size:
        final SQLiteStatement stmt = db.prepare("PRAGMA page_size;");
        if (stmt.step()) {
            long cacheSize = stmt.columnLong(0);
            db.exec("PRAGMA cache_size = " + (1024l*1024l*1024l / cacheSize) + ";");
        }
        stmt.dispose();
        db.exec("PRAGMA synchronous = OFF;");
        db.exec("PRAGMA journal_mode = OFF;");
//        db.exec("PRAGMA locking_mode = EXCLUSIVE;");
        db.exec("PRAGMA case_sensitive_like = true;");
        db.exec("PRAGMA encoding = 'UTF-8';");
        db.exec("PRAGMA temp_store = MEMORY;");
        return db;
    }
View Full Code Here

            String dbFileName,
            Map<String, Set<String>> templateTree,
            Map<String, Set<String>> includeTree,
            Map<String, Set<String>> referenceTree)
            throws RuntimeException {
        SQLiteConnection db = null;
        SQLiteStatement stmt = null;
        try {
            db = WikiDumpPrepareSQLiteForScalarisHandler.openDB(dbFileName, true);
            SiteInfo siteInfo = readSiteInfo(db);
            MyParsingWikiModel wikiModel = new MyParsingWikiModel("", "", new MyNamespace(siteInfo));
            stmt = db
                    .prepare("SELECT page.title, tpl.title FROM " +
                            "templates INNER JOIN pages AS page ON templates.title == page.id " +
                            "INNER JOIN pages AS tpl ON templates.template == tpl.id " +
                            "WHERE page.title LIKE '" + wikiModel.normalisePageTitle(wikiModel.getTemplateNamespace() + ":") + "%';");
            while (stmt.step()) {
                String pageTitle = stmt.columnString(0);
                String template = stmt.columnString(1);
                updateMap(templateTree, pageTitle, template);
            }
            stmt.dispose();
            stmt = db
                    .prepare("SELECT page.title, incl.title FROM " +
                            "includes INNER JOIN pages AS page ON includes.title == page.id " +
                            "INNER JOIN pages AS incl ON includes.include == incl.id;");
            while (stmt.step()) {
                String pageTitle = stmt.columnString(0);
                String include = stmt.columnString(1);
                updateMap(includeTree, pageTitle, include);
            }
            stmt.dispose();
            stmt = db
                    .prepare("SELECT page.title, redir.title FROM " +
                            "redirects INNER JOIN pages AS page ON redirects.title == page.id " +
                            "INNER JOIN pages AS redir ON redirects.redirect == redir.id;");
            while (stmt.step()) {
                String pageTitle = stmt.columnString(0);
                String redirect = stmt.columnString(1);
                updateMap(referenceTree, redirect, pageTitle);
            }
        } catch (SQLiteException e) {
            System.err.println("read of category tree failed (sqlite error: " + e.toString() + ")");
            throw new RuntimeException(e);
        } finally {
            if (stmt != null) {
                stmt.dispose();
            }
            if (db != null) {
                db.dispose();
            }
        }
    }
View Full Code Here

TOP

Related Classes of com.almworks.sqlite4java.SQLiteConnection

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.