/*
 * Copyright 2017-present Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

package com.facebook.buck.rules;

import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.Optional;

public class SQLiteBuildInfoStore implements BuildInfoStore {
  private final Connection connection;
  private final PreparedStatement selectStmt;
  private final PreparedStatement updateStmt;
  private final PreparedStatement deleteStmt;

  public SQLiteBuildInfoStore(ProjectFilesystem filesystem) throws IOException {
    String dbPath =
        filesystem
            .getRootPath()
            .resolve(filesystem.getBuckPaths().getScratchDir().resolve("metadata.db"))
            .toString();
    try {
      Class.forName("org.sqlite.JDBC");
      connection = DriverManager.getConnection("jdbc:sqlite:" + dbPath);
      connection.createStatement().executeUpdate("PRAGMA SYNCHRONOUS = OFF");
      connection.createStatement().executeUpdate("PRAGMA JOURNAL_MODE = OFF");
      connection
          .createStatement()
          .executeUpdate(
              "CREATE TABLE IF NOT EXISTS metadata "
                  + "(target TEXT, key TEXT, value TEXT, "
                  + "PRIMARY KEY (target, key)) "
                  + "WITHOUT ROWID");
      selectStmt =
          connection.prepareStatement("SELECT value FROM metadata WHERE target = ? AND key = ?");
      updateStmt =
          connection.prepareStatement(
              "INSERT OR REPLACE INTO metadata (target, key, value) VALUES (?, ?, ?)");
      deleteStmt = connection.prepareStatement("DELETE FROM metadata WHERE target = ?");
    } catch (ClassNotFoundException | SQLException e) {
      throw new IOException(e);
    }
  }

  @Override
  public void close() {
    try {
      connection.close();
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public synchronized Optional<String> readMetadata(BuildTarget buildTarget, String key) {
    try {
      selectStmt.setString(1, buildTarget.getFullyQualifiedName());
      selectStmt.setString(2, key);
      ResultSet rs = selectStmt.executeQuery();
      if (!rs.next()) {
        return Optional.empty();
      }
      String value = rs.getString(1);
      return Optional.of(value);
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public synchronized void updateMetadata(BuildTarget buildTarget, Map<String, String> metadata)
      throws IOException {
    try {
      for (Map.Entry<String, String> e : metadata.entrySet()) {
        updateStmt.setString(1, buildTarget.getFullyQualifiedName());
        updateStmt.setString(2, e.getKey());
        updateStmt.setString(3, e.getValue());
        updateStmt.addBatch();
      }
      updateStmt.executeBatch();
    } catch (SQLException e) {
      throw new IOException(e);
    }
  }

  @Override
  public synchronized void deleteMetadata(BuildTarget buildTarget) throws IOException {
    try {
      deleteStmt.setString(1, buildTarget.getFullyQualifiedName());
      deleteStmt.executeUpdate();
    } catch (SQLException e) {
      throw new IOException(e);
    }
  }
}

@@ -952,16 +952,47 @@
 ptional;
+%0Aimport org.sqlite.BusyHandler;
 %0A%0Apublic
@@ -1757,19 +1757,19 @@
 _MODE = 
-OFF
+WAL
 %22);%0A    
@@ -2295,24 +2295,24 @@
 ?, ?, ?)%22);%0A
-
       delete
@@ -2384,24 +2384,451 @@
 rget = ?%22);%0A
+      BusyHandler busyHandler =%0A          new BusyHandler() %7B%0A            @Override%0A            protected int callback(int retries) throws SQLException %7B%0A              try %7B%0A                Thread.sleep(retries);%0A              %7D catch (InterruptedException e) %7B%0A                throw new SQLException(e);%0A              %7D%0A              return 1;%0A            %7D%0A          %7D;%0A      BusyHandler.setHandler(connection, busyHandler);%0A
     %7D catch 

Add a busy handler, use WAL journaling