<commit_before>/*
 * Copyright 2016 <NAME>
 *
 * 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.pyamsoft.powermanager.app.sql;

import android.content.ContentValues;
import android.content.Context;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.pyamsoft.powermanager.model.sql.PowerTriggerEntry;
import com.squareup.sqlbrite.BriteDatabase;
import com.squareup.sqlbrite.SqlBrite;
import java.util.List;
import rx.Observable;
import rx.Scheduler;
import rx.schedulers.Schedulers;

public class PowerTriggerDB {
  private static volatile Delegate instance = null;
  @NonNull private final BriteDatabase briteDatabase;

  PowerTriggerDB(final @NonNull Context context, final @NonNull Scheduler dbScheduler) {
    final SqlBrite sqlBrite = SqlBrite.create();
    final PowerTriggerOpenHelper openHelper =
        new PowerTriggerOpenHelper(context.getApplicationContext());
    briteDatabase = sqlBrite.wrapDatabaseHelper(openHelper, dbScheduler);
  }

  public static void setDelegate(@Nullable Delegate delegate) {
    instance = delegate;
  }

  @CheckResult @NonNull public static Delegate with(@NonNull Context context) {
    return with(context, Schedulers.io());
  }

  @CheckResult @NonNull
  public static Delegate with(@NonNull Context context, @NonNull Scheduler scheduler) {
    if (instance == null) {
      synchronized (Delegate.class) {
        if (instance == null) {
          instance = new Delegate(context, scheduler);
        }
      }
    }

    return instance;
  }

  @CheckResult @NonNull BriteDatabase getDatabase() {
    return briteDatabase;
  }

  public static class Delegate {

    @NonNull final PowerTriggerDB database;

    public Delegate(@NonNull Context context) {
      this(context, Schedulers.io());
    }

    public Delegate(@NonNull Context context, @NonNull Scheduler scheduler) {
      this.database = new PowerTriggerDB(context.getApplicationContext(), scheduler);
    }

    @CheckResult @NonNull
    public Observable<Long> insert(final @NonNull ContentValues contentValues) {
      return Observable.defer(() -> Observable.just(
          database.getDatabase().insert(PowerTriggerEntry.TABLE_NAME, contentValues)));
    }

    @CheckResult @NonNull
    public Observable<Integer> update(final @NonNull ContentValues contentValues,
        final int percent) {
      return Observable.defer(() -> Observable.just(database.getDatabase()
          .update(PowerTriggerEntry.TABLE_NAME, contentValues,
              PowerTriggerEntry.UPDATE_WITH_PERCENT, String.valueOf(percent))));
    }

    @NonNull @CheckResult public Observable<List<PowerTriggerEntry>> queryAll() {
      return database.getDatabase()
          .createQuery(PowerTriggerEntry.TABLE_NAME, PowerTriggerEntry.ALL_ENTRIES)
          .mapToList(PowerTriggerEntry.FACTORY.all_entriesMapper()::map)
          .filter(padLockEntries -> padLockEntries != null);
    }

    @CheckResult @NonNull public Observable<Integer> deleteWithPercent(final int percent) {
      return Observable.defer(() -> Observable.just(database.getDatabase()
          .delete(PowerTriggerEntry.TABLE_NAME, PowerTriggerEntry.DELETE_WITH_PERCENT,
              Integer.toString(percent))));
    }

    @CheckResult @NonNull public Observable<Integer> deleteAll() {
      return Observable.defer(() -> Observable.just(database.getDatabase()
          .delete(PowerTriggerEntry.TABLE_NAME, PowerTriggerEntry.DELETE_ALL)));
    }
  }
}<commit_msg>Close db when done accessing<commit_after>/*
 * Copyright 2016 <NAME>
 *
 * 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.pyamsoft.powermanager.app.sql;

import android.content.ContentValues;
import android.content.Context;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.pyamsoft.powermanager.model.sql.PowerTriggerEntry;
import com.squareup.sqlbrite.BriteDatabase;
import com.squareup.sqlbrite.SqlBrite;
import java.util.List;
import rx.Observable;
import rx.Scheduler;
import rx.schedulers.Schedulers;
import timber.log.Timber;

public class PowerTriggerDB {
  @NonNull static final Object lock = new Object();
  private static volatile PowerTriggerDB instance = null;

  @NonNull private final SqlBrite sqlBrite;
  @NonNull private final PowerTriggerOpenHelper openHelper;
  @NonNull private final Scheduler dbScheduler;
  volatile BriteDatabase briteDatabase;
  volatile int openCount;

  PowerTriggerDB(final @NonNull Context context, final @NonNull Scheduler scheduler) {
    sqlBrite = SqlBrite.create();
    openHelper = new PowerTriggerOpenHelper(context.getApplicationContext());
    dbScheduler = scheduler;
    openCount = 0;
  }

  public static void setDB(@Nullable PowerTriggerDB db) {
    instance = db;
  }

  @CheckResult @NonNull public static PowerTriggerDB with(@NonNull Context context) {
    return with(context, Schedulers.io());
  }

  @CheckResult @NonNull
  public static PowerTriggerDB with(@NonNull Context context, @NonNull Scheduler scheduler) {
    if (instance == null) {
      synchronized (lock) {
        if (instance == null) {
          instance = new PowerTriggerDB(context, scheduler);
        }
      }
    }

    return instance;
  }

  synchronized void openDatabase() {
    if (briteDatabase == null) {
      Timber.d("Open new Database instance");
      briteDatabase = sqlBrite.wrapDatabaseHelper(openHelper, dbScheduler);
    }

    ++openCount;
    Timber.d("Increment open count to: %d", openCount);
  }

  synchronized void closeDatabase() {
    --openCount;
    Timber.d("Decrement open count to: %d", openCount);

    if (openCount == 0) {
      close();
    }
  }

  @CheckResult @NonNull public Observable<Long> insert(final @NonNull ContentValues contentValues) {
    openDatabase();
    return Observable.defer(() -> {
      final long result = briteDatabase.insert(PowerTriggerEntry.TABLE_NAME, contentValues);
      closeDatabase();
      return Observable.just(result);
    });
  }

  @CheckResult @NonNull
  public Observable<Integer> update(final @NonNull ContentValues contentValues, final int percent) {
    openDatabase();
    return Observable.defer(() -> {
      final int result = briteDatabase.update(PowerTriggerEntry.TABLE_NAME, contentValues,
          PowerTriggerEntry.UPDATE_WITH_PERCENT, String.valueOf(percent));
      closeDatabase();
      return Observable.just(result);
    });
  }

  @NonNull @CheckResult public Observable<List<PowerTriggerEntry>> queryAll() {
    openDatabase();

    return briteDatabase.createQuery(PowerTriggerEntry.TABLE_NAME, PowerTriggerEntry.ALL_ENTRIES)
        .mapToList(PowerTriggerEntry.FACTORY.all_entriesMapper()::map)
        .filter(padLockEntries -> padLockEntries != null)
        .map(powerTriggerEntries -> {
          closeDatabase();
          return powerTriggerEntries;
        });
  }

  @CheckResult @NonNull public Observable<Integer> deleteWithPercent(final int percent) {
    openDatabase();

    return Observable.defer(() -> {
      final int result =
          briteDatabase.delete(PowerTriggerEntry.TABLE_NAME, PowerTriggerEntry.DELETE_WITH_PERCENT,
              Integer.toString(percent));
      closeDatabase();
      return Observable.just(result);
    });
  }

  @CheckResult @NonNull public Observable<Integer> deleteAll() {
    openDatabase();

    return Observable.defer(() -> {
      final int result =
          briteDatabase.delete(PowerTriggerEntry.TABLE_NAME, PowerTriggerEntry.DELETE_ALL);
      closeDatabase();
      return Observable.just(result);
    });
  }

  public void close() {
    Timber.d("Close and recycle database connection");
    if (briteDatabase != null) {
      briteDatabase.close();
      briteDatabase = null;
    }
  }
}
{'fraction_non_alphanumeric': 0.09549610565526583, 'fraction_numerical': 0.002031832035218422, 'mean_word_length': 3.8654585392641407, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 28, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2404932', 'n_tokens_mistral': 2388, 'n_tokens_neox': 2378, 'n_words': 639}