public function sqlLine($sql) { if (!$this->putline) { return parent::sqlLine($sql); } if ($sql == '\\.') { $this->putline = false; pg_put_line($this->connection, $sql . "\n"); pg_end_copy($this->connection); pg_close($this->connection); } else { pg_put_line($this->connection, $sql . "\n"); } return true; }
function main($id, $mode) { global $cache, $db, $user, $template, $table_prefix, $request; global $phpbb_root_path, $phpbb_container, $phpbb_log; $this->db_tools = $phpbb_container->get('dbal.tools'); $user->add_lang('acp/database'); $this->tpl_name = 'acp_database'; $this->page_title = 'ACP_DATABASE'; $action = $request->variable('action', ''); $submit = isset($_POST['submit']) ? true : false; $template->assign_vars(array('MODE' => $mode)); switch ($mode) { case 'backup': $this->page_title = 'ACP_BACKUP'; switch ($action) { case 'download': $type = $request->variable('type', ''); $table = array_intersect($this->db_tools->sql_list_tables(), $request->variable('table', array(''))); $format = $request->variable('method', ''); $where = $request->variable('where', ''); if (!sizeof($table)) { trigger_error($user->lang['TABLE_SELECT_ERROR'] . adm_back_link($this->u_action), E_USER_WARNING); } $store = $download = $structure = $schema_data = false; if ($where == 'store_and_download' || $where == 'store') { $store = true; } if ($where == 'store_and_download' || $where == 'download') { $download = true; } if ($type == 'full' || $type == 'structure') { $structure = true; } if ($type == 'full' || $type == 'data') { $schema_data = true; } @set_time_limit(1200); @set_time_limit(0); $time = time(); $filename = 'backup_' . $time . '_' . unique_id(); $extractor = $phpbb_container->get('dbal.extractor'); $extractor->init_extractor($format, $filename, $time, $download, $store); $extractor->write_start($table_prefix); foreach ($table as $table_name) { // Get the table structure if ($structure) { $extractor->write_table($table_name); } else { // We might wanna empty out all that junk :D switch ($db->get_sql_layer()) { case 'sqlite': case 'sqlite3': $extractor->flush('DELETE FROM ' . $table_name . ";\n"); break; case 'mssql': case 'mssql_odbc': case 'mssqlnative': $extractor->flush('TRUNCATE TABLE ' . $table_name . "GO\n"); break; case 'oracle': $extractor->flush('TRUNCATE TABLE ' . $table_name . "/\n"); break; default: $extractor->flush('TRUNCATE TABLE ' . $table_name . ";\n"); break; } } // Data if ($schema_data) { $extractor->write_data($table_name); } } $extractor->write_end(); $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_DB_BACKUP'); if ($download == true) { exit; } trigger_error($user->lang['BACKUP_SUCCESS'] . adm_back_link($this->u_action)); break; default: $tables = $this->db_tools->sql_list_tables(); asort($tables); foreach ($tables as $table_name) { if (strlen($table_prefix) === 0 || stripos($table_name, $table_prefix) === 0) { $template->assign_block_vars('tables', array('TABLE' => $table_name)); } } unset($tables); $template->assign_vars(array('U_ACTION' => $this->u_action . '&action=download')); $available_methods = array('gzip' => 'zlib', 'bzip2' => 'bz2'); foreach ($available_methods as $type => $module) { if (!@extension_loaded($module)) { continue; } $template->assign_block_vars('methods', array('TYPE' => $type)); } $template->assign_block_vars('methods', array('TYPE' => 'text')); break; } break; case 'restore': $this->page_title = 'ACP_RESTORE'; switch ($action) { case 'submit': $delete = $request->variable('delete', ''); $file = $request->variable('file', ''); $download = $request->variable('download', ''); if (!preg_match('#^backup_\\d{10,}_[a-z\\d]{16}\\.(sql(?:\\.(?:gz|bz2))?)$#', $file, $matches)) { trigger_error($user->lang['BACKUP_INVALID'] . adm_back_link($this->u_action), E_USER_WARNING); } $file_name = $phpbb_root_path . 'store/' . $matches[0]; if (!file_exists($file_name) || !is_readable($file_name)) { trigger_error($user->lang['BACKUP_INVALID'] . adm_back_link($this->u_action), E_USER_WARNING); } if ($delete) { if (confirm_box(true)) { unlink($file_name); $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_DB_DELETE'); trigger_error($user->lang['BACKUP_DELETE'] . adm_back_link($this->u_action)); } else { confirm_box(false, $user->lang['DELETE_SELECTED_BACKUP'], build_hidden_fields(array('delete' => $delete, 'file' => $file))); } } else { if ($download || confirm_box(true)) { if ($download) { $name = $matches[0]; switch ($matches[1]) { case 'sql': $mimetype = 'text/x-sql'; break; case 'sql.bz2': $mimetype = 'application/x-bzip2'; break; case 'sql.gz': $mimetype = 'application/x-gzip'; break; } header('Cache-Control: private, no-cache'); header("Content-Type: {$mimetype}; name=\"{$name}\""); header("Content-disposition: attachment; filename={$name}"); @set_time_limit(0); $fp = @fopen($file_name, 'rb'); if ($fp !== false) { while (!feof($fp)) { echo fread($fp, 8192); } fclose($fp); } flush(); exit; } switch ($matches[1]) { case 'sql': $fp = fopen($file_name, 'rb'); $read = 'fread'; $seek = 'fseek'; $eof = 'feof'; $close = 'fclose'; $fgetd = 'fgetd'; break; case 'sql.bz2': $fp = bzopen($file_name, 'r'); $read = 'bzread'; $seek = ''; $eof = 'feof'; $close = 'bzclose'; $fgetd = 'fgetd_seekless'; break; case 'sql.gz': $fp = gzopen($file_name, 'rb'); $read = 'gzread'; $seek = 'gzseek'; $eof = 'gzeof'; $close = 'gzclose'; $fgetd = 'fgetd'; break; } switch ($db->get_sql_layer()) { case 'mysql': case 'mysql4': case 'mysqli': case 'sqlite': case 'sqlite3': while (($sql = $fgetd($fp, ";\n", $read, $seek, $eof)) !== false) { $db->sql_query($sql); } break; case 'postgres': $delim = ";\n"; while (($sql = $fgetd($fp, $delim, $read, $seek, $eof)) !== false) { $query = trim($sql); if (substr($query, 0, 13) == 'CREATE DOMAIN') { list(, , $domain) = explode(' ', $query); $sql = "SELECT domain_name\n\t\t\t\t\t\t\t\t\t\t\t\tFROM information_schema.domains\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE domain_name = '{$domain}';"; $result = $db->sql_query($sql); if (!$db->sql_fetchrow($result)) { $db->sql_query($query); } $db->sql_freeresult($result); } else { $db->sql_query($query); } if (substr($query, 0, 4) == 'COPY') { while (($sub = $fgetd($fp, "\n", $read, $seek, $eof)) !== '\\.') { if ($sub === false) { trigger_error($user->lang['RESTORE_FAILURE'] . adm_back_link($this->u_action), E_USER_WARNING); } pg_put_line($db->get_db_connect_id(), $sub . "\n"); } pg_put_line($db->get_db_connect_id(), "\\.\n"); pg_end_copy($db->get_db_connect_id()); } } break; case 'oracle': while (($sql = $fgetd($fp, "/\n", $read, $seek, $eof)) !== false) { $db->sql_query($sql); } break; case 'mssql': case 'mssql_odbc': case 'mssqlnative': while (($sql = $fgetd($fp, "GO\n", $read, $seek, $eof)) !== false) { $db->sql_query($sql); } break; } $close($fp); // Purge the cache due to updated data $cache->purge(); $phpbb_log->add('admin', $user->data['user_id'], $user->ip, 'LOG_DB_RESTORE'); trigger_error($user->lang['RESTORE_SUCCESS'] . adm_back_link($this->u_action)); break; } else { if (!$download) { confirm_box(false, $user->lang['RESTORE_SELECTED_BACKUP'], build_hidden_fields(array('file' => $file))); } } } default: $methods = array('sql'); $available_methods = array('sql.gz' => 'zlib', 'sql.bz2' => 'bz2'); foreach ($available_methods as $type => $module) { if (!@extension_loaded($module)) { continue; } $methods[] = $type; } $dir = $phpbb_root_path . 'store/'; $dh = @opendir($dir); $backup_files = array(); if ($dh) { while (($file = readdir($dh)) !== false) { if (preg_match('#^backup_(\\d{10,})_[a-z\\d]{16}\\.(sql(?:\\.(?:gz|bz2))?)$#', $file, $matches)) { if (in_array($matches[2], $methods)) { $backup_files[(int) $matches[1]] = $file; } } } closedir($dh); } if (!empty($backup_files)) { krsort($backup_files); foreach ($backup_files as $name => $file) { $template->assign_block_vars('files', array('FILE' => $file, 'NAME' => $user->format_date($name, 'd-m-Y H:i:s', true), 'SUPPORTED' => true)); } } $template->assign_vars(array('U_ACTION' => $this->u_action . '&action=submit')); break; } break; } }
/** * Performs a batch insert using plain INSERTs * * @see OA_Dal::batchInsert() * * @param string $tableName The unquoted table name * @param array $aFields The array of unquoted field names * @param array $aValues The array of data to be inserted * @param bool $replace Should the primary key be replaced when already present? * @return int The number of rows inserted or PEAR_Error on failure */ private function _batchInsertPgSQL($qTableName, $fieldList, $aValues, $replace, $primaryKey) { $oDbh = OA_DB::singleton(); $delim = "\t"; $eol = "\n"; $null = '\\N'; // Disable error handler RV::disableErrorHandling(); // we start by manually deleting conflicting unique rows foreach ($aValues as $aRow) { // because Postgresql doesn't have the REPLACE keyword, // we manually delete the rows with the primary key first if ($replace) { $where = ''; foreach ($primaryKey as $fieldName) { $where .= $fieldName . ' = \'' . $aRow[$fieldName] . '\' AND '; } $where = substr($where, 0, strlen($where) - 5); $oDbh->query('DELETE FROM ' . $qTableName . ' WHERE ' . $where); } } $pg = $oDbh->getConnection(); $result = $oDbh->exec("\n COPY\n {$qTableName} {$fieldList}\n FROM\n STDIN\n "); if (PEAR::isError($result)) { return MAX::raiseError('Error issuing the COPY query for the batch INSERTs.', PEAR_ERROR_RETURN); } foreach ($aValues as $aRow) { // Stringify row $row = ''; foreach ($aRow as $value) { if (!isset($value) || $value === false) { $row .= $null . $delim; } else { $row .= $value . $delim; } } // Replace delim with eol $row[strlen($row) - 1] = $eol; // Send line $ret = pg_put_line($pg, $row); if (!$ret) { return MAX::raiseError('Error COPY-ing data: ' . pg_errormessage($pg), PEAR_ERROR_RETURN); } } $result = pg_put_line($pg, '\\.' . $eol) && pg_end_copy($pg); $result = $result ? count($aValues) : new PEAR_Error('Error at the end of the COPY: ' . pg_errormessage($pg)); // Enable error handler again RV::enableErrorHandling(); return $result; }
public function putLine($data) { assert('is_string($data)'); return pg_put_line($this->_pg, $data); }
function main($id, $mode) { global $db, $user, $auth, $template, $table_prefix; global $config, $phpbb_root_path, $phpbb_admin_path, $phpEx; $user->add_lang('acp/database'); $this->tpl_name = 'acp_database'; $this->page_title = 'ACP_DATABASE'; $action = request_var('action', ''); $submit = (isset($_POST['submit'])) ? true : false; $template->assign_vars(array( 'MODE' => $mode )); switch ($mode) { case 'backup': $this->page_title = 'ACP_BACKUP'; switch ($action) { case 'download': $type = request_var('type', ''); $table = request_var('table', array('')); $format = request_var('method', ''); $where = request_var('where', ''); if (!sizeof($table)) { trigger_error($user->lang['TABLE_SELECT_ERROR'] . adm_back_link($this->u_action), E_USER_WARNING); } $store = $download = $structure = $schema_data = false; if ($where == 'store_and_download' || $where == 'store') { $store = true; } if ($where == 'store_and_download' || $where == 'download') { $download = true; } if ($type == 'full' || $type == 'structure') { $structure = true; } if ($type == 'full' || $type == 'data') { $schema_data = true; } @set_time_limit(1200); $time = time(); $filename = 'backup_' . $time . '_' . unique_id(); switch ($db->sql_layer) { case 'mysqli': case 'mysql4': case 'mysql': $extractor = new mysql_extractor($download, $store, $format, $filename, $time); break; case 'sqlite': $extractor = new sqlite_extractor($download, $store, $format, $filename, $time); break; case 'postgres': $extractor = new postgres_extractor($download, $store, $format, $filename, $time); break; case 'oracle': $extractor = new oracle_extractor($download, $store, $format, $filename, $time); break; case 'mssql': case 'mssql_odbc': $extractor = new mssql_extractor($download, $store, $format, $filename, $time); break; case 'firebird': $extractor = new firebird_extractor($download, $store, $format, $filename, $time); break; } $extractor->write_start($table_prefix); foreach ($table as $table_name) { // Get the table structure if ($structure) { $extractor->write_table($table_name); } else { // We might wanna empty out all that junk :D switch ($db->sql_layer) { case 'sqlite': case 'firebird': $extractor->flush('DELETE FROM ' . $table_name . ";\n"); break; case 'mssql': case 'mssql_odbc': $extractor->flush('TRUNCATE TABLE ' . $table_name . "GO\n"); break; case 'oracle': $extractor->flush('TRUNCATE TABLE ' . $table_name . "\\\n"); break; default: $extractor->flush('TRUNCATE TABLE ' . $table_name . ";\n"); break; } } // Data if ($schema_data) { $extractor->write_data($table_name); } } $extractor->write_end(); if ($download == true) { exit; } add_log('admin', 'LOG_DB_BACKUP'); trigger_error($user->lang['BACKUP_SUCCESS'] . adm_back_link($this->u_action)); break; default: include($phpbb_root_path . 'includes/functions_install.' . $phpEx); $tables = get_tables($db); foreach ($tables as $table_name) { if (strlen($table_prefix) === 0 || stripos($table_name, $table_prefix) === 0) { $template->assign_block_vars('tables', array( 'TABLE' => $table_name )); } } unset($tables); $template->assign_vars(array( 'U_ACTION' => $this->u_action . '&action=download' )); $available_methods = array('gzip' => 'zlib', 'bzip2' => 'bz2'); foreach ($available_methods as $type => $module) { if (!@extension_loaded($module)) { continue; } $template->assign_block_vars('methods', array( 'TYPE' => $type )); } $template->assign_block_vars('methods', array( 'TYPE' => 'text' )); break; } break; case 'restore': $this->page_title = 'ACP_RESTORE'; switch ($action) { case 'submit': $delete = request_var('delete', ''); $file = request_var('file', ''); if (!preg_match('#^backup_\d{10,}_[a-z\d]{16}\.(sql(?:\.(?:gz|bz2))?)$#', $file, $matches)) { trigger_error($user->lang['BACKUP_INVALID'] . adm_back_link($this->u_action), E_USER_WARNING); } $file_name = $phpbb_root_path . 'store/' . $matches[0]; if (!file_exists($file_name) || !is_readable($file_name)) { trigger_error($user->lang['BACKUP_INVALID'] . adm_back_link($this->u_action), E_USER_WARNING); } if ($delete) { if (confirm_box(true)) { unlink($file_name); add_log('admin', 'LOG_DB_DELETE'); trigger_error($user->lang['BACKUP_DELETE'] . adm_back_link($this->u_action)); } else { confirm_box(false, $user->lang['DELETE_SELECTED_BACKUP'], build_hidden_fields(array('delete' => $delete, 'file' => $file))); } } else { $download = request_var('download', ''); if ($download) { $name = $matches[0]; switch ($matches[1]) { case 'sql': $mimetype = 'text/x-sql'; break; case 'sql.bz2': $mimetype = 'application/x-bzip2'; break; case 'sql.gz': $mimetype = 'application/x-gzip'; break; } header('Pragma: no-cache'); header("Content-Type: $mimetype; name=\"$name\""); header("Content-disposition: attachment; filename=$name"); @set_time_limit(0); $fp = @fopen($file_name, 'rb'); if ($fp !== false) { while (!feof($fp)) { echo fread($fp, 8192); } fclose($fp); } flush(); exit; } switch ($matches[1]) { case 'sql': $fp = fopen($file_name, 'rb'); $read = 'fread'; $seek = 'fseek'; $eof = 'feof'; $close = 'fclose'; $fgetd = 'fgetd'; break; case 'sql.bz2': $fp = bzopen($file_name, 'r'); $read = 'bzread'; $seek = ''; $eof = 'feof'; $close = 'bzclose'; $fgetd = 'fgetd_seekless'; break; case 'sql.gz': $fp = gzopen($file_name, 'rb'); $read = 'gzread'; $seek = 'gzseek'; $eof = 'gzeof'; $close = 'gzclose'; $fgetd = 'fgetd'; break; } switch ($db->sql_layer) { case 'mysql': case 'mysql4': case 'mysqli': case 'sqlite': while (($sql = $fgetd($fp, ";\n", $read, $seek, $eof)) !== false) { $db->sql_query($sql); } break; case 'firebird': $delim = ";\n"; while (($sql = $fgetd($fp, $delim, $read, $seek, $eof)) !== false) { $query = trim($sql); if (substr($query, 0, 8) === 'SET TERM') { $delim = $query[9] . "\n"; continue; } $db->sql_query($query); } break; case 'postgres': while (($sql = $fgetd($fp, $delim, $read, $seek, $eof)) !== false) { $query = trim($sql); $db->sql_query($query); if (substr($query, 0, 4) == 'COPY') { while (($sub = $fgetd($fp, "\n", $read, $seek, $eof)) !== '\.') { if ($sub === false) { trigger_error($user->lang['RESTORE_FAILURE'] . adm_back_link($this->u_action), E_USER_WARNING); } pg_put_line($db->db_connect_id, $sub . "\n"); } pg_put_line($db->db_connect_id, "\\.\n"); pg_end_copy($db->db_connect_id); } } break; case 'oracle': while (($sql = $fgetd($fp, "/\n", $read, $seek, $eof)) !== false) { $db->sql_query($sql); } break; case 'mssql': case 'mssql_odbc': while (($sql = $fgetd($fp, "GO\n", $read, $seek, $eof)) !== false) { $db->sql_query($sql); } break; } $close($fp); add_log('admin', 'LOG_DB_RESTORE'); trigger_error($user->lang['RESTORE_SUCCESS'] . adm_back_link($this->u_action)); break; } default: $methods = array('sql'); $available_methods = array('sql.gz' => 'zlib', 'sql.bz2' => 'bz2'); foreach ($available_methods as $type => $module) { if (!@extension_loaded($module)) { continue; } $methods[] = $type; } $dir = $phpbb_root_path . 'store/'; $dh = @opendir($dir); if ($dh) { while (($file = readdir($dh)) !== false) { if (preg_match('#^backup_(\d{10,})_[a-z\d]{16}\.(sql(?:\.(?:gz|bz2))?)$#', $file, $matches)) { $supported = in_array($matches[2], $methods); if ($supported == 'true') { $template->assign_block_vars('files', array( 'FILE' => $file, 'NAME' => gmdate("d-m-Y H:i:s", $matches[1]), 'SUPPORTED' => $supported )); } } } closedir($dh); } $template->assign_vars(array( 'U_ACTION' => $this->u_action . '&action=submit' )); break; } break; } }
/** * Executes an SQL script as a series of SQL statements. Returns * the result of the final step. This is a very complicated lexer * based on the REL7_4_STABLE src/bin/psql/mainloop.c lexer in * the PostgreSQL source code. * XXX: It does not handle multibyte languages properly. * @param $name Entry in $_FILES to use * @param $callback (optional) Callback function to call with each query, its result and line number. * @return True for general success, false on any failure. */ function executeScript($name, $callback = null) { global $data; // This whole function isn't very encapsulated, but hey... $conn = $data->conn->_connectionID; if (!is_uploaded_file($_FILES[$name]['tmp_name'])) { return false; } $fd = fopen($_FILES[$name]['tmp_name'], 'r'); if (!$fd) { return false; } // Build up each SQL statement, they can be multiline $query_buf = null; $query_start = 0; $in_quote = 0; $in_xcomment = 0; $bslash_count = 0; $dol_quote = null; $paren_level = 0; $len = 0; $i = 0; $prevlen = 0; $thislen = 0; $lineno = 0; // Loop over each line in the file while (!feof($fd)) { $line = fgets($fd); $lineno++; // Nothing left on line? Then ignore... if (trim($line) == '') { continue; } $len = strlen($line); $query_start = 0; /* * Parse line, looking for command separators. * * The current character is at line[i], the prior character at line[i * - prevlen], the next character at line[i + thislen]. */ $prevlen = 0; $thislen = $len > 0 ? 1 : 0; for ($i = 0; $i < $len; $this->advance_1($i, $prevlen, $thislen)) { /* was the previous character a backslash? */ if ($i > 0 && substr($line, $i - $prevlen, 1) == '\\') { $bslash_count++; } else { $bslash_count = 0; } /* * It is important to place the in_* test routines before the * in_* detection routines. i.e. we have to test if we are in * a quote before testing for comments. */ /* in quote? */ if ($in_quote !== 0) { /* * end of quote if matching non-backslashed character. * backslashes don't count for double quotes, though. */ if (substr($line, $i, 1) == $in_quote && ($bslash_count % 2 == 0 || $in_quote == '"')) { $in_quote = 0; } } else { if ($dol_quote) { if (strncmp(substr($line, $i), $dol_quote, strlen($dol_quote)) == 0) { $this->advance_1($i, $prevlen, $thislen); while (substr($line, $i, 1) != '$') { $this->advance_1($i, $prevlen, $thislen); } $dol_quote = null; } } else { if (substr($line, $i, 2) == '/*') { $in_xcomment++; if ($in_xcomment == 1) { $this->advance_1($i, $prevlen, $thislen); } } else { if ($in_xcomment) { if (substr($line, $i, 2) == '*/' && !--$in_xcomment) { $this->advance_1($i, $prevlen, $thislen); } } else { if (substr($line, $i, 1) == '\'' || substr($line, $i, 1) == '"') { $in_quote = substr($line, $i, 1); } else { if (!$dol_quote && $this->valid_dolquote(substr($line, $i))) { $dol_end = strpos(substr($line, $i + 1), '$'); $dol_quote = substr($line, $i, $dol_end + 1); $this->advance_1($i, $prevlen, $thislen); while (substr($line, $i, 1) != '$') { $this->advance_1($i, $prevlen, $thislen); } } else { if (substr($line, $i, 2) == '--') { $line = substr($line, 0, $i); /* remove comment */ break; } else { if (substr($line, $i, 1) == '(') { $paren_level++; } else { if (substr($line, $i, 1) == ')' && $paren_level > 0) { $paren_level--; } else { if (substr($line, $i, 1) == ';' && !$bslash_count && !$paren_level) { $subline = substr(substr($line, 0, $i), $query_start); /* is there anything else on the line? */ if (strspn($subline, " \t\n\r") != strlen($subline)) { /* * insert a cosmetic newline, if this is not the first * line in the buffer */ if (strlen($query_buf) > 0) { $query_buf .= "\n"; } /* append the line to the query buffer */ $query_buf .= $subline; $query_buf .= ';'; // Execute the query. PHP cannot execute // empty queries, unlike libpq $res = @pg_query($conn, $query_buf); // Call the callback function for display if ($callback !== null) { $callback($query_buf, $res, $lineno); } // Check for COPY request if (pg_result_status($res) == 4) { // 4 == PGSQL_COPY_FROM while (!feof($fd)) { $copy = fgets($fd, 32768); $lineno++; pg_put_line($conn, $copy); if ($copy == "\\.\n" || $copy == "\\.\r\n") { pg_end_copy($conn); break; } } } } $query_buf = null; $query_start = $i + $thislen; } else { if (preg_match('/^[_[:alpha:]]$/', substr($line, $i, 1))) { $sub = substr($line, $i, $thislen); while (preg_match('/^[\\$_A-Za-z0-9]$/', $sub)) { /* keep going while we still have identifier chars */ $this->advance_1($i, $prevlen, $thislen); $sub = substr($line, $i, $thislen); } // Since we're now over the next character to be examined, it is necessary // to move back one space. $i -= $prevlen; } } } } } } } } } } } } // end for /* Put the rest of the line in the query buffer. */ $subline = substr($line, $query_start); if ($in_quote || $dol_quote || strspn($subline, " \t\n\r") != strlen($subline)) { if (strlen($query_buf) > 0) { $query_buf .= "\n"; } $query_buf .= $subline; } $line = null; } // end while /* * Process query at the end of file without a semicolon, so long as * it's non-empty. */ if (strlen($query_buf) > 0 && strspn($query_buf, " \t\n\r") != strlen($query_buf)) { // Execute the query $res = @pg_query($conn, $query_buf); // Call the callback function for display if ($callback !== null) { $callback($query_buf, $res, $lineno); } // Check for COPY request if (pg_result_status($res) == 4) { // 4 == PGSQL_COPY_FROM while (!feof($fd)) { $copy = fgets($fd, 32768); $lineno++; pg_put_line($conn, $copy); if ($copy == "\\.\n" || $copy == "\\.\r\n") { pg_end_copy($conn); break; } } } } fclose($fd); return true; }
public function bulkInsert($table, array $params, $extra = null) { # Ensure we have a connection to run this query on $this->connect(); if ($output = $this->output) { $this->output = false; echo "BULK INSERT INTO " . $table . " (" . count($params) . " rows)...\n"; } switch ($this->mode) { case "mysql": case "redshift": case "odbc": $fields = ""; $first = reset($params); foreach ($first as $key => $val) { if ($fields) { $fields .= ","; } $fields .= $this->quoteField($key); } $newParams = []; $noParams = false; if ($this->mode == "redshift" && count($params) * count($first) > 32767) { $noParams = true; } $values = ""; foreach ($params as $row) { if ($values) { $values .= ","; } $values .= "("; $first = true; foreach ($row as $key => $val) { if ($first) { $first = false; } else { $values .= ","; } if ($noParams) { $values .= "'" . pg_escape_string($val) . "'"; } else { $values .= "?"; $newParams[] = $val; } } $values .= ")"; } $tableName = $this->getTableName($table); if ($extra === self::INSERT_REPLACE) { $query = "REPLACE "; } elseif ($extra === self::INSERT_IGNORE) { $query = "INSERT IGNORE "; } else { $query = "INSERT "; } $query .= "INTO " . $tableName . " (" . $fields . ") VALUES " . $values; $result = $this->query($query, $newParams); break; case "postgres": $fields = ""; $first = reset($params); foreach ($first as $key => $val) { if ($fields) { $fields .= ","; } $fields .= $this->quoteField($key); } $tableName = $this->getTableName($table); $this->query("COPY " . $tableName . " (" . $fields . ") FROM STDIN"); foreach ($params as $row) { if (!pg_put_line($this->server, implode("\t", $row) . "\n")) { $this->error(); } } if (pg_put_line($this->server, "\\.\n")) { $this->error(); } $result = new Result(pg_end_copy($this->server), $this->mode); break; default: $result = true; foreach ($params as $newParams) { if (!$this->insert($table, $newParams)) { $result = false; break; } } } if (!$result) { $this->error(); } if ($output) { $this->output = true; } return $result; }
public function putLine($line) { return pg_put_line($this->conn, $line); }