tableExists static method

Future<bool> tableExists(
  1. String tableName
)

Check if a table exists.

Implementation

static Future<bool> tableExists(String tableName) async {
  await _ensureConnected();

  try {
    final String sql;
    final Map<String, dynamic> params = {'table': tableName};

    if (_driver == DBDriver.postgres) {
      sql = '''
      SELECT COUNT(*) > 0 AS exists
      FROM information_schema.tables
      WHERE table_schema = 'public'
      AND table_name = :table
    ''';
    } else {
      sql = '''
      SELECT COUNT(*) > 0 AS exists
      FROM information_schema.tables
      WHERE table_schema = DATABASE()
      AND table_name = ?
    ''';
    }

    final result = await query(
      sql,
      positionalParams: _driver == DBDriver.mysql ? [tableName] : null,
      namedParams: _driver == DBDriver.postgres ? params : null,
    );

    final exists = result.first['exists'];
    if (exists is bool) return exists;
    if (exists is int) return exists > 0;
    if (exists is BigInt) return exists > BigInt.zero;
    if (exists is String) {
      return exists == '1' || exists.toLowerCase() == 'true';
    }
    return false;
  } catch (e) {
    print('⚠️ tableExists() failed: $e');
    return false;
  }
}