checkTableIndexes function

List<String> checkTableIndexes(
  1. SqfEntityTableBase table
)

Check indexes of the table if exist

Implementation

List<String> checkTableIndexes(SqfEntityTableBase table) {
  final alterTableQuery = <String>[];
  final List<String?> addedIndexes = <String?>[];

  for (SqfEntityFieldType field in table.fields!) {
    if (addedIndexes.contains(field.fieldName)) {
      continue;
    }
    dynamic columns;
    bool? isUnique = false;
    String? indexName;
    isUnique = field.isUnique ?? false;
    if (field.isIndex ?? false) {
      if (field.isIndexGroup != null) {
        columns = table.fields!
            .where((f) => f.isIndexGroup == field.isIndexGroup)
            .map((e) => e.fieldName)
            .toList();
        indexName = 'IDX_${table.tableName}_Group_${field.isIndexGroup}';
      } else {
        columns = [
          '${field.fieldName}${field.collate != null ? ' COLLATE ${field.collate.toString().replaceAll('Collate.', '')}' : ''}'
        ];
        indexName = 'IDX_${table.tableName}_${field.fieldName}';
      }
    } else if (field is SqfEntityFieldRelationshipBase) {
      indexName = 'IDX${field.relationshipName! + field.fieldName!}';
      columns = [field.fieldName!];
    }

    if (indexName != null) {
      addedIndexes.addAll((columns as List<String?>));
      alterTableQuery.add(
          'CREATE UNIQUE INDEX IF NOT EXISTS $indexName ON ${table.tableName} (${columns.join(',')})');
    }
  }
  if (alterTableQuery.isNotEmpty) {
    print(
        'SQFENTITY: FOUND INDEX(ES) ON TABLE ${table.tableName}: (${addedIndexes.join(',')})');
  }
  return alterTableQuery;
}