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"); ?>