PageRenderTime 63ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/classes/Import.php

http://github.com/phpmyadmin/phpmyadmin
PHP | 1794 lines | 1196 code | 195 blank | 403 comment | 214 complexity | 6825622287c8fb418f9cb9c7b76ea654 MD5 | raw file
Possible License(s): GPL-2.0, MIT, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpMyAdmin;
  4. use PhpMyAdmin\SqlParser\Parser;
  5. use PhpMyAdmin\SqlParser\Statements\DeleteStatement;
  6. use PhpMyAdmin\SqlParser\Statements\InsertStatement;
  7. use PhpMyAdmin\SqlParser\Statements\ReplaceStatement;
  8. use PhpMyAdmin\SqlParser\Statements\UpdateStatement;
  9. use PhpMyAdmin\SqlParser\Utils\Query;
  10. use function __;
  11. use function abs;
  12. use function count;
  13. use function explode;
  14. use function function_exists;
  15. use function htmlspecialchars;
  16. use function implode;
  17. use function is_array;
  18. use function is_numeric;
  19. use function max;
  20. use function mb_chr;
  21. use function mb_ord;
  22. use function mb_stripos;
  23. use function mb_strlen;
  24. use function mb_strpos;
  25. use function mb_strtoupper;
  26. use function mb_substr;
  27. use function mb_substr_count;
  28. use function preg_match;
  29. use function preg_replace;
  30. use function sprintf;
  31. use function str_contains;
  32. use function str_starts_with;
  33. use function strcmp;
  34. use function strlen;
  35. use function strpos;
  36. use function strtoupper;
  37. use function substr;
  38. use function time;
  39. use function trim;
  40. /**
  41. * Library that provides common import functions that are used by import plugins
  42. */
  43. class Import
  44. {
  45. /* MySQL type defs */
  46. public const NONE = 0;
  47. public const VARCHAR = 1;
  48. public const INT = 2;
  49. public const DECIMAL = 3;
  50. public const BIGINT = 4;
  51. public const GEOMETRY = 5;
  52. /* Decimal size defs */
  53. public const M = 0;
  54. public const D = 1;
  55. public const FULL = 2;
  56. /* Table array defs */
  57. public const TBL_NAME = 0;
  58. public const COL_NAMES = 1;
  59. public const ROWS = 2;
  60. /* Analysis array defs */
  61. public const TYPES = 0;
  62. public const SIZES = 1;
  63. public const FORMATTEDSQL = 2;
  64. public function __construct()
  65. {
  66. global $dbi;
  67. $GLOBALS['cfg']['Server']['DisableIS'] = false;
  68. $checkUserPrivileges = new CheckUserPrivileges($dbi);
  69. $checkUserPrivileges->getPrivileges();
  70. }
  71. /**
  72. * Checks whether timeout is getting close
  73. *
  74. * @access public
  75. */
  76. public function checkTimeout(): bool
  77. {
  78. global $timestamp, $maximum_time, $timeout_passed;
  79. if ($maximum_time == 0) {
  80. return false;
  81. }
  82. if ($timeout_passed) {
  83. return true;
  84. /* 5 in next row might be too much */
  85. }
  86. if (time() - $timestamp > $maximum_time - 5) {
  87. $timeout_passed = true;
  88. return true;
  89. }
  90. return false;
  91. }
  92. /**
  93. * Runs query inside import buffer. This is needed to allow displaying
  94. * of last SELECT, SHOW or HANDLER results and similar nice stuff.
  95. *
  96. * @param string $sql query to run
  97. * @param string $full query to display, this might be commented
  98. * @param array $sqlData SQL parse data storage
  99. *
  100. * @access public
  101. */
  102. public function executeQuery(string $sql, string $full, array &$sqlData): void
  103. {
  104. global $sql_query, $my_die, $error, $reload, $result, $msg, $cfg, $sql_query_disabled, $db, $dbi;
  105. $result = $dbi->tryQuery($sql);
  106. // USE query changes the database, son need to track
  107. // while running multiple queries
  108. $isUseQuery = mb_stripos($sql, 'use ') !== false;
  109. $msg = '# ';
  110. if ($result === false) { // execution failed
  111. if (! isset($my_die)) {
  112. $my_die = [];
  113. }
  114. $my_die[] = [
  115. 'sql' => $full,
  116. 'error' => $dbi->getError(),
  117. ];
  118. $msg .= __('Error');
  119. if (! $cfg['IgnoreMultiSubmitErrors']) {
  120. $error = true;
  121. return;
  122. }
  123. } else {
  124. $aNumRows = (int) @$dbi->numRows($result);
  125. $aAffectedRows = (int) @$dbi->affectedRows();
  126. if ($aNumRows > 0) {
  127. $msg .= __('Rows') . ': ' . $aNumRows;
  128. } elseif ($aAffectedRows > 0) {
  129. $message = Message::getMessageForAffectedRows($aAffectedRows);
  130. $msg .= $message->getMessage();
  131. } else {
  132. $msg .= __('MySQL returned an empty result set (i.e. zero rows).');
  133. }
  134. if (($aNumRows > 0) || $isUseQuery) {
  135. $sqlData['valid_sql'][] = $sql;
  136. if (! isset($sqlData['valid_queries'])) {
  137. $sqlData['valid_queries'] = 0;
  138. }
  139. $sqlData['valid_queries']++;
  140. }
  141. }
  142. if (! $sql_query_disabled) {
  143. $sql_query .= $msg . "\n";
  144. }
  145. // If a 'USE <db>' SQL-clause was found and the query
  146. // succeeded, set our current $db to the new one
  147. if ($result != false) {
  148. [$db, $reload] = $this->lookForUse($sql, $db, $reload);
  149. }
  150. $pattern = '@^[\s]*(DROP|CREATE)[\s]+(IF EXISTS[[:space:]]+)?(TABLE|DATABASE)[[:space:]]+(.+)@im';
  151. if ($result == false || ! preg_match($pattern, $sql)) {
  152. return;
  153. }
  154. $reload = true;
  155. }
  156. /**
  157. * Runs query inside import buffer. This is needed to allow displaying
  158. * of last SELECT, SHOW or HANDLER results and similar nice stuff.
  159. *
  160. * @param string $sql query to run
  161. * @param string $full query to display, this might be commented
  162. * @param array $sqlData SQL parse data storage
  163. *
  164. * @access public
  165. */
  166. public function runQuery(
  167. string $sql = '',
  168. string $full = '',
  169. array &$sqlData = []
  170. ): void {
  171. global $import_run_buffer, $go_sql, $complete_query, $display_query, $sql_query, $msg,
  172. $skip_queries, $executed_queries, $max_sql_len, $read_multiply, $sql_query_disabled, $run_query;
  173. $read_multiply = 1;
  174. if (! isset($import_run_buffer)) {
  175. // Do we have something to push into buffer?
  176. $import_run_buffer = $this->runQueryPost($import_run_buffer, $sql, $full);
  177. return;
  178. }
  179. // Should we skip something?
  180. if ($skip_queries > 0) {
  181. $skip_queries--;
  182. // Do we have something to push into buffer?
  183. $import_run_buffer = $this->runQueryPost($import_run_buffer, $sql, $full);
  184. return;
  185. }
  186. if (! empty($import_run_buffer['sql']) && trim($import_run_buffer['sql']) != '') {
  187. $max_sql_len = max(
  188. $max_sql_len,
  189. mb_strlen($import_run_buffer['sql'])
  190. );
  191. if (! $sql_query_disabled) {
  192. $sql_query .= $import_run_buffer['full'];
  193. }
  194. $executed_queries++;
  195. if ($run_query && $executed_queries < 50) {
  196. $go_sql = true;
  197. if (! $sql_query_disabled) {
  198. $complete_query = $sql_query;
  199. $display_query = $sql_query;
  200. } else {
  201. $complete_query = '';
  202. $display_query = '';
  203. }
  204. $sql_query = $import_run_buffer['sql'];
  205. $sqlData['valid_sql'][] = $import_run_buffer['sql'];
  206. $sqlData['valid_full'][] = $import_run_buffer['full'];
  207. if (! isset($sqlData['valid_queries'])) {
  208. $sqlData['valid_queries'] = 0;
  209. }
  210. $sqlData['valid_queries']++;
  211. } elseif ($run_query) {
  212. /* Handle rollback from go_sql */
  213. if ($go_sql && isset($sqlData['valid_full'])) {
  214. $queries = $sqlData['valid_sql'];
  215. $fulls = $sqlData['valid_full'];
  216. $count = $sqlData['valid_queries'];
  217. $go_sql = false;
  218. $sqlData['valid_sql'] = [];
  219. $sqlData['valid_queries'] = 0;
  220. unset($sqlData['valid_full']);
  221. for ($i = 0; $i < $count; $i++) {
  222. $this->executeQuery($queries[$i], $fulls[$i], $sqlData);
  223. }
  224. }
  225. $this->executeQuery($import_run_buffer['sql'], $import_run_buffer['full'], $sqlData);
  226. }
  227. } elseif (! empty($import_run_buffer['full'])) {
  228. if ($go_sql) {
  229. $complete_query .= $import_run_buffer['full'];
  230. $display_query .= $import_run_buffer['full'];
  231. } elseif (! $sql_query_disabled) {
  232. $sql_query .= $import_run_buffer['full'];
  233. }
  234. }
  235. // check length of query unless we decided to pass it to /sql
  236. // (if $run_query is false, we are just displaying so show
  237. // the complete query in the textarea)
  238. if (! $go_sql && $run_query && ! empty($sql_query)) {
  239. if (mb_strlen($sql_query) > 50000 || $executed_queries > 50 || $max_sql_len > 1000) {
  240. $sql_query = '';
  241. $sql_query_disabled = true;
  242. }
  243. }
  244. // Do we have something to push into buffer?
  245. $import_run_buffer = $this->runQueryPost($import_run_buffer, $sql, $full);
  246. // In case of ROLLBACK, notify the user.
  247. if (! isset($_POST['rollback_query'])) {
  248. return;
  249. }
  250. $msg .= __('[ROLLBACK occurred.]');
  251. }
  252. /**
  253. * Return import run buffer
  254. *
  255. * @param array $importRunBuffer Buffer of queries for import
  256. * @param string $sql SQL query
  257. * @param string $full Query to display
  258. *
  259. * @return array Buffer of queries for import
  260. */
  261. public function runQueryPost(
  262. ?array $importRunBuffer,
  263. string $sql,
  264. string $full
  265. ): ?array {
  266. if (! empty($sql) || ! empty($full)) {
  267. return [
  268. 'sql' => $sql . ';',
  269. 'full' => $full . ';',
  270. ];
  271. }
  272. unset($GLOBALS['import_run_buffer']);
  273. return $importRunBuffer;
  274. }
  275. /**
  276. * Looks for the presence of USE to possibly change current db
  277. *
  278. * @param string $buffer buffer to examine
  279. * @param string $db current db
  280. * @param bool $reload reload
  281. *
  282. * @return array (current or new db, whether to reload)
  283. *
  284. * @access public
  285. */
  286. public function lookForUse(?string $buffer, ?string $db, ?bool $reload): array
  287. {
  288. if (preg_match('@^[\s]*USE[[:space:]]+([\S]+)@i', (string) $buffer, $match)) {
  289. $db = trim($match[1]);
  290. $db = trim($db, ';'); // for example, USE abc;
  291. // $db must not contain the escape characters generated by backquote()
  292. // ( used in buildSql() as: backquote($db_name), and then called
  293. // in runQuery() which in turn calls lookForUse() )
  294. $db = Util::unQuote($db);
  295. $reload = true;
  296. }
  297. return [
  298. $db,
  299. $reload,
  300. ];
  301. }
  302. /**
  303. * Returns next part of imported file/buffer
  304. *
  305. * @param int $size size of buffer to read (this is maximal size function will return)
  306. *
  307. * @return string|bool part of file/buffer
  308. */
  309. public function getNextChunk(?File $importHandle = null, int $size = 32768)
  310. {
  311. global $charset_conversion, $charset_of_file, $read_multiply;
  312. // Add some progression while reading large amount of data
  313. if ($read_multiply <= 8) {
  314. $size *= $read_multiply;
  315. } else {
  316. $size *= 8;
  317. }
  318. $read_multiply++;
  319. // We can not read too much
  320. if ($size > $GLOBALS['read_limit']) {
  321. $size = $GLOBALS['read_limit'];
  322. }
  323. if ($this->checkTimeout()) {
  324. return false;
  325. }
  326. if ($GLOBALS['finished']) {
  327. return true;
  328. }
  329. if ($GLOBALS['import_file'] === 'none') {
  330. // Well this is not yet supported and tested,
  331. // but should return content of textarea
  332. if (mb_strlen($GLOBALS['import_text']) < $size) {
  333. $GLOBALS['finished'] = true;
  334. return $GLOBALS['import_text'];
  335. }
  336. $r = mb_substr($GLOBALS['import_text'], 0, $size);
  337. $GLOBALS['offset'] += $size;
  338. $GLOBALS['import_text'] = mb_substr($GLOBALS['import_text'], $size);
  339. return $r;
  340. }
  341. if ($importHandle === null) {
  342. return false;
  343. }
  344. $result = $importHandle->read($size);
  345. $GLOBALS['finished'] = $importHandle->eof();
  346. $GLOBALS['offset'] += $size;
  347. if ($charset_conversion) {
  348. return Encoding::convertString($charset_of_file, 'utf-8', $result);
  349. }
  350. /**
  351. * Skip possible byte order marks (I do not think we need more
  352. * charsets, but feel free to add more, you can use wikipedia for
  353. * reference: <https://en.wikipedia.org/wiki/Byte_Order_Mark>)
  354. *
  355. * @todo BOM could be used for charset autodetection
  356. */
  357. if ($GLOBALS['offset'] == $size) {
  358. $result = $this->skipByteOrderMarksFromContents($result);
  359. }
  360. return $result;
  361. }
  362. /**
  363. * Skip possible byte order marks (I do not think we need more
  364. * charsets, but feel free to add more, you can use wikipedia for
  365. * reference: <https://en.wikipedia.org/wiki/Byte_Order_Mark>)
  366. *
  367. * @param string $contents The contents to strip BOM
  368. *
  369. * @todo BOM could be used for charset autodetection
  370. */
  371. public function skipByteOrderMarksFromContents(string $contents): string
  372. {
  373. // Do not use mb_ functions they are sensible to mb_internal_encoding()
  374. // UTF-8
  375. if (str_starts_with($contents, "\xEF\xBB\xBF")) {
  376. return substr($contents, 3);
  377. // UTF-16 BE, LE
  378. }
  379. if (str_starts_with($contents, "\xFE\xFF") || str_starts_with($contents, "\xFF\xFE")) {
  380. return substr($contents, 2);
  381. }
  382. return $contents;
  383. }
  384. /**
  385. * Returns the "Excel" column name (i.e. 1 = "A", 26 = "Z", 27 = "AA", etc.)
  386. *
  387. * This functions uses recursion to build the Excel column name.
  388. *
  389. * The column number (1-26) is converted to the responding
  390. * ASCII character (A-Z) and returned.
  391. *
  392. * If the column number is bigger than 26 (= num of letters in alphabet),
  393. * an extra character needs to be added. To find this extra character,
  394. * the number is divided by 26 and this value is passed to another instance
  395. * of the same function (hence recursion). In that new instance the number is
  396. * evaluated again, and if it is still bigger than 26, it is divided again
  397. * and passed to another instance of the same function. This continues until
  398. * the number is smaller than 26. Then the last called function returns
  399. * the corresponding ASCII character to the function that called it.
  400. * Each time a called function ends an extra character is added to the column name.
  401. * When the first function is reached, the last character is added and the complete
  402. * column name is returned.
  403. *
  404. * @param int $num the column number
  405. *
  406. * @return string The column's "Excel" name
  407. *
  408. * @access public
  409. */
  410. public function getColumnAlphaName(int $num): string
  411. {
  412. $capitalA = 65; // ASCII value for capital "A"
  413. $colName = '';
  414. if ($num > 26) {
  415. $div = (int) ($num / 26);
  416. $remain = $num % 26;
  417. // subtract 1 of divided value in case the modulus is 0,
  418. // this is necessary because A-Z has no 'zero'
  419. if ($remain == 0) {
  420. $div--;
  421. }
  422. // recursive function call
  423. $colName = $this->getColumnAlphaName($div);
  424. // use modulus as new column number
  425. $num = $remain;
  426. }
  427. if ($num == 0) {
  428. // use 'Z' if column number is 0,
  429. // this is necessary because A-Z has no 'zero'
  430. $colName .= mb_chr($capitalA + 26 - 1);
  431. } else {
  432. // convert column number to ASCII character
  433. $colName .= mb_chr($capitalA + $num - 1);
  434. }
  435. return $colName;
  436. }
  437. /**
  438. * Returns the column number based on the Excel name.
  439. * So "A" = 1, "Z" = 26, "AA" = 27, etc.
  440. *
  441. * Basically this is a base26 (A-Z) to base10 (0-9) conversion.
  442. * It iterates through all characters in the column name and
  443. * calculates the corresponding value, based on character value
  444. * (A = 1, ..., Z = 26) and position in the string.
  445. *
  446. * @param string $name column name(i.e. "A", or "BC", etc.)
  447. *
  448. * @return int The column number
  449. *
  450. * @access public
  451. */
  452. public function getColumnNumberFromName(string $name): int
  453. {
  454. if (empty($name)) {
  455. return 0;
  456. }
  457. $name = mb_strtoupper($name);
  458. $numChars = mb_strlen($name);
  459. $columnNumber = 0;
  460. for ($i = 0; $i < $numChars; ++$i) {
  461. // read string from back to front
  462. $charPos = $numChars - 1 - $i;
  463. // convert capital character to ASCII value
  464. // and subtract 64 to get corresponding decimal value
  465. // ASCII value of "A" is 65, "B" is 66, etc.
  466. // Decimal equivalent of "A" is 1, "B" is 2, etc.
  467. $number = (int) (mb_ord($name[$charPos]) - 64);
  468. // base26 to base10 conversion : multiply each number
  469. // with corresponding value of the position, in this case
  470. // $i=0 : 1; $i=1 : 26; $i=2 : 676; ...
  471. $columnNumber += $number * 26 ** $i;
  472. }
  473. return (int) $columnNumber;
  474. }
  475. /**
  476. * Obtains the precision (total # of digits) from a size of type decimal
  477. *
  478. * @param string $lastCumulativeSize Size of type decimal
  479. *
  480. * @return int Precision of the given decimal size notation
  481. *
  482. * @access public
  483. */
  484. public function getDecimalPrecision(string $lastCumulativeSize): int
  485. {
  486. return (int) substr(
  487. $lastCumulativeSize,
  488. 0,
  489. (int) strpos($lastCumulativeSize, ',')
  490. );
  491. }
  492. /**
  493. * Obtains the scale (# of digits to the right of the decimal point)
  494. * from a size of type decimal
  495. *
  496. * @param string $lastCumulativeSize Size of type decimal
  497. *
  498. * @return int Scale of the given decimal size notation
  499. *
  500. * @access public
  501. */
  502. public function getDecimalScale(string $lastCumulativeSize): int
  503. {
  504. return (int) substr(
  505. $lastCumulativeSize,
  506. strpos($lastCumulativeSize, ',') + 1,
  507. strlen($lastCumulativeSize) - strpos($lastCumulativeSize, ',')
  508. );
  509. }
  510. /**
  511. * Obtains the decimal size of a given cell
  512. *
  513. * @param string $cell cell content
  514. *
  515. * @return array Contains the precision, scale, and full size
  516. * representation of the given decimal cell
  517. *
  518. * @access public
  519. */
  520. public function getDecimalSize(string $cell): array
  521. {
  522. $currSize = mb_strlen($cell);
  523. $decPos = mb_strpos($cell, '.');
  524. $decPrecision = $currSize - 1 - $decPos;
  525. $m = $currSize - 1;
  526. $d = $decPrecision;
  527. return [
  528. $m,
  529. $d,
  530. $m . ',' . $d,
  531. ];
  532. }
  533. /**
  534. * Obtains the size of the given cell
  535. *
  536. * @param string|int $lastCumulativeSize Last cumulative column size
  537. * @param int|null $lastCumulativeType Last cumulative column type (NONE or VARCHAR or DECIMAL or INT or BIGINT)
  538. * @param int $currentCellType Type of the current cell (NONE or VARCHAR or DECIMAL or INT or BIGINT)
  539. * @param string $cell The current cell
  540. *
  541. * @return string|int Size of the given cell in the type-appropriate format
  542. *
  543. * @access public
  544. * @todo Handle the error cases more elegantly
  545. */
  546. public function detectSize(
  547. $lastCumulativeSize,
  548. ?int $lastCumulativeType,
  549. int $currentCellType,
  550. string $cell
  551. ) {
  552. $currSize = mb_strlen($cell);
  553. /**
  554. * If the cell is NULL, don't treat it as a varchar
  555. */
  556. if (! strcmp('NULL', $cell)) {
  557. return $lastCumulativeSize;
  558. }
  559. if ($currentCellType == self::VARCHAR) {
  560. /**
  561. * What to do if the current cell is of type VARCHAR
  562. */
  563. /**
  564. * The last cumulative type was VARCHAR
  565. */
  566. if ($lastCumulativeType == self::VARCHAR) {
  567. if ($currSize >= $lastCumulativeSize) {
  568. return $currSize;
  569. }
  570. return $lastCumulativeSize;
  571. }
  572. if ($lastCumulativeType == self::DECIMAL) {
  573. /**
  574. * The last cumulative type was DECIMAL
  575. */
  576. $oldM = $this->getDecimalPrecision($lastCumulativeSize);
  577. if ($currSize >= $oldM) {
  578. return $currSize;
  579. }
  580. return $oldM;
  581. }
  582. if ($lastCumulativeType == self::BIGINT || $lastCumulativeType == self::INT) {
  583. /**
  584. * The last cumulative type was BIGINT or INT
  585. */
  586. if ($currSize >= $lastCumulativeSize) {
  587. return $currSize;
  588. }
  589. return $lastCumulativeSize;
  590. }
  591. if (! isset($lastCumulativeType) || $lastCumulativeType == self::NONE) {
  592. /**
  593. * This is the first row to be analyzed
  594. */
  595. return $currSize;
  596. }
  597. /**
  598. * An error has DEFINITELY occurred
  599. */
  600. /**
  601. * TODO: Handle this MUCH more elegantly
  602. */
  603. return -1;
  604. }
  605. if ($currentCellType == self::DECIMAL) {
  606. /**
  607. * What to do if the current cell is of type DECIMAL
  608. */
  609. /**
  610. * The last cumulative type was VARCHAR
  611. */
  612. if ($lastCumulativeType == self::VARCHAR) {
  613. /* Convert $last_cumulative_size from varchar to decimal format */
  614. $size = $this->getDecimalSize($cell);
  615. if ($size[self::M] >= $lastCumulativeSize) {
  616. return $size[self::M];
  617. }
  618. return $lastCumulativeSize;
  619. }
  620. if ($lastCumulativeType == self::DECIMAL) {
  621. /**
  622. * The last cumulative type was DECIMAL
  623. */
  624. $size = $this->getDecimalSize($cell);
  625. $oldM = $this->getDecimalPrecision($lastCumulativeSize);
  626. $oldD = $this->getDecimalScale($lastCumulativeSize);
  627. /* New val if M or D is greater than current largest */
  628. if ($size[self::M] > $oldM || $size[self::D] > $oldD) {
  629. /* Take the largest of both types */
  630. return (string) (($size[self::M] > $oldM ? $size[self::M] : $oldM)
  631. . ',' . ($size[self::D] > $oldD ? $size[self::D] : $oldD));
  632. }
  633. return $lastCumulativeSize;
  634. }
  635. if ($lastCumulativeType == self::BIGINT || $lastCumulativeType == self::INT) {
  636. /**
  637. * The last cumulative type was BIGINT or INT
  638. */
  639. /* Convert $last_cumulative_size from int to decimal format */
  640. $size = $this->getDecimalSize($cell);
  641. if ($size[self::M] >= $lastCumulativeSize) {
  642. return $size[self::FULL];
  643. }
  644. return $lastCumulativeSize . ',' . $size[self::D];
  645. }
  646. if (! isset($lastCumulativeType) || $lastCumulativeType == self::NONE) {
  647. /**
  648. * This is the first row to be analyzed
  649. */
  650. /* First row of the column */
  651. $size = $this->getDecimalSize($cell);
  652. return $size[self::FULL];
  653. }
  654. /**
  655. * An error has DEFINITELY occurred
  656. */
  657. /**
  658. * TODO: Handle this MUCH more elegantly
  659. */
  660. return -1;
  661. }
  662. if ($currentCellType == self::BIGINT || $currentCellType == self::INT) {
  663. /**
  664. * What to do if the current cell is of type BIGINT or INT
  665. */
  666. /**
  667. * The last cumulative type was VARCHAR
  668. */
  669. if ($lastCumulativeType == self::VARCHAR) {
  670. if ($currSize >= $lastCumulativeSize) {
  671. return $currSize;
  672. }
  673. return $lastCumulativeSize;
  674. }
  675. if ($lastCumulativeType == self::DECIMAL) {
  676. /**
  677. * The last cumulative type was DECIMAL
  678. */
  679. $oldM = $this->getDecimalPrecision($lastCumulativeSize);
  680. $oldD = $this->getDecimalScale($lastCumulativeSize);
  681. $oldInt = $oldM - $oldD;
  682. $newInt = mb_strlen((string) $cell);
  683. /* See which has the larger integer length */
  684. if ($oldInt >= $newInt) {
  685. /* Use old decimal size */
  686. return $lastCumulativeSize;
  687. }
  688. /* Use $newInt + $oldD as new M */
  689. return ($newInt + $oldD) . ',' . $oldD;
  690. }
  691. if ($lastCumulativeType == self::BIGINT || $lastCumulativeType == self::INT) {
  692. /**
  693. * The last cumulative type was BIGINT or INT
  694. */
  695. if ($currSize >= $lastCumulativeSize) {
  696. return $currSize;
  697. }
  698. return $lastCumulativeSize;
  699. }
  700. if (! isset($lastCumulativeType) || $lastCumulativeType == self::NONE) {
  701. /**
  702. * This is the first row to be analyzed
  703. */
  704. return $currSize;
  705. }
  706. /**
  707. * An error has DEFINITELY occurred
  708. */
  709. /**
  710. * TODO: Handle this MUCH more elegantly
  711. */
  712. return -1;
  713. }
  714. /**
  715. * An error has DEFINITELY occurred
  716. */
  717. /**
  718. * TODO: Handle this MUCH more elegantly
  719. */
  720. return -1;
  721. }
  722. /**
  723. * Determines what MySQL type a cell is
  724. *
  725. * @param int $lastCumulativeType Last cumulative column type
  726. * (VARCHAR or INT or BIGINT or DECIMAL or NONE)
  727. * @param string|null $cell String representation of the cell for which
  728. * a best-fit type is to be determined
  729. *
  730. * @return int The MySQL type representation
  731. * (VARCHAR or INT or BIGINT or DECIMAL or NONE)
  732. *
  733. * @access public
  734. */
  735. public function detectType(?int $lastCumulativeType, ?string $cell): int
  736. {
  737. /**
  738. * If numeric, determine if decimal, int or bigint
  739. * Else, we call it varchar for simplicity
  740. */
  741. if (! strcmp('NULL', (string) $cell)) {
  742. if ($lastCumulativeType === null || $lastCumulativeType == self::NONE) {
  743. return self::NONE;
  744. }
  745. return $lastCumulativeType;
  746. }
  747. if (! is_numeric($cell)) {
  748. return self::VARCHAR;
  749. }
  750. if (
  751. $cell == (string) (float) $cell
  752. && str_contains((string) $cell, '.')
  753. && mb_substr_count((string) $cell, '.') === 1
  754. ) {
  755. return self::DECIMAL;
  756. }
  757. if (abs((int) $cell) > 2147483647) {
  758. return self::BIGINT;
  759. }
  760. if ($cell !== (string) (int) $cell) {
  761. return self::VARCHAR;
  762. }
  763. return self::INT;
  764. }
  765. /**
  766. * Determines if the column types are int, decimal, or string
  767. *
  768. * @link https://wiki.phpmyadmin.net/pma/Import
  769. *
  770. * @param array $table array(string $table_name, array $col_names, array $rows)
  771. *
  772. * @return array|bool array(array $types, array $sizes)
  773. *
  774. * @access public
  775. * @todo Handle the error case more elegantly
  776. */
  777. public function analyzeTable(array &$table)
  778. {
  779. /* Get number of rows in table */
  780. $numRows = count($table[self::ROWS]);
  781. /* Get number of columns */
  782. $numCols = count($table[self::COL_NAMES]);
  783. /* Current type for each column */
  784. $types = [];
  785. $sizes = [];
  786. /* Initialize $sizes to all 0's */
  787. for ($i = 0; $i < $numCols; ++$i) {
  788. $sizes[$i] = 0;
  789. }
  790. /* Initialize $types to NONE */
  791. for ($i = 0; $i < $numCols; ++$i) {
  792. $types[$i] = self::NONE;
  793. }
  794. /* If the passed array is not of the correct form, do not process it */
  795. if (
  796. ! is_array($table)
  797. || is_array($table[self::TBL_NAME])
  798. || ! is_array($table[self::COL_NAMES])
  799. || ! is_array($table[self::ROWS])
  800. ) {
  801. /**
  802. * TODO: Handle this better
  803. */
  804. return false;
  805. }
  806. /* Analyze each column */
  807. for ($i = 0; $i < $numCols; ++$i) {
  808. /* Analyze the column in each row */
  809. for ($j = 0; $j < $numRows; ++$j) {
  810. $cellValue = $table[self::ROWS][$j][$i];
  811. /* Determine type of the current cell */
  812. $currType = $this->detectType($types[$i], $cellValue === null ? null : (string) $cellValue);
  813. /* Determine size of the current cell */
  814. $sizes[$i] = $this->detectSize($sizes[$i], $types[$i], $currType, (string) $cellValue);
  815. /**
  816. * If a type for this column has already been declared,
  817. * only alter it if it was a number and a varchar was found
  818. */
  819. if ($currType == self::NONE) {
  820. continue;
  821. }
  822. if ($currType == self::VARCHAR) {
  823. $types[$i] = self::VARCHAR;
  824. } elseif ($currType == self::DECIMAL) {
  825. if ($types[$i] != self::VARCHAR) {
  826. $types[$i] = self::DECIMAL;
  827. }
  828. } elseif ($currType == self::BIGINT) {
  829. if ($types[$i] != self::VARCHAR && $types[$i] != self::DECIMAL) {
  830. $types[$i] = self::BIGINT;
  831. }
  832. } elseif ($currType == self::INT) {
  833. if ($types[$i] != self::VARCHAR && $types[$i] != self::DECIMAL && $types[$i] != self::BIGINT) {
  834. $types[$i] = self::INT;
  835. }
  836. }
  837. }
  838. }
  839. /* Check to ensure that all types are valid */
  840. $len = count($types);
  841. for ($n = 0; $n < $len; ++$n) {
  842. if (strcmp((string) self::NONE, (string) $types[$n])) {
  843. continue;
  844. }
  845. $types[$n] = self::VARCHAR;
  846. $sizes[$n] = '10';
  847. }
  848. return [
  849. $types,
  850. $sizes,
  851. ];
  852. }
  853. /**
  854. * Builds and executes SQL statements to create the database and tables
  855. * as necessary, as well as insert all the data.
  856. *
  857. * @link https://wiki.phpmyadmin.net/pma/Import
  858. *
  859. * @param string $dbName Name of the database
  860. * @param array $tables Array of tables for the specified database
  861. * @param array|null $analyses Analyses of the tables
  862. * @param array|null $additionalSql Additional SQL statements to be executed
  863. * @param array|null $options Associative array of options
  864. * @param array $sqlData 2-element array with sql data
  865. *
  866. * @access public
  867. */
  868. public function buildSql(
  869. string $dbName,
  870. array &$tables,
  871. ?array &$analyses = null,
  872. ?array &$additionalSql = null,
  873. ?array $options = null,
  874. array &$sqlData = []
  875. ): void {
  876. global $import_notice, $dbi;
  877. /* Needed to quell the beast that is Message */
  878. $import_notice = null;
  879. /* Take care of the options */
  880. if (isset($options['db_collation']) && $options['db_collation'] !== null) {
  881. $collation = $options['db_collation'];
  882. } else {
  883. $collation = 'utf8_general_ci';
  884. }
  885. if (isset($options['db_charset']) && $options['db_charset'] !== null) {
  886. $charset = $options['db_charset'];
  887. } else {
  888. $charset = 'utf8';
  889. }
  890. if (isset($options['create_db'])) {
  891. $createDb = $options['create_db'];
  892. } else {
  893. $createDb = true;
  894. }
  895. /**
  896. * Create SQL code to handle the database
  897. *
  898. * @var array<int,string> $sql
  899. */
  900. $sql = [];
  901. if ($createDb) {
  902. $sql[] = 'CREATE DATABASE IF NOT EXISTS ' . Util::backquote($dbName)
  903. . ' DEFAULT CHARACTER SET ' . $charset . ' COLLATE ' . $collation
  904. . ';';
  905. }
  906. /**
  907. * The calling plug-in should include this statement,
  908. * if necessary, in the $additional_sql parameter
  909. *
  910. * $sql[] = "USE " . backquote($db_name);
  911. */
  912. /* Execute the SQL statements create above */
  913. $sqlLength = count($sql);
  914. for ($i = 0; $i < $sqlLength; ++$i) {
  915. $this->runQuery($sql[$i], $sql[$i], $sqlData);
  916. }
  917. /* No longer needed */
  918. unset($sql);
  919. /* Run the $additional_sql statements supplied by the caller plug-in */
  920. if ($additionalSql != null) {
  921. /* Clean the SQL first */
  922. $additionalSqlLength = count($additionalSql);
  923. /**
  924. * Only match tables for now, because CREATE IF NOT EXISTS
  925. * syntax is lacking or nonexisting for views, triggers,
  926. * functions, and procedures.
  927. *
  928. * See: https://bugs.mysql.com/bug.php?id=15287
  929. *
  930. * To the best of my knowledge this is still an issue.
  931. *
  932. * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
  933. */
  934. $pattern = '/CREATE [^`]*(TABLE)/';
  935. $replacement = 'CREATE \\1 IF NOT EXISTS';
  936. /* Change CREATE statements to CREATE IF NOT EXISTS to support
  937. * inserting into existing structures
  938. */
  939. for ($i = 0; $i < $additionalSqlLength; ++$i) {
  940. $additionalSql[$i] = preg_replace($pattern, $replacement, $additionalSql[$i]);
  941. /* Execute the resulting statements */
  942. $this->runQuery($additionalSql[$i], $additionalSql[$i], $sqlData);
  943. }
  944. }
  945. if ($analyses != null) {
  946. $typeArray = [
  947. self::NONE => 'NULL',
  948. self::VARCHAR => 'varchar',
  949. self::INT => 'int',
  950. self::DECIMAL => 'decimal',
  951. self::BIGINT => 'bigint',
  952. self::GEOMETRY => 'geometry',
  953. ];
  954. /* TODO: Do more checking here to make sure they really are matched */
  955. if (count($tables) != count($analyses)) {
  956. exit;
  957. }
  958. /* Create SQL code to create the tables */
  959. $numTables = count($tables);
  960. for ($i = 0; $i < $numTables; ++$i) {
  961. $numCols = count($tables[$i][self::COL_NAMES]);
  962. $tempSQLStr = 'CREATE TABLE IF NOT EXISTS '
  963. . Util::backquote($dbName)
  964. . '.' . Util::backquote($tables[$i][self::TBL_NAME]) . ' (';
  965. for ($j = 0; $j < $numCols; ++$j) {
  966. $size = $analyses[$i][self::SIZES][$j];
  967. if ((int) $size == 0) {
  968. $size = 10;
  969. }
  970. $tempSQLStr .= Util::backquote($tables[$i][self::COL_NAMES][$j]) . ' '
  971. . $typeArray[$analyses[$i][self::TYPES][$j]];
  972. if ($analyses[$i][self::TYPES][$j] != self::GEOMETRY) {
  973. $tempSQLStr .= '(' . $size . ')';
  974. }
  975. if ($j == count($tables[$i][self::COL_NAMES]) - 1) {
  976. continue;
  977. }
  978. $tempSQLStr .= ', ';
  979. }
  980. $tempSQLStr .= ') DEFAULT CHARACTER SET ' . $charset
  981. . ' COLLATE ' . $collation . ';';
  982. /**
  983. * Each SQL statement is executed immediately
  984. * after it is formed so that we don't have
  985. * to store them in a (possibly large) buffer
  986. */
  987. $this->runQuery($tempSQLStr, $tempSQLStr, $sqlData);
  988. }
  989. }
  990. /**
  991. * Create the SQL statements to insert all the data
  992. *
  993. * Only one insert query is formed for each table
  994. */
  995. $tempSQLStr = '';
  996. $colCount = 0;
  997. $numTables = count($tables);
  998. for ($i = 0; $i < $numTables; ++$i) {
  999. $numCols = count($tables[$i][self::COL_NAMES]);
  1000. $numRows = count($tables[$i][self::ROWS]);
  1001. $tempSQLStr = 'INSERT INTO ' . Util::backquote($dbName) . '.'
  1002. . Util::backquote($tables[$i][self::TBL_NAME]) . ' (';
  1003. for ($m = 0; $m < $numCols; ++$m) {
  1004. $tempSQLStr .= Util::backquote($tables[$i][self::COL_NAMES][$m]);
  1005. if ($m == $numCols - 1) {
  1006. continue;
  1007. }
  1008. $tempSQLStr .= ', ';
  1009. }
  1010. $tempSQLStr .= ') VALUES ';
  1011. for ($j = 0; $j < $numRows; ++$j) {
  1012. $tempSQLStr .= '(';
  1013. for ($k = 0; $k < $numCols; ++$k) {
  1014. // If fully formatted SQL, no need to enclose
  1015. // with apostrophes, add slashes etc.
  1016. if (
  1017. $analyses != null
  1018. && isset($analyses[$i][self::FORMATTEDSQL][$colCount])
  1019. && $analyses[$i][self::FORMATTEDSQL][$colCount] == true
  1020. ) {
  1021. $tempSQLStr .= (string) $tables[$i][self::ROWS][$j][$k];
  1022. } else {
  1023. if ($analyses != null) {
  1024. $isVarchar = ($analyses[$i][self::TYPES][$colCount] === self::VARCHAR);
  1025. } else {
  1026. $isVarchar = ! is_numeric($tables[$i][self::ROWS][$j][$k]);
  1027. }
  1028. /* Don't put quotes around NULL fields */
  1029. if (! strcmp((string) $tables[$i][self::ROWS][$j][$k], 'NULL')) {
  1030. $isVarchar = false;
  1031. }
  1032. $tempSQLStr .= $isVarchar ? "'" : '';
  1033. $tempSQLStr .= $dbi->escapeString((string) $tables[$i][self::ROWS][$j][$k]);
  1034. $tempSQLStr .= $isVarchar ? "'" : '';
  1035. }
  1036. if ($k != $numCols - 1) {
  1037. $tempSQLStr .= ', ';
  1038. }
  1039. if ($colCount == $numCols - 1) {
  1040. $colCount = 0;
  1041. } else {
  1042. $colCount++;
  1043. }
  1044. /* Delete the cell after we are done with it */
  1045. unset($tables[$i][self::ROWS][$j][$k]);
  1046. }
  1047. $tempSQLStr .= ')';
  1048. if ($j != $numRows - 1) {
  1049. $tempSQLStr .= ",\n ";
  1050. }
  1051. $colCount = 0;
  1052. /* Delete the row after we are done with it */
  1053. unset($tables[$i][self::ROWS][$j]);
  1054. }
  1055. $tempSQLStr .= ';';
  1056. /**
  1057. * Each SQL statement is executed immediately
  1058. * after it is formed so that we don't have
  1059. * to store them in a (possibly large) buffer
  1060. */
  1061. $this->runQuery($tempSQLStr, $tempSQLStr, $sqlData);
  1062. }
  1063. /* No longer needed */
  1064. unset($tempSQLStr);
  1065. /**
  1066. * A work in progress
  1067. */
  1068. /**
  1069. * Add the viewable structures from $additional_sql
  1070. * to $tables so they are also displayed
  1071. */
  1072. $viewPattern = '@VIEW `[^`]+`\.`([^`]+)@';
  1073. $tablePattern = '@CREATE TABLE IF NOT EXISTS `([^`]+)`@';
  1074. /* Check a third pattern to make sure its not a "USE `db_name`;" statement */
  1075. $regs = [];
  1076. $inTables = false;
  1077. $additionalSqlLength = $additionalSql === null ? 0 : count($additionalSql);
  1078. for ($i = 0; $i < $additionalSqlLength; ++$i) {
  1079. preg_match($viewPattern, $additionalSql[$i], $regs);
  1080. if (count($regs) === 0) {
  1081. preg_match($tablePattern, $additionalSql[$i], $regs);
  1082. }
  1083. if (count($regs)) {
  1084. for ($n = 0; $n < $numTables; ++$n) {
  1085. if (! strcmp($regs[1], $tables[$n][self::TBL_NAME])) {
  1086. $inTables = true;
  1087. break;
  1088. }
  1089. }
  1090. if (! $inTables) {
  1091. $tables[] = [self::TBL_NAME => $regs[1]];
  1092. }
  1093. }
  1094. /* Reset the array */
  1095. $regs = [];
  1096. $inTables = false;
  1097. }
  1098. $params = ['db' => $dbName];
  1099. $dbUrl = Url::getFromRoute('/database/structure', $params);
  1100. $dbOperationsUrl = Url::getFromRoute('/database/operations', $params);
  1101. $message = '<br><br>';
  1102. $message .= '<strong>' . __(
  1103. 'The following structures have either been created or altered. Here you can:'
  1104. ) . '</strong><br>';
  1105. $message .= '<ul><li>' . __("View a structure's contents by clicking on its name.") . '</li>';
  1106. $message .= '<li>' . __('Change any of its settings by clicking the corresponding "Options" link.') . '</li>';
  1107. $message .= '<li>' . __('Edit structure by following the "Structure" link.')
  1108. . '</li>';
  1109. $message .= sprintf(
  1110. '<br><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">'
  1111. . __('Options') . '</a>)</li>',
  1112. $dbUrl,
  1113. sprintf(
  1114. __('Go to database: %s'),
  1115. htmlspecialchars(Util::backquote($dbName))
  1116. ),
  1117. htmlspecialchars($dbName),
  1118. $dbOperationsUrl,
  1119. sprintf(
  1120. __('Edit settings for %s'),
  1121. htmlspecialchars(Util::backquote($dbName))
  1122. )
  1123. );
  1124. $message .= '<ul>';
  1125. unset($params);
  1126. foreach ($tables as $table) {
  1127. $params = [
  1128. 'db' => $dbName,
  1129. 'table' => (string) $table[self::TBL_NAME],
  1130. ];
  1131. $tblUrl = Url::getFromRoute('/sql', $params);
  1132. $tblStructUrl = Url::getFromRoute('/table/structure', $params);
  1133. $tblOpsUrl = Url::getFromRoute('/table/operations', $params);
  1134. unset($params);
  1135. $tableObj = new Table($table[self::TBL_NAME], $dbName);
  1136. if (! $tableObj->isView()) {
  1137. $message .= sprintf(
  1138. '<li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __(
  1139. 'Structure'
  1140. ) . '</a>) (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
  1141. $tblUrl,
  1142. sprintf(
  1143. __('Go to table: %s'),
  1144. htmlspecialchars(
  1145. Util::backquote($table[self::TBL_NAME])
  1146. )
  1147. ),
  1148. htmlspecialchars($table[self::TBL_NAME]),
  1149. $tblStructUrl,
  1150. sprintf(
  1151. __('Structure of %s'),
  1152. htmlspecialchars(
  1153. Util::backquote($table[self::TBL_NAME])
  1154. )
  1155. ),
  1156. $tblOpsUrl,
  1157. sprintf(
  1158. __('Edit settings for %s'),
  1159. htmlspecialchars(
  1160. Util::backquote($table[self::TBL_NAME])
  1161. )
  1162. )
  1163. );
  1164. } else {
  1165. $message .= sprintf(
  1166. '<li><a href="%s" title="%s">%s</a></li>',
  1167. $tblUrl,
  1168. sprintf(
  1169. __('Go to view: %s'),
  1170. htmlspecialchars(
  1171. Util::backquote($table[self::TBL_NAME])
  1172. )
  1173. ),
  1174. htmlspecialchars($table[self::TBL_NAME])
  1175. );
  1176. }
  1177. }
  1178. $message .= '</ul></ul>';
  1179. $import_notice = $message;
  1180. }
  1181. /**
  1182. * Handles request for Simulation of UPDATE/DELETE queries.
  1183. */
  1184. public function handleSimulateDmlRequest(): void
  1185. {
  1186. global $dbi;
  1187. $response = ResponseRenderer::getInstance();
  1188. $error = false;
  1189. $errorMsg = __('Only single-table UPDATE and DELETE queries can be simulated.');
  1190. $sqlDelimiter = $_POST['sql_delimiter'];
  1191. $sqlData = [];
  1192. $queries = explode($sqlDelimiter, $GLOBALS['sql_query']);
  1193. foreach ($queries as $sqlQuery) {
  1194. if (empty($sqlQuery)) {
  1195. continue;
  1196. }
  1197. // Parsing the query.
  1198. $parser = new Parser($sqlQuery);
  1199. if (empty($parser->statements[0])) {
  1200. continue;
  1201. }
  1202. $statement = $parser->statements[0];
  1203. $analyzedSqlResults = [
  1204. 'query' => $sqlQuery,
  1205. 'parser' => $parser,
  1206. 'statement' => $statement,
  1207. ];
  1208. if (
  1209. ! ($statement instanceof UpdateStatement
  1210. || $statement instanceof DeleteStatement)
  1211. || ! empty($statement->join)
  1212. ) {
  1213. $error = $errorMsg;
  1214. break;
  1215. }
  1216. $tables = Query::getTables($statement);
  1217. if (count($tables) > 1) {
  1218. $error = $errorMsg;
  1219. break;
  1220. }
  1221. // Get the matched rows for the query.
  1222. $result = $this->getMatchedRows($analyzedSqlResults);
  1223. $error = $dbi->getError();
  1224. if ($error !== false) {
  1225. break;
  1226. }
  1227. $sqlData[] = $result;
  1228. }
  1229. if ($error) {
  1230. $message = Message::rawError($error);
  1231. $response->addJSON('message', $message);
  1232. $response->addJSON('sql_data', false);
  1233. } else {
  1234. $response->addJSON('sql_data', $sqlData);
  1235. }
  1236. }
  1237. /**
  1238. * Find the matching rows for UPDATE/DELETE query.
  1239. *
  1240. * @param array $analyzedSqlResults Analyzed SQL results from parser.
  1241. *
  1242. * @return array
  1243. */
  1244. public function getMatchedRows(array $analyzedSqlResults = []): array
  1245. {
  1246. $statement = $analyzedSqlResults['statement'];
  1247. $matchedRowQuery = '';
  1248. if ($statement instanceof DeleteStatement) {
  1249. $matchedRowQuery = $this->getSimulatedDeleteQuery($analyzedSqlResults);
  1250. } elseif ($statement instanceof UpdateStatement) {
  1251. $matchedRowQuery = $this->getSimulatedUpdateQuery($analyzedSqlResults);
  1252. }
  1253. // Execute the query and get the number of matched rows.
  1254. $matchedRows = $this->executeMatchedRowQuery($matchedRowQuery);
  1255. // URL to matched rows.
  1256. $urlParams = [
  1257. 'db' => $GLOBALS['db'],
  1258. 'sql_query' => $matchedRowQuery,
  1259. ];
  1260. $matchedRowsUrl = Url::getFromRoute('/sql', $urlParams);
  1261. return [
  1262. 'sql_query' => Html\Generator::formatSql($analyzedSqlResults['query']),
  1263. 'matched_rows' => $matchedRows,
  1264. 'matched_rows_url' => $matchedRowsUrl,
  1265. ];
  1266. }
  1267. /**
  1268. * Transforms a UPDATE query into SELECT statement.
  1269. *
  1270. * @param array $analyzedSqlResults Analyzed SQL results from parser.
  1271. *
  1272. * @return string SQL query
  1273. */
  1274. public function getSimulatedUpdateQuery(array $analyzedSqlResults): string
  1275. {
  1276. $tableReferences = Query::getTables($analyzedSqlResults['statement']);
  1277. $where = Query::getClause($analyzedSqlResults['statement'], $analyzedSqlResults['parser']->list, 'WHERE');
  1278. if (empty($where)) {
  1279. $where = '1';
  1280. }
  1281. $columns = [];
  1282. $diff = [];
  1283. foreach ($analyzedSqlResults['statement']->set as $set) {
  1284. $columns[] = $set->column;
  1285. $notEqualOperator = ' <> ';
  1286. if (strtoupper($set->value) === 'NULL') {
  1287. $notEqualOperator = ' IS NOT ';
  1288. }
  1289. $diff[] = $set->column . $notEqualOperator . $set->value;
  1290. }
  1291. if (! empty($diff)) {
  1292. $where .= ' AND (' . implode(' OR ', $diff) . ')';
  1293. }
  1294. $orderAndLimit = '';
  1295. if (! empty($analyzedSqlResults['statement']->order)) {
  1296. $orderAndLimit .= ' ORDER BY ' . Query::getClause(
  1297. $analyzedSqlResults['statement'],
  1298. $analyzedSqlResults['parser']->list,
  1299. 'ORDER BY'
  1300. );
  1301. }
  1302. if (! empty($analyzedSqlResults['statement']->limit)) {
  1303. $orderAndLimit .= ' LIMIT ' . Query::getClause(
  1304. $analyzedSqlResults['sta…

Large files files are truncated, but you can click here to view the full file