public function tearDown() { // Remove test tables. $this->wpdb->query('SET FOREIGN_KEY_CHECKS = 0'); $this->wpdb->query('DROP TABLE IF EXISTS `test_types`'); $this->wpdb->query('DROP TABLE IF EXISTS `test_table`'); $this->wpdb->query('SET FOREIGN_KEY_CHECKS = 1'); $ct = new \WordPress\Tabulate\DB\ChangeTracker($this->wpdb); $ct->close_changeset(); // Uninstall if (!defined('WP_UNINSTALL_PLUGIN')) { define('WP_UNINSTALL_PLUGIN', 'tabulate/tabulate.php'); } require __DIR__ . '/../uninstall.php'; parent::tearDown(); }
/** * @testdox Rows can be imported from CSV. * @test */ public function basic_import() { $testtypes_table = $this->db->get_table('test_types'); $csv = '"ID","Title"' . "\r\n" . '"1","One"' . "\r\n" . '"2","Two"' . "\r\n"; $uploaded = $this->save_data_file($csv); $csv = new WordPress\Tabulate\CSV(null, $uploaded); $csv->load_data(); $column_map = array('title' => 'Title'); $csv->import_data($testtypes_table, $column_map); // Make sure 2 records were imported. $this->assertEquals(2, $testtypes_table->count_records()); $rec1 = $testtypes_table->get_record(1); $this->assertEquals('One', $rec1->title()); // And that 1 changeset was created, with 4 changes. $change_tracker = new \WordPress\Tabulate\DB\ChangeTracker($this->wpdb); $sql = "SELECT COUNT(id) FROM " . $change_tracker->changesets_name(); $this->assertEquals(1, $this->wpdb->get_var($sql)); $sql = "SELECT COUNT(id) FROM " . $change_tracker->changes_name(); $this->assertEquals(4, $this->wpdb->get_var($sql)); }
/** * Assume all data is now valid, and only FK values remain to be translated. * * @param DB\Table $table The table into which to import data. * @param array $column_map array of DB names to import names. * @return integer The number of rows imported. */ public function import_data($table, $column_map) { global $wpdb; $change_tracker = new \WordPress\Tabulate\DB\ChangeTracker($wpdb); $change_tracker->open_changeset('CSV import.', true); $count = 0; $headers = $this->remap($column_map); for ($row_num = 1; $row_num <= $this->row_count(); $row_num++) { $row = array(); foreach ($this->data[$row_num] as $col_num => $value) { if (!isset($headers[$col_num])) { continue; } $db_column_name = $headers[$col_num]; $column = $table->get_column($db_column_name); // Get actual foreign key value if ($column->is_foreign_key()) { if (empty($value)) { // Ignore empty-string FKs. continue; } else { $fk_rows = $this->get_fk_rows($column->get_referenced_table(), $value); $foreign_row = array_shift($fk_rows); $value = $foreign_row->get_primary_key(); } } // All other values are used as they are $row[$db_column_name] = $value; } $pk_name = $table->get_pk_column()->get_name(); $pk_value = isset($row[$pk_name]) ? $row[$pk_name] : null; $table->save_record($row, $pk_value); $count++; } $change_tracker->close_changeset(); return $count; }