checkTableColumns function

List<String> checkTableColumns(
  1. SqfEntityTableBase table,
  2. List<TableField> existingDBfields
)

Check table fields if exist

Implementation

List<String> checkTableColumns(
    SqfEntityTableBase table, List<TableField> existingDBfields) {
  final alterTableQuery = <String>[];
  bool recreateTable = false;
  if (table.useSoftDeleting! &&
      existingDBfields
          .where((x) => x.fieldName!.toLowerCase() == 'isdeleted')
          .isEmpty) {
    alterTableQuery.add(
        'ALTER TABLE ${table.tableName} ADD COLUMN isDeleted numeric NOT NULL DEFAULT 0');
  }
  for (var newField in table.fields!) {
    if (newField is SqfEntityFieldVirtualBase) {
      continue;
    }
    final eField = existingDBfields.where(
        (x) => x.fieldName!.toLowerCase() == newField.fieldName!.toLowerCase());
    if (eField.isNotEmpty) {
      // if (newField.dbType == DbType.bool) newField.dbType = DbType.numeric;
      if (!(newField.dbType == DbType.bool &&
              eField.toList()[0].fieldType == DbType.numeric) &&
          !(newField.dbType == DbType.datetimeUtc &&
              eField.toList()[0].fieldType == DbType.datetime) &&
          !(newField.dbType == DbType.time &&
              eField.toList()[0].fieldType == DbType.text) &&
          eField.toList()[0].fieldType != newField.dbType) {
        recreateTable = true;
        print(
            'SQFENTITIY COLUMN TYPE HAS CHANGED: The new type of the column [${newField.fieldName}(${newField.dbType.toString()})] applied to the existing column [${eField.toList()[0].fieldName}(${eField.toList()[0].fieldType.toString()})] on the table (${table.tableName})');
      }
    } else {
      alterTableQuery.add(
          'ALTER TABLE ${table.tableName} ADD COLUMN ${newField.toSqLiteFieldString()}');
      if (newField is SqfEntityFieldRelationshipBase) {
        alterTableQuery.add(
            'CREATE INDEX IF NOT EXISTS IDX${newField.relationshipName! + newField.fieldName!} ON ${table.tableName} (${newField.fieldName} ASC)');
      }
    }
  }
  if (recreateTable) {
    alterTableQuery
      ..add('PRAGMA foreign_keys=off')
      ..add('ALTER TABLE ${table.tableName} RENAME TO _${table.tableName}_old')
      ..add(table.createTableSQLnoForeignKeys)
      ..add(
          '''INSERT INTO ${table.tableName} (${table.createConstructureWithId.replaceAll('this.', '')})
  SELECT ${table.createConstructureWithId.replaceAll('this.', '')}
  FROM _${table.tableName}_old''')
      ..add('DROP TABLE _${table.tableName}_old')
      ..add('PRAGMA foreign_keys=on');
  }
  return alterTableQuery;
}