126 lines
3.3 KiB
PHP
126 lines
3.3 KiB
PHP
<?php
|
|
// import_csv_to_sqlite.php - Importador de base de datos corregido
|
|
define('CSV_FILE', __DIR__ . '/dbip-city-lite.csv');
|
|
define('SQLITE_DB', __DIR__ . '/ip_db.sqlite');
|
|
define('BATCH_SIZE', 50000);
|
|
|
|
// Verificar si el archivo CSV existe
|
|
if (!file_exists(CSV_FILE)) {
|
|
die("Archivo CSV no encontrado: " . CSV_FILE);
|
|
}
|
|
|
|
// Eliminar base de datos existente
|
|
if (file_exists(SQLITE_DB)) {
|
|
unlink(SQLITE_DB);
|
|
}
|
|
|
|
// Crear nueva base de datos
|
|
$db = new SQLite3(SQLITE_DB);
|
|
if (!$db) {
|
|
die("No se pudo crear la base de datos SQLite");
|
|
}
|
|
|
|
// Crear tabla con estructura mejorada
|
|
$db->exec('CREATE TABLE ip_ranges (
|
|
start INTEGER UNSIGNED,
|
|
end INTEGER UNSIGNED,
|
|
country TEXT,
|
|
region TEXT,
|
|
city TEXT,
|
|
lat REAL,
|
|
lon REAL
|
|
)');
|
|
|
|
// Crear índices
|
|
$db->exec('CREATE INDEX idx_start ON ip_ranges (start)');
|
|
$db->exec('CREATE INDEX idx_end ON ip_ranges (end)');
|
|
|
|
// Abrir archivo CSV
|
|
$file = fopen(CSV_FILE, 'r');
|
|
if (!$file) {
|
|
die("No se pudo abrir el archivo CSV");
|
|
}
|
|
|
|
// Preparar statement
|
|
$stmt = $db->prepare('INSERT INTO ip_ranges (start, end, country, region, city, lat, lon)
|
|
VALUES (:start, :end, :country, :region, :city, :lat, :lon)');
|
|
if (!$stmt) {
|
|
die("Error preparando statement: " . $db->lastErrorMsg());
|
|
}
|
|
|
|
echo "Iniciando importación...\n";
|
|
$startTime = microtime(true);
|
|
$count = 0;
|
|
$batchCount = 0;
|
|
$db->exec('BEGIN TRANSACTION');
|
|
|
|
while (($data = fgetcsv($file)) !== false) {
|
|
// Asegurarse de que hay suficientes columnas
|
|
if (count($data) < 8) {
|
|
continue;
|
|
}
|
|
|
|
// Obtener rangos de IP
|
|
$start = ip2long($data[0]);
|
|
$end = ip2long($data[1]);
|
|
|
|
if ($start === false || $end === false) {
|
|
continue;
|
|
}
|
|
|
|
// Convertir a enteros sin signo
|
|
$start = sprintf('%u', $start);
|
|
$end = sprintf('%u', $end);
|
|
|
|
// Obtener datos de ubicación
|
|
$country = $data[2];
|
|
$region = $data[3] ?? '';
|
|
$city = $data[4] ?? '';
|
|
|
|
// Latitud y Longitud - índices corregidos según estructura estándar
|
|
$lat = is_numeric($data[6]) ? (float)$data[6] : 0.0;
|
|
$lon = is_numeric($data[7]) ? (float)$data[7] : 0.0;
|
|
|
|
// Insertar datos
|
|
$stmt->bindValue(':start', $start, SQLITE3_INTEGER);
|
|
$stmt->bindValue(':end', $end, SQLITE3_INTEGER);
|
|
$stmt->bindValue(':country', $country, SQLITE3_TEXT);
|
|
$stmt->bindValue(':region', $region, SQLITE3_TEXT);
|
|
$stmt->bindValue(':city', $city, SQLITE3_TEXT);
|
|
$stmt->bindValue(':lat', $lat, SQLITE3_FLOAT);
|
|
$stmt->bindValue(':lon', $lon, SQLITE3_FLOAT);
|
|
|
|
if (!$stmt->execute()) {
|
|
echo "Error insertando fila: " . $db->lastErrorMsg() . "\n";
|
|
}
|
|
|
|
$count++;
|
|
$batchCount++;
|
|
|
|
// Commit periódico
|
|
if ($batchCount >= BATCH_SIZE) {
|
|
$db->exec('COMMIT');
|
|
$db->exec('BEGIN TRANSACTION');
|
|
echo "Importadas $count filas...\n";
|
|
$batchCount = 0;
|
|
}
|
|
}
|
|
|
|
// Finalizar transacción
|
|
$db->exec('COMMIT');
|
|
fclose($file);
|
|
|
|
// Optimizar base de datos
|
|
$db->exec('VACUUM');
|
|
$db->close();
|
|
|
|
$endTime = microtime(true);
|
|
$timeTaken = round($endTime - $startTime, 2);
|
|
echo "Importación completada!\n";
|
|
echo "Total filas: $count\n";
|
|
echo "Tiempo tomado: {$timeTaken} segundos\n";
|
|
|
|
// Crear archivo de verificación
|
|
file_put_contents(__DIR__ . '/import_success.txt', "Importación completada: $count registros");
|
|
?>
|