You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.0 KiB
68 lines
2.0 KiB
2 years ago
|
<?php
|
||
|
function save_computed_data_to_db(string $filename, bool $clear_before, string $userdata = '') {
|
||
|
try {
|
||
|
$pdo = new PDO('mysql:host=localhost;dbname=observer', 'observer', '6BjUdh7n');
|
||
|
|
||
|
$fd = fopen($filename, 'r');
|
||
|
|
||
|
$columns = fgetcsv($fd);
|
||
|
$placeholders = array_map(function($_) { return '?'; }, $columns);
|
||
|
$column_count = count($columns);
|
||
|
|
||
|
$sql_insert = 'insert into computeddata (' . implode(',', $columns) .
|
||
|
') values (' . implode(',', $placeholders) . ');';
|
||
|
|
||
|
$pdo->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);
|
||
|
}
|
||
|
}
|