insert Batch Files

@param string|string[] $fileNames
@param string[]        $columns
@param string          $format ['TabSeparated','TabSeparatedWithNames','CSV','CSVWithNames']
@return Statement[]
@throws Exception\TransportException
183213
public function insertBatchFiles(string $tableName, $fileNames, array $columns = [], string $format = 'CSV')
    {
        if (is_string($fileNames)) {
            $fileNames = [$fileNames];
        }
        if ($this->getCountPendingQueue() > 0) {
            throw new QueryException('Queue must be empty, before insertBatch, need executeAsync');
        }

        if (! in_array($format, self::SUPPORTED_FORMATS, true)) {
            throw new QueryException('Format not support in insertBatchFiles');
        }

        $result = [];

        foreach ($fileNames as $fileName) {
            if (! is_file($fileName) || ! is_readable($fileName)) {
                throw  new QueryException('Cant read file: ' . $fileName . ' ' . (is_file($fileName) ? '' : ' is not file'));
            }

            if (empty($columns)) {
                $sql = 'INSERT INTO ' . $tableName . ' FORMAT ' . $format;
            } else {
                $sql = 'INSERT INTO ' . $tableName . ' ( ' . implode(',', $columns) . ' ) FORMAT ' . $format;
            }
            $result[$fileName] = $this->transport()->writeAsyncCSV($sql, $fileName);
        }

        // exec
        $this->executeAsync();

        // fetch resutl
        foreach ($fileNames as $fileName) {
            if (! $result[$fileName]->isError()) {
                continue;
            }

            $result[$fileName]->error();
        }

        return $result;
    }
659667
public function insertMany($table, array $columns, array $values)
    {
        $columns = $this->quote($columns);

        // Validate the length
        foreach ($values as $data) {
            $dataCount = count($data);
            $columnsCount = count($columns);

            if ($dataCount !== $columnsCount) {
                throw new LogicException(sprintf('Count mismatch. One collection contains %s keys instead of expected %s', $dataCount, $columnsCount));
            }
        }

        // Generate initial fragment
        $sql = sprintf('INSERT INTO %s (%s) VALUES ', $table, implode(', ', $columns));

        // Generate the rest
        foreach ($values as $data) {
            if (is_array($data)) {
                $sql .= sprintf("(%s), ", implode(', ', $data));
            } else {
                throw new RuntimeException(sprintf('3-rd argument should contain a collection of arrays, one of them is %s', gettype($data)));
            }
        }

        // Tweak the ending fragment
        $sql = substr($sql, 0, -2);
        $sql .= ';';

        // Done there
        $this->append($sql);
        return $this;
    }
900883
public function insert($columns) {
        // Check if array is associative
        if (Arr::is_assoc($columns)) {
            // Get array keys
            $arr_keys = array_keys($columns);

            // Get array values
            $arr_values = array_values($columns);

            $values = '';
            $fields = '';
            $insert  = [];

            // Build up the insert query
            $this->q->apd('INSERT INTO ' . $this->table_name . '(');

            for ($ii = 0; $ii < count($arr_keys); $ii++) {
                if ($ii != count($arr_keys) -1) {
                    $fields .= $arr_keys[$ii] . ', ';

                    if (!$this->is_SQL_function($arr_values[$ii])) {
                        $values .= ':' . $arr_keys[$ii] . ', ';
                        $insert[':' . $arr_keys[$ii]] = $arr_values[$ii];
                    } else {
                        $values .= $arr_values[$ii] . ', ';
                    }
                } else {
                    $fields .= $arr_keys[$ii] . ') VALUES (';

                    if (!$this->is_SQL_function($arr_values[$ii])) {
                        $values .= ':' . $arr_keys[$ii] . ')';
                        $insert[':' . $arr_keys[$ii]] = $arr_values[$ii];
                    } else {
                        $values .= $arr_values[$ii] . ')';
                    }
                }
            }

            // Finalize query
            $this->q->apd($fields . $values);

            try {
                $query = $this->db->prepare($this->q->get());
                $query->execute($insert);
                $this->clear();

                // Set last inserted id
                $this->lastInsertId = $this->db->lastInsertId();

                return true;
            } catch (\PDOException $e) {
                $this->setError('d', $e->getMessage());
                return false;
            }
        } else {
            echo 'Wrong array format';
            return false;
        }
    }
679903
public synchronized void insert (Connection conn, T[] objects)
        throws SQLException
    {
        StringBuilder sql = new StringBuilder(
            "insert into " + name + " (" + listOfFields + ") values (?");
        for (int i = 1; i < nColumns; i++) {
            sql.append(",?");
        }
        sql.append(")");
        PreparedStatement insertStmt = conn.prepareStatement(sql.toString());
        for (int i = 0; i < objects.length; i++) {
            bindUpdateVariables(insertStmt, objects[i], null);
            insertStmt.addBatch();
        }
        insertStmt.executeBatch();
        insertStmt.close();
    }
271622
public function addFiles(array $files)
    {
        $added_files = 0;
        try {
            foreach ($files as $localName => $filename) {
                if (!is_null($filename)) {
                    $this->sevenZip->addEntry($filename);
                    $this->sevenZip->renameEntry($filename, $localName);
                    $added_files++;
                }
            }
        } catch (Exception $e) {
            throw new Exception('Could not modify archive: '.$e->getMessage(), $e->getCode(), $e);
        }
        return $added_files;
    }
232200
public function loadAll(array $columnNames = null)
    {
        if (is_array($columnNames)) {
            foreach ($columnNames as $columnName) {
                $this->columnsToLoad[$columnName] = $this->structure->getColumn($columnName);
            }
        } else {
            $this->columnsToLoad = $this->structure->getColumns();
        }

        return $this;
    }
848231
public function run_insert($sql, array $params=null, $seqName=null, array $driverOptions=array()) {
		
		#$this->sth = $this->dbh->prepare($sql, $driverOptions);
		#$this->sth->execute($params);
		$numRows = $this->run_query($sql, $params, $driverOptions);
		
		if($numRows > 0 && is_object($this->dbh)) {
			$retval = $this->dbh->lastInsertId($seqName);
		}
		else {
			throw new \Exception(__METHOD__ .": insert failed");
		}
		
		#$retval = $this->dbh->lastInsertId($seqName);
		return($retval);
	}
962553
public function insert($fields) {
        // Create temporary variables for 
        // tokenized parameter
        $_tmp_fields = [];
        $_tmp_values = [];
        
        if (is_array($fields)) {
            foreach ($fields as $key => $value) {
                array_push($_tmp_fields, $key);
                
                if (is_string($value)) {
                    array_push($_tmp_values, '\'' . addslashes($value) . '\'');
                } else {
                    array_push($_tmp_values, $value);
                }
            }
            
            $this->_fields = implode($_tmp_fields, ', ');
            $this->_values = implode($_tmp_values, ', ');
        } else {
            return false;
        }
        
        $sql_query = 'INSERT INTO ' . $this->_table . 
                     '(' . $this->_fields . ')' .
                     ' VALUES(' . $this->_values . ')';
                     
        // Set the query
        $this->_sql_query = $sql_query;
        
        // Execute query
        return $this;
    }
1178720
public function insert($columns = null, $data = null) {
        $sql = $this->grammar()->compileInsert($this, $columns, $data);
        return $this->command()
            ->insert($sql, $this->getBindings());
    }
196126
public function importFromCSV($FileName, array $Options = [])
    {
        $Delimiter = isset($Options["Delimiter"]) ? $Options["Delimiter"] : ",";
        $GotHeader = isset($Options["GotHeader"]) ? $Options["GotHeader"] : false;
        $SkipColumns = isset($Options["SkipColumns"]) ? $Options["SkipColumns"] : [-1];
        $DefaultSerieName = isset($Options["DefaultSerieName"]) ? $Options["DefaultSerieName"] : "Serie";

        $Handle = @fopen($FileName, "r");
        if ($Handle) {
            $HeaderParsed = false;
            $SerieNames = [];
            while (!feof($Handle)) {
                $Buffer = fgets($Handle, 4096);
                $Buffer = str_replace(chr(10), "", $Buffer);
                $Buffer = str_replace(chr(13), "", $Buffer);
                $Values = preg_split("/" . $Delimiter . "/", $Buffer);

                if ($Buffer != "") {
                    if ($GotHeader && !$HeaderParsed) {
                        foreach ($Values as $Key => $Name) {
                            if (!in_array($Key, $SkipColumns)) {
                                $SerieNames[$Key] = $Name;
                            }
                        }
                        $HeaderParsed = true;
                    } else {
                        if (!count($SerieNames)) {
                            foreach ($Values as $Key => $Name) {
                                if (!in_array($Key, $SkipColumns)) {
                                    $SerieNames[$Key] = $DefaultSerieName . $Key;
                                }
                            }
                        }
                        foreach ($Values as $Key => $Value) {
                            if (!in_array($Key, $SkipColumns)) {
                                $this->addPoints($Value, $SerieNames[$Key]);
                            }
                        }
                    }
                }
            }
            fclose($Handle);
        }
    }
63589
public function setColumnNames(array $columnNames)
    {
        $this->columnNames = array();

        foreach ($columnNames as $columnName) {
            $this->addColumnName($columnName);
        }
    }
49399
public function insert(...$field_values)
    {
        if ($this->is_done) {
            throw new RuntimeException('This batch insert is already done');
        }

        if (count($field_values) == $this->fields_num) {
            $this->rows[] = $this->connection->prepare($this->row_prepare_pattern, ...$field_values);

            if (count($this->rows) == $this->rows_per_batch) {
                $this->flush();
            }
        } else {
            throw new BadMethodCallException('Number of arguments does not match number of fields');
        }
    }
354760
protected function processExportData($columns, $results, $options)
    {
        /*
         * Validate
         */
        if (!$results) {
            throw new ApplicationException(Lang::get('backend::lang.import_export.empty_error'));
        }

        /*
         * Parse options
         */
        $defaultOptions = [
            'firstRowTitles' => true,
            'useOutput' => false,
            'fileName' => 'export.csv',
            'delimiter' => null,
            'enclosure' => null,
            'escape' => null
        ];

        $options = array_merge($defaultOptions, $options);
        $columns = $this->exportExtendColumns($columns);

        /*
         * Prepare CSV
         */
        $csv = CsvWriter::createFromFileObject(new SplTempFileObject);
        
        $csv->setOutputBOM(CsvWriter::BOM_UTF8);

        if ($options['delimiter'] !== null) {
            $csv->setDelimiter($options['delimiter']);
        }

        if ($options['enclosure'] !== null) {
            $csv->setEnclosure($options['enclosure']);
        }

        if ($options['escape'] !== null) {
            $csv->setEscape($options['escape']);
        }

        /*
         * Add headers
         */
        if ($options['firstRowTitles']) {
            $headers = $this->getColumnHeaders($columns);
            $csv->insertOne($headers);
        }

        /*
         * Add records
         */
        foreach ($results as $result) {
            $data = $this->matchDataToColumns($result, $columns);
            $csv->insertOne($data);
        }

        /*
         * Output
         */
        if ($options['useOutput']) {
            $csv->output($options['fileName']);
        }

        /*
         * Save for download
         */
        $csvName = uniqid('oc');
        $csvPath = temp_path().'/'.$csvName;
        $output = $csv->__toString();

        File::put($csvPath, $output);

        return $csvName;
    }
787804
public function setColumns(array $columns)
    {
        foreach ($columns as $id => $params) {
            if (!is_string($id) || strlen($id) < 1)
                throw new \Exception("Column ID should be a non-empty string");
            if (!isset($params['title']))
                throw new \Exception("No 'title' param for ID $id");
            if (!isset($params['type']))
                throw new \Exception("No 'type' param for ID $id");
            if (!in_array($params['type'], self::getAvailableTypes()))
                throw new \Exception("Unknown type '" . $params['type'] . "' for ID $id");
            if (!isset($params['filters']))
                throw new \Exception("No 'filters' param for ID $id");
            if (!isset($params['sortable']))
                throw new \Exception("No 'sortable' param for ID $id");
            if (!isset($params['visible']))
                throw new \Exception("No 'visible' param for ID $id");

            foreach ($params['filters'] as $filter) {
                if (!in_array($filter, self::getAvailableFilters()))
                    throw new \Exception("Unknown filter: $filter");
            }
        }

        $this->columns = $columns;
        return $this;
    }
67799
public function batchInsert(array $rows): ResultInterface
    {
        $this->insert = $this->getTableName();
        foreach ($rows as $row) {
            ksort($row);
            if (!isset($this->insertValues['columns'])) {
                $this->insertValues['columns'] = array_keys($row);
            }
            $this->insertValues['values'][] = array_values($row);
        }

        return $this->execute();
    }
830394
public function bulk_insert( array $records ) {
		// Build cols.
		$cols = [];
		foreach ( $records as $record ) {
			foreach ( $record as $key => $value ) {
				$cols[] = $key;
			}
			break;
		}
		$current_time = current_time( 'mysql', $this->use_gmt() );
		foreach ( [ 'created', 'updated' ] as $key ) {
			if ( !in_array( $key, $cols ) ) {
				$cols[] = $key;
				$records = array_map( function( $values ) use ( $key ) {
					$values[ $key ] = current_time( 'mysql', true );
					return $values;
				}, $records );
			}
		}
		$value_expression = implode( ', ', array_map( function( $values ) {
			$escaped_values = [];
			foreach ( $values as $key => $value ) {
				$escaped_values[] = $this->db->prepare( $this->get_place_holder( $key ), $value );
			}
			return sprintf( '(%s)', implode( ', ', $escaped_values ) );
		}, $records ) );
		$cols = implode( ', ', array_map( function( $col ) {
			return "`{$col}`";
		}, $cols ) );
		$query = <<<SQL
			INSERT INTO {$this->table} ( {$cols} ) VALUES {$value_expression}
SQL;
		return $this->db->query( $query );
	}
909385
private function importTable(string $tableName, array $columns, array $items)
    {
        if (empty($tableName) || empty($columns) || empty($items)) {
            throw new \RuntimeException(
                'Invalid import data',
                1535487373
            );
        }

        $this->connection->truncate($tableName);

        $columnNames = array_keys($columns);
        $columnTypes = array_values($columns);
        foreach ($items as $item) {
            $this->connection->insert(
                $tableName,
                array_combine($columnNames, $item),
                $columns
            );
        }
    }