toSql method

Future<void> toSql(
  1. String tableName,
  2. String connectionString, {
  3. String ifExists = 'fail',
  4. bool index = false,
  5. String? indexLabel,
  6. int? chunkSize,
  7. Map<String, String>? dtype,
})

Writes DataFrame to SQL database table (pandas-like to_sql)

Implementation

Future<void> toSql(
  String tableName,
  String connectionString, {
  String ifExists = 'fail',
  bool index = false,
  String? indexLabel,
  int? chunkSize,
  Map<String, String>? dtype,
}) async {
  if (!['fail', 'replace', 'append'].contains(ifExists)) {
    throw ArgumentError('ifExists must be one of: fail, replace, append');
  }

  final connection = DatabaseReader.createConnection(connectionString);
  try {
    // Check if table exists
    final tableExists = await _tableExists(connection, tableName);

    if (tableExists) {
      if (ifExists == 'fail') {
        throw DatabaseQueryError('Table $tableName already exists');
      } else if (ifExists == 'replace') {
        await connection.execute('DROP TABLE IF EXISTS $tableName');
        await _createTable(connection, tableName, dtype);
      }
    } else {
      await _createTable(connection, tableName, dtype);
    }

    // Insert data
    await _insertData(connection, tableName, index, indexLabel, chunkSize);
  } finally {
    await connection.close();
  }
}