Exemple #1
0
 private function _batchInsertMySQL($qTableName, $fieldList, $aValues, $replace)
 {
     $oDbh = OA_DB::singleton();
     // File path defaults to var/cache
     if (!isset(self::$batchInsertPath)) {
         self::$batchInsertPath = MAX_PATH . '/var/cache';
     }
     // Create file path using hostname and table name
     $filePath = self::$batchInsertPath . '/' . OX_getHostName() . '-batch-' . $qTableName . '.csv';
     if (DIRECTORY_SEPARATOR == '\\') {
         // On windows, MySQL expects slashes as directory separators
         $filePath = str_replace('\\', '/', $filePath);
     }
     if ($replace) {
         $replace = ' REPLACE ';
     } else {
         $replace = '';
     }
     // Set up CSV delimiters, quotes, etc
     $delim = "\t";
     $quote = '"';
     $eol = "\n";
     $null = 'NULL';
     // Disable error handler
     RV::disableErrorHandling();
     $fp = fopen($filePath, 'wb');
     if (!$fp) {
         return MAX::raiseError('Error creating the tmp file ' . $filePath . ' containing the batch INSERTs.', PEAR_ERROR_RETURN);
     }
     // ensure that when maintenance is run in crontab, as root eg.
     // the file can still be overwritten by maintenance ran from the UI
     @chmod($filePath, 0777);
     foreach ($aValues as $aRow) {
         // Stringify row
         $row = '';
         foreach ($aRow as $value) {
             if (!isset($value) || is_null($value) || $value === false) {
                 $row .= $null . $delim;
             } else {
                 $row .= $quote . $value . $quote . $delim;
             }
         }
         // Replace delim with eol
         $row[strlen($row) - 1] = $eol;
         // Append
         $ret = fwrite($fp, $row);
         if (!$ret) {
             fclose($fp);
             unlink($filePath);
             return MAX::raiseError('Error writing to the tmp file ' . $filePath . ' containing the batch INSERTs.', PEAR_ERROR_RETURN);
         }
     }
     fclose($fp);
     $query = "\n            LOAD DATA LOCAL INFILE\n                '{$filePath}'\n                {$replace}\n            INTO TABLE\n                {$qTableName}\n            FIELDS TERMINATED BY\n                " . $oDbh->quote($delim) . "\n            ENCLOSED BY\n                " . $oDbh->quote($quote) . "\n            ESCAPED BY\n                ''\n            LINES TERMINATED BY\n                " . $oDbh->quote($eol) . "\n        \t{$fieldList}\n        ";
     $result = $oDbh->exec($query);
     @unlink($filePath);
     // Enable error handler again
     RV::enableErrorHandling();
     return $result;
 }