getEntityColumnsName<T> method

Future<List<String>> getEntityColumnsName<T>()

Returns the list of column names of the entity table T as currently stored in SQLite. Useful to detect schema drift (columns added or removed on the Dart side).

Implementation

Future<List<String>> getEntityColumnsName<T>() async {
  List<String> columns = <String>[];
  await (await db).transaction((txn) async {
    final List<Map<String, Object?>> res = await txn.rawQuery(
      "SELECT sql FROM sqlite_master WHERE type='table' AND name='${T.toString()}'",
    );
    if (res.isEmpty) return;
    final String? createStatement = res.first['sql'] as String?;
    if (createStatement == null) return;
    final List<String> lines = createStatement.split('\n');
    if (lines.length <= 2) return;
    columns = lines
        .sublist(1, lines.length - 1)
        .map((String line) => line.trim().split(' ').first)
        .where((String token) => token != 'FOREIGN')
        .toList();
  });
  return columns;
}