insertSingle method

Future<int> insertSingle({
  1. @required required dynamic objectToInsert,
})

This method is used to insert a single object into the database.

It takes an object as a parameter and inserts it into the database. If the insert operation is successful, the method returns the id of the inserted record. If an error occurs during the insert operation, the method logs the error and returns -1.

The method first gets the database instance. Then, it calls the toJson method on the object to convert it to a map, and inserts the map into the database. The table name for the insert operation is obtained by calling the getTableName method with the object.

Parameters: objectToInsert (dynamic): The object to insert into the database.

Returns: Future

Implementation

Future<int> insertSingle({@required required dynamic objectToInsert}) async {
  var db = await getDatabase();
  try {
    var queryResult = await select(
        sqlBuilder: SqlBuilder()
            .querySelect()
            .queryFrom(table: getTableName(objectToInsert)),
        model: objectToInsert,
        print: false);
    if (queryResult.contains(objectToInsert)) {
      PrintHandler.warningLogger.e(
          '⚠️sqflite_simple_dao_backend⚠️: Record already exists. "-1" returned.');
      return -1;
    }
    var result = await db!
        .insert(getTableName(objectToInsert), objectToInsert.toJson());
    return result;
  } catch (e) {
    PrintHandler.warningLogger.e(
        '⛔sqflite_simple_dao_backend⛔: Error inserting the record: $e. "-1" returned.');
    return -1;
  }
}