Adds a table to the dataset

The table will be given the passed name. $csvFile should be a path to
a valid csv file (based on the arguments passed to the constructor.)

@param string $tableName
@param string $csvFile
493807
public function addTable($tableName, $csvFile)
    {
        if (!is_file($csvFile)) {
            throw new \InvalidArgumentException("Could not find csv file: {$csvFile}");
        }

        if (!is_readable($csvFile)) {
            throw new \InvalidArgumentException("Could not read csv file: {$csvFile}");
        }

        $fh      = fopen($csvFile, 'rb');
        fseek($fh, 2);  // after BOM

        // TODO chunk
        $tmpFp = fopen('php://temp', 'w+b');
        fwrite($tmpFp, mb_convert_encoding(stream_get_contents($fh), 'UTF-8', 'UTF-16LE'));
        rewind($tmpFp);

        $columns = $this->getCsvRow($tmpFp);

        if ($columns === FALSE)
        {
            throw new \InvalidArgumentException("Could not determine the headers from the given file {$csvFile}");
        }

        $metaData = new \PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($tableName, $columns);
        $table    = new \PHPUnit_Extensions_Database_DataSet_DefaultTable($metaData);

        while (($row = $this->getCsvRow($tmpFp)) !== FALSE)
        {
            $table->addRow(array_combine($columns, $row));
        }

        $this->tables[$tableName] = $table;
    }
1326013
public static function arrayToCsvFile($filename, $data)
    {
        $fp = fopen($filename, 'w');

        foreach ($data as $fields) {
            fputcsv($fp, $fields);
        }

        fclose($fp);
    }
575804
public function buildFromCsv(CsvLine $csv_line_base = null)
	{
		$this->csv_line_base = $csv_line_base ? $csv_line_base : new CsvLine;
		$this->csv_parser->setConfig($this->config_file_parse);
		$this->csv_line_base->setConfig($this->config_model);

		$this->updateCsvHeader();

		// Csv loop
		while ( ($csv_line_array = $this->csv_parser->parseCsvFile()) != false )
		{
			if( count($csv_line_array) && (! ( (count($csv_line_array) == 1) && is_null($csv_line_array[0]) ) ) )
			{
				// create csv_line
				$csv_line = clone $this->csv_line_base;
				$csv_line->forceSetAttributes($csv_line_array);
				$this->appendLine($csv_line);
			}
		}
	}
1019314
private void addTable(TableDef table)
    {
        table.setOwner(this);
        _tableDefs.put(table.getName(), table);
    }
1118426
public function updateHeaders(CsvFile $csv_file, array $columns, $table_name)
	{
		$this->csv_file = $csv_file ? $csv_file : $this->csv_file;

		foreach($this->csv_file as $csv_line)
		{
			$this->updateHeader($csv_line, $columns, $table_name);
		}
	}
466184
public function addColumn($table, $name, $data)
    {

        $q = "ALTER TABLE {$table} ADD {$name}";
        $v = $data;

        if (isset($v['type'])) {
            $q .= " {$v['type']}";
            if (isset($v['length'])) {
                $q .= "({$v['length']})";
            } else {
                if ($v['type'] != 'int' && $v['type'] != 'datetime') {
                    die ("Please set length for table: {$name} - column: {$name}");
                }
            }

            if (isset($v['unsigned']) && $v['unsigned'] == true) {
                $q .= " UNSIGNED";
            }

            if (!isset($v['null']) || $v['null'] == false) {
                $q .= " NOT NULL";
            }

            if (isset($v['default'])) {
                if (is_string($v['default'])) {
                    $v['default'] = "'{$v['default']}'";
                }

                $q .= " DEFAULT {$v['default']}";
            }

            if (isset($v['ai']) && $v['ai'] == true) {
                $q .= " AUTO_INCREMENT";
            }

            if ((isset($v['unique']) && $v['unique'] == true) && (isset($v['primary']) && $v['primary'] == true)) {
                die ("Unique or Primary?");
            }

            if (isset($v['unique']) && $v['unique'] == true) {
                $q .= " UNIQUE";
            }

            if (isset($v['primary']) && $v['primary'] == true) {
                $q .= " PRIMARY KEY";
            }

            if (isset($v['after'])) {
                $q .= " AFTER {$v['after']}";
            }

        } else {
            die ("Please set type of column ");
        }

        return $this->executeQuery($q);
    }
576816
public function import($sqlFile, $charsetMode = null)
    {
        if (!file_exists($sqlFile)) {
            throw new Exception("File '$sqlFile' was not found.");
        }

        $credentialsFile = $this->databaseDefaultsFileGenerator->generate();
        $charsetMode = $charsetMode ? $charsetMode : $this->getCharsetMode();
        $command = 'mysql --defaults-file=' . $credentialsFile;
        $command .= ' --default-character-set=' . $charsetMode;
        $command .= ' ' .escapeshellarg($this->getDbName());
        $command .= ' < ' . escapeshellarg($sqlFile);
        $this->executeCommand($command);
        unlink($credentialsFile);
    }
507958
private void addOrUpdateTable(File file) {
        try {
            String insertStmnt = FileUtils.readFileToString(file);
            DataSource ds = processSql(insertStmnt);
            DataSource existingDs = db().getDataSource(ds.getName());
            if (existingDs == null) {//We never saw this table before.
                db().addDataSource(ds);
                return;
            }
            // If startTime/endTime/templatePath changed then we should update the table.
            if (existingDs.getStartTime() != ds.getStartTime() || 
                    existingDs.getEndTime() != ds.getEndTime() ||
                    !existingDs.getTemplatePath().equals(ds.getTemplatePath())) {
                // We have to reuse the existing entity bean(else update will fail).
                existingDs.updateFrom(ds);
                db().updateDataSource(existingDs);
            }                 
        } catch (IOException ex) {
            log.error("Exception while loading druid sql file {} : {}", file, ex);
        }
    }
925339
@Override
    public synchronized void addFile(File pFile, String pRelativePath) throws TTException, IOException {
        // LOGGER.info("Adding file " + pFile.getName());

        int readingAmount = 0;

        @SuppressWarnings("resource")
        FileChannel ch = new RandomAccessFile(pFile, "rw").getChannel();
        FileLock lock = null;

        while (lock == null) {
            try {
                lock = ch.tryLock();
            } catch (OverlappingFileLockException e) {
                // File is already locked in this thread or virtual machine
            }
        }

        // LOGGER.info("Filesize: " + ch.size());

        ByteBuffer buffer = ByteBuffer.allocate(FileData.FILENODESIZE);

        // LOGGER.debug("Successfully initialized byte source.");
        readingAmount += ch.read(buffer);

        // LOGGER.debug("First readAmount: " + readingAmount);
        if (readingAmount <= 0) {
            MetaKey key = new MetaKey(pRelativePath);
            MetaValue value = new MetaValue(FilelistenerReadTrx.emptyFileKey);
            getBucketTransaction().getMetaBucket().put(key, value);

            return;
        }

        long newKey = getBucketTransaction().incrementDataKey();

        if (fileExists(pRelativePath)) {
            removeFile(pRelativePath);
        }

        // Setting a new header file data
        MetaKey key = new MetaKey(pRelativePath);
        MetaValue value = new MetaValue(newKey);

        // And adding it to the meta map
        // LOGGER.debug("Metakeypair setup");
        getBucketTransaction().getMetaBucket().put(key, value);

        // Creating and setting the headerdata.
        FileData headerData = new FileData(newKey, buffer.array(), false);

        getBucketTransaction().setData(headerData);

        // Creating and setting following datas based on the file size.
        FileData data;

        int currentReadingAmount = 0;
        // LOGGER.info("Iterating file content");
        while ((currentReadingAmount = ch.read(buffer = ByteBuffer.allocate(FileData.FILENODESIZE))) > 0) {
            // LOGGER.debug("Curr. read amount: " + currentReadingAmount);
            byte[] slice = Arrays.copyOf(buffer.array(), currentReadingAmount);

            long dataKey = getBucketTransaction().incrementDataKey();
            data = new FileData(dataKey, slice, false);

            getBucketTransaction().setData(data);

            readingAmount += currentReadingAmount;
        }

        ByteArrayDataOutput size = ByteStreams.newDataOutput();
        size.writeInt(readingAmount);

        data = new FileData(getBucketTransaction().incrementDataKey(), size.toByteArray(), true);

        getBucketTransaction().setData(data);

        Preconditions.checkArgument(getBucketTransaction().getData(newKey) != null);
        lock.release();
        ch.close();
    }
1185302
public function addTable($headers, $data, $options = [], $html = true)
    {
        $options = array_merge($this->defaultOptions['table'], $options);
        if ($html) {
            $this->addHTMLTable($headers, $data, $options);
        } else {
            $this->addNormalTable($headers, $data, $options);
        }
    }
272684
protected function createTable(Table $table): void
	{
		$table->addPrimaryKey('id')
			->int()
			->setAutoIncrement();
		$table->addForeignKey('pageId', PagesMapper::class);
		$table->addColumn('name')
			->text();
		$table->addColumn('quantity')
			->tinyint(2)
			->setDefault(null);
		$table->addColumn('position')
			->int(3);
		$table->addColumn('visible')
			->bool()
			->setDefault(1);
	}
605877
public function cuSelectOneDataSet($tableName, $fieldName, $fieldValue)
    {

        $where         = " $fieldName='$fieldValue' ";
        $dataSetsArray = $this->cuSelectAsArray($tableName, $where);

        $dataSetArray = null;
        if (array_key_exists(0, $dataSetsArray)) {
            $dataSetArray = $dataSetsArray[0];
        }

        return $dataSetArray;
    }
34702
def read_csv_to_html_list(csvFile):
    
    txt = ''
    with open(csvFile) as csv_file:
        for row in csv.reader(csv_file, delimiter=','):
            txt += '<div id="table_row">'
            for col in row:
                txt += " "
                try:
                    txt += col
                except Exception:
                    txt += 'Error'
                txt += " "
            txt += "</div>\n"
    return txt
818218
public void csv(String file) throws IOException {
        CsvWriteOptions options = CsvWriteOptions.builder(file).build();
        new CsvWriter().write(table, options);
    }
1194569
public function matchCsv(TableNode $expected, $options = []) {
    $actual = CSVTable::fromString($this->getMink()->getSession()->getDriver()->getContent());
    $actualRows = $actual->getRows();
    $expectedCount = count($expected->getRows());
    $actualCount = count($actualRows);
    if ($actualCount > $expectedCount) {
      $actualRows = array_slice($actualRows, 0, $expectedCount);
      $actual = new TableNode($actualRows);
    }
    $assert = new AssertTable();
    $assert->isComparable(
      $expected,
      $actual,
      $options + [
        "comparators" => $this->getComparators($expected)
      ]
    );
  }
1041997
public static boolean addColumn (
        Connection conn, String table, String cname, String cdef, String afterCname)
        throws SQLException
    {
        if (tableContainsColumn(conn, table, cname)) {
//             Log.info("Database table '" + table + "' already has column '" + cname + "'.");
            return false;
        }

        String update = "ALTER TABLE " + table + " ADD COLUMN " + cname + " " + cdef;
        if (afterCname != null) {
            update += " AFTER " + afterCname;
        }
        PreparedStatement stmt = null;
        try {
            stmt = conn.prepareStatement(update);
            stmt.executeUpdate();
        } finally {
            close(stmt);
        }
        log.info("Database column '" + cname + "' added to table '" + table + "'.");
        return true;
    }
696934
public function addFilesToData(&$data, $table = "tt_content")
    {
        if ($data["_LOCALIZED_UID"]) {
            $uid = $data["_LOCALIZED_UID"];
        } else {
            $uid = $data["uid"];
        }

        // using is_numeric in favor to is_int
        // due to some rare cases where uids are provided as strings
        if (!is_numeric($uid)) {
            return;
        }
        $fieldHelper = GeneralUtility::makeInstance('MASK\\Mask\\Helper\\FieldHelper');
        if (!$this->objectManager) {
            $this->objectManager = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
        }

        $storage = $this->storageRepository->load();
        /* @var $fileRepository \TYPO3\CMS\Core\Resource\FileRepository */
        $fileRepository = $this->objectManager->get("TYPO3\CMS\Core\Resource\FileRepository");
        $contentFields = array("media", "image", "assets");
        if ($storage[$table]["tca"]) {
            foreach ($storage[$table]["tca"] as $fieldKey => $field) {
                $contentFields[] = $fieldKey;
            }
        }
        if ($contentFields) {
            foreach ($contentFields as $fieldKey) {
                if ($fieldHelper->getFormType($fieldKey, "", $table) == "File") {
                    $data[$fieldKey] = $fileRepository->findByRelation($table, $fieldKey, $uid);
                }
            }
        }
    }