<commit_before>import 'dart:async';

import 'package:flutter/services.dart';
import 'dart:io';
import 'src/utils.dart';
import 'package:synchronized/synchronized.dart';

const String _paramPath = "path";
const String _paramVersion = "version";
const String _paramId = "id";
const String _paramSql = "sql";
const String _paramTable = "table";
const String _paramValues = "values";
const String _paramSqlArguments = "arguments";

const String _methodSetDebugModeOn = "debugMode";
const String _methodCloseDatabase = "closeDatabase";
const String _methodOpenDatabase = "openDatabase";
const String _methodExecute = "execute";
const String _methodInsert = "insert";
const String _methodUpdate = "update";
const String _methodQuery = "query";

class Sqflite {
  static const MethodChannel _channel =
      const MethodChannel('com.tekartik.sqflite');

  static Future<String> get platformVersion =>
      _channel.invokeMethod('getPlatformVersion');

  static Future setDebugModeOn() async {
    await Sqflite._channel.invokeMethod(_methodSetDebugModeOn);
  }

  static firstIntValue(List<Map> list) {
    if (list != null && list.length > 0) {
      return parseInt(list.first.values?.first);
    }
    return null;
  }
}

class Transaction {
  bool successfull;
}

class Database {
  String get path => _path;
  String _path;
  int _id;
  Database._(this._path, this._id);
  var lock = new SynchronizedLock();

  @override
  String toString() {
    return "$_id $_path";
  }

  Future close() async {
    await Sqflite._channel
        .invokeMethod(_methodCloseDatabase, <String, dynamic>{_paramId: _id});
  }

  /// for sql without return values
  Future execute(String sql, [List arguments]) async {
    return synchronized(lock, () async {
      await Sqflite._channel.invokeMethod(_methodExecute, <String, dynamic>{
        _paramId: _id,
        _paramSql: sql,
        _paramSqlArguments: arguments
      });
    });
  }

  /// for INSERT sql query
  /// returns the last inserted record id
  Future<int> insert(String sql, [List arguments]) async {
    return synchronized(lock, () async {
      return await Sqflite._channel.invokeMethod(
          _methodInsert, <String, dynamic>{
        _paramId: _id,
        _paramSql: sql,
        _paramSqlArguments: arguments
      });
    });
  }

  /// for UPDATE sql query
  /// return the number of changes made
  Future<int> update(String sql, [List arguments]) async {
    return synchronized(lock, () async {
      return await Sqflite._channel.invokeMethod(
          _methodUpdate, <String, dynamic>{
        _paramId: _id,
        _paramSql: sql,
        _paramSqlArguments: arguments
      });
    });
  }

  /// for DELETE sql query
  /// return the number of changes made
  Future<int> delete(String sql, [List arguments]) => update(sql, arguments);

  /// for SELECT sql query
  Future<List<Map<String, dynamic>>> query(String sql, [List arguments]) async {
    return synchronized(lock, () async {
      return await Sqflite._channel.invokeMethod(
          _methodQuery, <String, dynamic>{
        _paramId: _id,
        _paramSql: sql,
        _paramSqlArguments: arguments
      });
    });
  }

  Map<String, dynamic> _first(List<Map<String, dynamic>> list) {
    if (list != null && list.length > 0) {
      return list.first;
    }
    return null;
  }

  /// Warning as it does not introduce any context
  /// We'll need a transaction context in the other calls
  @deprecated
  Future<Transaction> beginTransaction({bool exclusive}) async {
    Transaction transaction = new Transaction();
    if (exclusive == true) {
      await execute("BEGIN EXCLUSIVE;");
    } else {
      await execute("BEGIN IMMEDIATE;");
    }
    return transaction;
  }

  @deprecated
  Future endTransaction(Transaction transaction) async {
    if (transaction.successfull == true) {
      await execute("COMMIT;");
    } else {
      await execute("ROLLBACK;");
    }
  }

  Future<Transaction> _beginTransaction({bool exclusive}) async {
    Transaction transaction = new Transaction();
    if (exclusive == true) {
      await execute("BEGIN EXCLUSIVE;");
    } else {
      await execute("BEGIN IMMEDIATE;");
    }
    return transaction;
  }

  Future _endTransaction(Transaction transaction) async {
    if (transaction.successfull == true) {
      await execute("COMMIT;");
    } else {
      await execute("ROLLBACK;");
    }
  }

  ///
  /// Simple transaction mechanism
  Future inTransaction(action(), {bool exclusive}) async {
    return synchronized(lock, () async {
      Transaction transaction = await _beginTransaction(exclusive: exclusive);
      try {
        await action();
        transaction.successfull = true;
      } finally {
        await _endTransaction(transaction);
      }
    });
  }

  Future<int> getVersion() async {
    return parseInt(_first(await query("PRAGMA user_version;"))?.values?.first);
  }

  Future setVersion(int version) async {
    await execute("PRAGMA user_version = $version;");
  }
}

class DatabaseException implements Exception {
  String msg;
  DatabaseException(this.msg);
}

typedef Future OnDatabaseVersionChangeFn(
    Database db, int oldVersion, int newVersion);<commit_msg>feat: add insert and make transaction reintrant<commit_after>import 'dart:async';

import 'package:flutter/services.dart';
import 'dart:io';
import 'package:sqflite/src/sql_builder.dart';
import 'src/utils.dart';
import 'package:synchronized/synchronized.dart';

const String _paramPath = "path";
const String _paramVersion = "version";
const String _paramId = "id";
const String _paramSql = "sql";
const String _paramTable = "table";
const String _paramValues = "values";
const String _paramSqlArguments = "arguments";

const String _methodSetDebugModeOn = "debugMode";
const String _methodCloseDatabase = "closeDatabase";
const String _methodOpenDatabase = "openDatabase";
const String _methodExecute = "execute";
const String _methodInsert = "insert";
const String _methodUpdate = "update";
const String _methodQuery = "query";
const String _methodGetPlatformVersion = "getPlatformVersion";

const String _channelName = 'com.tekartik.sqflite';

class Sqflite {
  static const MethodChannel _channel =
      const MethodChannel(_channelName);

  static Future<String> get platformVersion =>
      _channel.invokeMethod(_methodGetPlatformVersion);

  static Future setDebugModeOn([bool on = true]) async {
    await Sqflite._channel.invokeMethod(_methodSetDebugModeOn, on);
  }

  static firstIntValue(List<Map> list) {
    if (list != null && list.length > 0) {
      return parseInt(list.first.values?.first);
    }
    return null;
  }
}

class _Transaction {
  bool successfull;
}

///
/// Basic Database support
/// to send raw sql commands
///
class Database {
  String get path => _path;
  String _path;
  int _id;
  Database._(this._path, this._id);

  // only set during inTransaction
  _Transaction _currentTransaction;

  var _lock = new SynchronizedLock();


  SynchronizedLock get transactionLock => _lock;

  @override
  String toString() {
    return "$_id $_path";
  }

  Future close() async {
    await Sqflite._channel
        .invokeMethod(_methodCloseDatabase, <String, dynamic>{_paramId: _id});
  }

  /// for sql without return values
  Future execute(String sql, [List arguments]) async {
    return synchronized(_lock, () async {
      await Sqflite._channel.invokeMethod(_methodExecute, <String, dynamic>{
        _paramId: _id,
        _paramSql: sql,
        _paramSqlArguments: arguments
      });
    });
  }

  /// for INSERT sql query
  /// returns the last inserted record id
  Future<int> rawInsert(String sql, [List arguments]) async {
    return synchronized(_lock, () async {
      return await Sqflite._channel.invokeMethod(
          _methodInsert, <String, dynamic>{
        _paramId: _id,
        _paramSql: sql,
        _paramSqlArguments: arguments
      });
    });
  }

  Future<int> insert(String table, { String nullColumnHack,
    Map values, ConflictAlgorithm conflictAlgorithm}) {
    SqlBuilder builder = new SqlBuilder.insert(table, values: values, nullColumnHack: nullColumnHack, conflictAlgorithm: conflictAlgorithm);
    return rawInsert(builder.sql, builder.arguments);
  }

  Future<int> bulkInsert(String table, {String nullColumnHack,
    List<Map<String, dynamic>> items, ConflictAlgorithm conflictAlgorithm}) async {
    int count = 0;
    await inTransaction(() {
      items.forEach((values) async {
        count += await insert(table,
            nullColumnHack: nullColumnHack,
            values: values,
            conflictAlgorithm: conflictAlgorithm);
      });
    });

    return count;
  }

  /// for UPDATE sql query
  /// return the number of changes made
  Future<int> update(String sql, [List arguments]) async {
    return synchronized(_lock, () async {
      return await Sqflite._channel.invokeMethod(
          _methodUpdate, <String, dynamic>{
        _paramId: _id,
        _paramSql: sql,
        _paramSqlArguments: arguments
      });
    });
  }

  /// for DELETE sql query
  /// return the number of changes made
  Future<int> rawDelete(String sql, [List arguments]) => update(sql, arguments);

  /// for SELECT sql query
  Future<List<Map<String, dynamic>>> rawQuery(String sql, [List arguments]) async {
    return synchronized(_lock, () async {
      return await Sqflite._channel.invokeMethod(
          _methodQuery, <String, dynamic>{
        _paramId: _id,
        _paramSql: sql,
        _paramSqlArguments: arguments
      });
    });
  }

  Map<String, dynamic> _first(List<Map<String, dynamic>> list) {
    if (list != null && list.length > 0) {
      return list.first;
    }
    return null;
  }

  Future<_Transaction> _beginTransaction({bool exclusive}) async {
    _Transaction transaction = new _Transaction();
    if (exclusive == true) {
      await execute("BEGIN EXCLUSIVE;");
    } else {
      await execute("BEGIN IMMEDIATE;");
    }
    return transaction;
  }

  Future _endTransaction(_Transaction transaction) async {
    if (transaction.successfull == true) {
      await execute("COMMIT;");
    } else {
      await execute("ROLLBACK;");
    }
  }

  ///
  /// Simple transaction mechanism
  Future inTransaction(action(), {bool exclusive}) async {
    return synchronized(_lock, () async {
      _Transaction transaction = await _beginTransaction(exclusive: exclusive);
      _currentTransaction = transaction;
      try {
        await action();
        transaction.successfull = true;
      } finally {
        await _endTransaction(transaction);
        _currentTransaction = null;
      }
    });
  }

  Future<int> getVersion() async {
    return parseInt(_first(await rawQuery("PRAGMA user_version;"))?.values?.first);
  }

  Future setVersion(int version) async {
    await execute("PRAGMA user_version = $version;");
  }
}

class DatabaseException implements Exception {
  String msg;
  DatabaseException(this.msg);
}

typedef Future OnDatabaseVersionChangeFn(
    Database db, int oldVersion, int newVersion);
{'fraction_non_alphanumeric': 0.1111816450530516, 'fraction_numerical': 0.0004534324839031468, 'mean_word_length': 3.358893280632411, 'pattern_counts': {'":': 0, '<': 44, '<?xml version=': 0, '>': 55, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '5747987', 'n_tokens_mistral': 3148, 'n_tokens_neox': 3115, 'n_words': 866}