beginTransaction(); $statement = $pdo->prepare($sql_insert); $nan_to_null = function ($x) { if ((gettype($x) === 'double' && is_nan($x)) || $x === 'NaN') { return null; } return $x; }; $insert_data = function ($line) use ($column_count, $statement, $nan_to_null) { if (count($line) == $column_count) { if (!$statement->execute(array_map($nan_to_null, $line))) { HttpResponse::internal_server_error()->set_and_exit(); } } else { throw new Exception('Incomplete or overfull line in CSV: ' . $column_count . ' expected, ' . count($line) . ' given (distance ' . $line['distance'] . ')'); } }; if ($clear_before) { $setup_id_index = array_search('setup_id', array_map('strtolower', $columns)); $line = fgetcsv($fd); $setup_id = $line[$setup_id_index]; $pdo->exec('delete from computeddata where setup_id = ' . $setup_id . ';'); $insert_data($line); if ($userdata !== '') { $pdo->prepare('replace into setup (setup_id, userdata) values (?, ?);')->execute(array($setup_id, $userdata)); } } while (($line = fgetcsv($fd)) !== false) { $insert_data($line); } $pdo->commit(); } catch (Exception $e) { // Prevent incomplete dataset insertion if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); } // As all we care about is aborting the transaction, we leave taking // care of the exception up to the caller throw $e; } finally { if (isset($fd)) { fclose($fd); } unset($statement); unset($pdo); } }