ExportSql.php 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876
  1. <?php
  2. /**
  3. * Set of functions used to build SQL dumps of tables
  4. */
  5. declare(strict_types=1);
  6. namespace PhpMyAdmin\Plugins\Export;
  7. use PhpMyAdmin\Charsets;
  8. use PhpMyAdmin\DatabaseInterface;
  9. use PhpMyAdmin\FieldMetadata;
  10. use PhpMyAdmin\Plugins\ExportPlugin;
  11. use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
  12. use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
  13. use PhpMyAdmin\Properties\Options\Groups\OptionsPropertySubgroup;
  14. use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
  15. use PhpMyAdmin\Properties\Options\Items\MessageOnlyPropertyItem;
  16. use PhpMyAdmin\Properties\Options\Items\NumberPropertyItem;
  17. use PhpMyAdmin\Properties\Options\Items\RadioPropertyItem;
  18. use PhpMyAdmin\Properties\Options\Items\SelectPropertyItem;
  19. use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
  20. use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
  21. use PhpMyAdmin\SqlParser\Components\CreateDefinition;
  22. use PhpMyAdmin\SqlParser\Context;
  23. use PhpMyAdmin\SqlParser\Parser;
  24. use PhpMyAdmin\SqlParser\Statements\CreateStatement;
  25. use PhpMyAdmin\SqlParser\Token;
  26. use PhpMyAdmin\Util;
  27. use PhpMyAdmin\Version;
  28. use function __;
  29. use function array_keys;
  30. use function bin2hex;
  31. use function count;
  32. use function defined;
  33. use function explode;
  34. use function implode;
  35. use function in_array;
  36. use function intval;
  37. use function is_array;
  38. use function mb_strlen;
  39. use function mb_strpos;
  40. use function mb_substr;
  41. use function preg_quote;
  42. use function preg_replace;
  43. use function preg_split;
  44. use function sprintf;
  45. use function str_repeat;
  46. use function str_replace;
  47. use function strtotime;
  48. use function strtoupper;
  49. use function trigger_error;
  50. use const E_USER_ERROR;
  51. use const PHP_VERSION;
  52. /**
  53. * Handles the export for the SQL class
  54. */
  55. class ExportSql extends ExportPlugin
  56. {
  57. /**
  58. * Whether charset header was sent.
  59. *
  60. * @var bool
  61. */
  62. private $sentCharset = false;
  63. /** @var string */
  64. private $sqlViews = '';
  65. protected function init(): void
  66. {
  67. // Avoids undefined variables, use NULL so isset() returns false
  68. if (isset($GLOBALS['sql_backquotes'])) {
  69. return;
  70. }
  71. $GLOBALS['sql_backquotes'] = null;
  72. }
  73. /**
  74. * @psalm-return non-empty-lowercase-string
  75. */
  76. public function getName(): string
  77. {
  78. return 'sql';
  79. }
  80. protected function setProperties(): ExportPluginProperties
  81. {
  82. global $plugin_param, $dbi;
  83. $hideSql = false;
  84. $hideStructure = false;
  85. if ($plugin_param['export_type'] === 'table' && ! $plugin_param['single_table']) {
  86. $hideStructure = true;
  87. $hideSql = true;
  88. }
  89. // In case we have `raw_query` parameter set,
  90. // we initialize SQL option
  91. if (isset($_REQUEST['raw_query'])) {
  92. $hideStructure = false;
  93. $hideSql = false;
  94. }
  95. $exportPluginProperties = new ExportPluginProperties();
  96. $exportPluginProperties->setText('SQL');
  97. $exportPluginProperties->setExtension('sql');
  98. $exportPluginProperties->setMimeType('text/x-sql');
  99. if ($hideSql) {
  100. return $exportPluginProperties;
  101. }
  102. $exportPluginProperties->setOptionsText(__('Options'));
  103. // create the root group that will be the options field for
  104. // $exportPluginProperties
  105. // this will be shown as "Format specific options"
  106. $exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
  107. // general options main group
  108. $generalOptions = new OptionsPropertyMainGroup('general_opts');
  109. // comments
  110. $subgroup = new OptionsPropertySubgroup('include_comments');
  111. $leaf = new BoolPropertyItem(
  112. 'include_comments',
  113. __(
  114. 'Display comments <i>(includes info such as export timestamp, PHP version, and server version)</i>'
  115. )
  116. );
  117. $subgroup->setSubgroupHeader($leaf);
  118. $leaf = new TextPropertyItem(
  119. 'header_comment',
  120. __('Additional custom header comment (\n splits lines):')
  121. );
  122. $subgroup->addProperty($leaf);
  123. $leaf = new BoolPropertyItem(
  124. 'dates',
  125. __(
  126. 'Include a timestamp of when databases were created, last updated, and last checked'
  127. )
  128. );
  129. $subgroup->addProperty($leaf);
  130. $relationParameters = $this->relation->getRelationParameters();
  131. if ($relationParameters->relationFeature !== null) {
  132. $leaf = new BoolPropertyItem(
  133. 'relation',
  134. __('Display foreign key relationships')
  135. );
  136. $subgroup->addProperty($leaf);
  137. }
  138. if ($relationParameters->browserTransformationFeature !== null) {
  139. $leaf = new BoolPropertyItem(
  140. 'mime',
  141. __('Display media types')
  142. );
  143. $subgroup->addProperty($leaf);
  144. }
  145. $generalOptions->addProperty($subgroup);
  146. // enclose in a transaction
  147. $leaf = new BoolPropertyItem(
  148. 'use_transaction',
  149. __('Enclose export in a transaction')
  150. );
  151. $leaf->setDoc(
  152. [
  153. 'programs',
  154. 'mysqldump',
  155. 'option_mysqldump_single-transaction',
  156. ]
  157. );
  158. $generalOptions->addProperty($leaf);
  159. // disable foreign key checks
  160. $leaf = new BoolPropertyItem(
  161. 'disable_fk',
  162. __('Disable foreign key checks')
  163. );
  164. $leaf->setDoc(
  165. [
  166. 'manual_MySQL_Database_Administration',
  167. 'server-system-variables',
  168. 'sysvar_foreign_key_checks',
  169. ]
  170. );
  171. $generalOptions->addProperty($leaf);
  172. // export views as tables
  173. $leaf = new BoolPropertyItem(
  174. 'views_as_tables',
  175. __('Export views as tables')
  176. );
  177. $generalOptions->addProperty($leaf);
  178. // export metadata
  179. $leaf = new BoolPropertyItem(
  180. 'metadata',
  181. __('Export metadata')
  182. );
  183. $generalOptions->addProperty($leaf);
  184. // compatibility maximization
  185. $compats = $dbi->getCompatibilities();
  186. if (count($compats) > 0) {
  187. $values = [];
  188. foreach ($compats as $val) {
  189. $values[$val] = $val;
  190. }
  191. $leaf = new SelectPropertyItem(
  192. 'compatibility',
  193. __(
  194. 'Database system or older MySQL server to maximize output compatibility with:'
  195. )
  196. );
  197. $leaf->setValues($values);
  198. $leaf->setDoc(
  199. [
  200. 'manual_MySQL_Database_Administration',
  201. 'Server_SQL_mode',
  202. ]
  203. );
  204. $generalOptions->addProperty($leaf);
  205. unset($values);
  206. }
  207. // what to dump (structure/data/both)
  208. $subgroup = new OptionsPropertySubgroup(
  209. 'dump_table',
  210. __('Dump table')
  211. );
  212. $leaf = new RadioPropertyItem('structure_or_data');
  213. $leaf->setValues(
  214. [
  215. 'structure' => __('structure'),
  216. 'data' => __('data'),
  217. 'structure_and_data' => __('structure and data'),
  218. ]
  219. );
  220. $subgroup->setSubgroupHeader($leaf);
  221. $generalOptions->addProperty($subgroup);
  222. // add the main group to the root group
  223. $exportSpecificOptions->addProperty($generalOptions);
  224. // structure options main group
  225. if (! $hideStructure) {
  226. $structureOptions = new OptionsPropertyMainGroup(
  227. 'structure',
  228. __('Object creation options')
  229. );
  230. $structureOptions->setForce('data');
  231. // begin SQL Statements
  232. $subgroup = new OptionsPropertySubgroup();
  233. $leaf = new MessageOnlyPropertyItem(
  234. 'add_statements',
  235. __('Add statements:')
  236. );
  237. $subgroup->setSubgroupHeader($leaf);
  238. // server export options
  239. if ($plugin_param['export_type'] === 'server') {
  240. $leaf = new BoolPropertyItem(
  241. 'drop_database',
  242. sprintf(__('Add %s statement'), '<code>DROP DATABASE IF EXISTS</code>')
  243. );
  244. $subgroup->addProperty($leaf);
  245. }
  246. if ($plugin_param['export_type'] === 'database') {
  247. $createClause = '<code>CREATE DATABASE / USE</code>';
  248. $leaf = new BoolPropertyItem(
  249. 'create_database',
  250. sprintf(__('Add %s statement'), $createClause)
  251. );
  252. $subgroup->addProperty($leaf);
  253. }
  254. if ($plugin_param['export_type'] === 'table') {
  255. $dropClause = $dbi->getTable($GLOBALS['db'], $GLOBALS['table'])->isView()
  256. ? '<code>DROP VIEW</code>'
  257. : '<code>DROP TABLE</code>';
  258. } else {
  259. $dropClause = '<code>DROP TABLE / VIEW / PROCEDURE / FUNCTION / EVENT</code>';
  260. }
  261. $dropClause .= '<code> / TRIGGER</code>';
  262. $leaf = new BoolPropertyItem(
  263. 'drop_table',
  264. sprintf(__('Add %s statement'), $dropClause)
  265. );
  266. $subgroup->addProperty($leaf);
  267. $subgroupCreateTable = new OptionsPropertySubgroup();
  268. // Add table structure option
  269. $leaf = new BoolPropertyItem(
  270. 'create_table',
  271. sprintf(__('Add %s statement'), '<code>CREATE TABLE</code>')
  272. );
  273. $subgroupCreateTable->setSubgroupHeader($leaf);
  274. $leaf = new BoolPropertyItem(
  275. 'if_not_exists',
  276. '<code>IF NOT EXISTS</code> ' . __(
  277. '(less efficient as indexes will be generated during table creation)'
  278. )
  279. );
  280. $subgroupCreateTable->addProperty($leaf);
  281. $leaf = new BoolPropertyItem(
  282. 'auto_increment',
  283. sprintf(__('%s value'), '<code>AUTO_INCREMENT</code>')
  284. );
  285. $subgroupCreateTable->addProperty($leaf);
  286. $subgroup->addProperty($subgroupCreateTable);
  287. // Add view option
  288. $subgroupCreateView = new OptionsPropertySubgroup();
  289. $leaf = new BoolPropertyItem(
  290. 'create_view',
  291. sprintf(__('Add %s statement'), '<code>CREATE VIEW</code>')
  292. );
  293. $subgroupCreateView->setSubgroupHeader($leaf);
  294. $leaf = new BoolPropertyItem(
  295. 'simple_view_export',
  296. /* l10n: Allow simplifying exported view syntax to only "CREATE VIEW" */
  297. __('Use simple view export')
  298. );
  299. $subgroupCreateView->addProperty($leaf);
  300. $leaf = new BoolPropertyItem(
  301. 'view_current_user',
  302. __('Exclude definition of current user')
  303. );
  304. $subgroupCreateView->addProperty($leaf);
  305. $leaf = new BoolPropertyItem(
  306. 'or_replace_view',
  307. sprintf(__('%s view'), '<code>OR REPLACE</code>')
  308. );
  309. $subgroupCreateView->addProperty($leaf);
  310. $subgroup->addProperty($subgroupCreateView);
  311. $leaf = new BoolPropertyItem(
  312. 'procedure_function',
  313. sprintf(
  314. __('Add %s statement'),
  315. '<code>CREATE PROCEDURE / FUNCTION / EVENT</code>'
  316. )
  317. );
  318. $subgroup->addProperty($leaf);
  319. // Add triggers option
  320. $leaf = new BoolPropertyItem(
  321. 'create_trigger',
  322. sprintf(__('Add %s statement'), '<code>CREATE TRIGGER</code>')
  323. );
  324. $subgroup->addProperty($leaf);
  325. $structureOptions->addProperty($subgroup);
  326. $leaf = new BoolPropertyItem(
  327. 'backquotes',
  328. __(
  329. 'Enclose table and column names with backquotes '
  330. . '<i>(Protects column and table names formed with'
  331. . ' special characters or keywords)</i>'
  332. )
  333. );
  334. $structureOptions->addProperty($leaf);
  335. // add the main group to the root group
  336. $exportSpecificOptions->addProperty($structureOptions);
  337. }
  338. // begin Data options
  339. $dataOptions = new OptionsPropertyMainGroup(
  340. 'data',
  341. __('Data creation options')
  342. );
  343. $dataOptions->setForce('structure');
  344. $leaf = new BoolPropertyItem(
  345. 'truncate',
  346. __('Truncate table before insert')
  347. );
  348. $dataOptions->addProperty($leaf);
  349. // begin SQL Statements
  350. $subgroup = new OptionsPropertySubgroup();
  351. $leaf = new MessageOnlyPropertyItem(
  352. __('Instead of <code>INSERT</code> statements, use:')
  353. );
  354. $subgroup->setSubgroupHeader($leaf);
  355. $leaf = new BoolPropertyItem(
  356. 'delayed',
  357. __('<code>INSERT DELAYED</code> statements')
  358. );
  359. $leaf->setDoc(
  360. [
  361. 'manual_MySQL_Database_Administration',
  362. 'insert_delayed',
  363. ]
  364. );
  365. $subgroup->addProperty($leaf);
  366. $leaf = new BoolPropertyItem(
  367. 'ignore',
  368. __('<code>INSERT IGNORE</code> statements')
  369. );
  370. $leaf->setDoc(
  371. [
  372. 'manual_MySQL_Database_Administration',
  373. 'insert',
  374. ]
  375. );
  376. $subgroup->addProperty($leaf);
  377. $dataOptions->addProperty($subgroup);
  378. // Function to use when dumping dat
  379. $leaf = new SelectPropertyItem(
  380. 'type',
  381. __('Function to use when dumping data:')
  382. );
  383. $leaf->setValues(
  384. [
  385. 'INSERT' => 'INSERT',
  386. 'UPDATE' => 'UPDATE',
  387. 'REPLACE' => 'REPLACE',
  388. ]
  389. );
  390. $dataOptions->addProperty($leaf);
  391. /* Syntax to use when inserting data */
  392. $subgroup = new OptionsPropertySubgroup();
  393. $leaf = new MessageOnlyPropertyItem(
  394. null,
  395. __('Syntax to use when inserting data:')
  396. );
  397. $subgroup->setSubgroupHeader($leaf);
  398. $leaf = new RadioPropertyItem(
  399. 'insert_syntax',
  400. __('<code>INSERT IGNORE</code> statements')
  401. );
  402. $leaf->setValues(
  403. [
  404. 'complete' => __(
  405. 'include column names in every <code>INSERT</code> statement'
  406. . ' <br> &nbsp; &nbsp; &nbsp; Example: <code>INSERT INTO'
  407. . ' tbl_name (col_A,col_B,col_C) VALUES (1,2,3)</code>'
  408. ),
  409. 'extended' => __(
  410. 'insert multiple rows in every <code>INSERT</code> statement'
  411. . '<br> &nbsp; &nbsp; &nbsp; Example: <code>INSERT INTO'
  412. . ' tbl_name VALUES (1,2,3), (4,5,6), (7,8,9)</code>'
  413. ),
  414. 'both' => __(
  415. 'both of the above<br> &nbsp; &nbsp; &nbsp; Example:'
  416. . ' <code>INSERT INTO tbl_name (col_A,col_B,col_C) VALUES'
  417. . ' (1,2,3), (4,5,6), (7,8,9)</code>'
  418. ),
  419. 'none' => __(
  420. 'neither of the above<br> &nbsp; &nbsp; &nbsp; Example:'
  421. . ' <code>INSERT INTO tbl_name VALUES (1,2,3)</code>'
  422. ),
  423. ]
  424. );
  425. $subgroup->addProperty($leaf);
  426. $dataOptions->addProperty($subgroup);
  427. // Max length of query
  428. $leaf = new NumberPropertyItem(
  429. 'max_query_size',
  430. __('Maximal length of created query')
  431. );
  432. $dataOptions->addProperty($leaf);
  433. // Dump binary columns in hexadecimal
  434. $leaf = new BoolPropertyItem(
  435. 'hex_for_binary',
  436. __(
  437. 'Dump binary columns in hexadecimal notation <i>(for example, "abc" becomes 0x616263)</i>'
  438. )
  439. );
  440. $dataOptions->addProperty($leaf);
  441. // Dump time in UTC
  442. $leaf = new BoolPropertyItem(
  443. 'utc_time',
  444. __(
  445. 'Dump TIMESTAMP columns in UTC <i>(enables TIMESTAMP columns'
  446. . ' to be dumped and reloaded between servers in different'
  447. . ' time zones)</i>'
  448. )
  449. );
  450. $dataOptions->addProperty($leaf);
  451. // add the main group to the root group
  452. $exportSpecificOptions->addProperty($dataOptions);
  453. // set the options for the export plugin property item
  454. $exportPluginProperties->setOptions($exportSpecificOptions);
  455. return $exportPluginProperties;
  456. }
  457. /**
  458. * Generates SQL for routines export
  459. *
  460. * @param string $db Database
  461. * @param array $aliases Aliases of db/table/columns
  462. * @param string $type Type of exported routine
  463. * @param string $name Verbose name of exported routine
  464. * @param array $routines List of routines to export
  465. * @param string $delimiter Delimiter to use in SQL
  466. *
  467. * @return string SQL query
  468. */
  469. protected function exportRoutineSQL(
  470. $db,
  471. array $aliases,
  472. $type,
  473. $name,
  474. array $routines,
  475. $delimiter
  476. ) {
  477. global $crlf, $cfg, $dbi;
  478. $text = $this->exportComment()
  479. . $this->exportComment($name)
  480. . $this->exportComment();
  481. $usedAlias = false;
  482. $procQuery = '';
  483. foreach ($routines as $routine) {
  484. if (! empty($GLOBALS['sql_drop_table'])) {
  485. $procQuery .= 'DROP ' . $type . ' IF EXISTS '
  486. . Util::backquote($routine)
  487. . $delimiter . $crlf;
  488. }
  489. $createQuery = $this->replaceWithAliases(
  490. $delimiter,
  491. $dbi->getDefinition($db, $type, $routine),
  492. $aliases,
  493. $db,
  494. '',
  495. $flag
  496. );
  497. if (! empty($createQuery) && $cfg['Export']['remove_definer_from_definitions']) {
  498. // Remove definer clause from routine definitions
  499. $parser = new Parser('DELIMITER ' . $delimiter . $crlf . $createQuery);
  500. $statement = $parser->statements[0];
  501. $statement->options->remove('DEFINER');
  502. $createQuery = $statement->build();
  503. }
  504. // One warning per database
  505. if ($flag) {
  506. $usedAlias = true;
  507. }
  508. $procQuery .= $createQuery . $delimiter . $crlf . $crlf;
  509. }
  510. if ($usedAlias) {
  511. $text .= $this->exportComment(
  512. __('It appears your database uses routines;')
  513. )
  514. . $this->exportComment(
  515. __('alias export may not work reliably in all cases.')
  516. )
  517. . $this->exportComment();
  518. }
  519. $text .= $procQuery;
  520. return $text;
  521. }
  522. /**
  523. * Exports routines (procedures and functions)
  524. *
  525. * @param string $db Database
  526. * @param array $aliases Aliases of db/table/columns
  527. */
  528. public function exportRoutines($db, array $aliases = []): bool
  529. {
  530. global $crlf, $dbi;
  531. $dbAlias = $db;
  532. $this->initAlias($aliases, $dbAlias);
  533. $text = '';
  534. $delimiter = '$$';
  535. $procedureNames = $dbi->getProceduresOrFunctions($db, 'PROCEDURE');
  536. $functionNames = $dbi->getProceduresOrFunctions($db, 'FUNCTION');
  537. if ($procedureNames || $functionNames) {
  538. $text .= $crlf
  539. . 'DELIMITER ' . $delimiter . $crlf;
  540. if ($procedureNames) {
  541. $text .= $this->exportRoutineSQL(
  542. $db,
  543. $aliases,
  544. 'PROCEDURE',
  545. __('Procedures'),
  546. $procedureNames,
  547. $delimiter
  548. );
  549. }
  550. if ($functionNames) {
  551. $text .= $this->exportRoutineSQL(
  552. $db,
  553. $aliases,
  554. 'FUNCTION',
  555. __('Functions'),
  556. $functionNames,
  557. $delimiter
  558. );
  559. }
  560. $text .= 'DELIMITER ;' . $crlf;
  561. }
  562. if (! empty($text)) {
  563. return $this->export->outputHandler($text);
  564. }
  565. return false;
  566. }
  567. /**
  568. * Possibly outputs comment
  569. *
  570. * @param string $text Text of comment
  571. *
  572. * @return string The formatted comment
  573. */
  574. private function exportComment($text = '')
  575. {
  576. if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments']) {
  577. // see https://dev.mysql.com/doc/refman/5.0/en/ansi-diff-comments.html
  578. if (empty($text)) {
  579. return '--' . $GLOBALS['crlf'];
  580. }
  581. $lines = preg_split("/\\r\\n|\\r|\\n/", $text);
  582. if ($lines === false) {
  583. return '--' . $GLOBALS['crlf'];
  584. }
  585. $result = [];
  586. foreach ($lines as $line) {
  587. $result[] = '-- ' . $line . $GLOBALS['crlf'];
  588. }
  589. return implode('', $result);
  590. }
  591. return '';
  592. }
  593. /**
  594. * Possibly outputs CRLF
  595. *
  596. * @return string crlf or nothing
  597. */
  598. private function possibleCRLF()
  599. {
  600. if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments']) {
  601. return $GLOBALS['crlf'];
  602. }
  603. return '';
  604. }
  605. /**
  606. * Outputs export footer
  607. */
  608. public function exportFooter(): bool
  609. {
  610. global $crlf, $dbi;
  611. $foot = '';
  612. if (isset($GLOBALS['sql_disable_fk'])) {
  613. $foot .= 'SET FOREIGN_KEY_CHECKS=1;' . $crlf;
  614. }
  615. if (isset($GLOBALS['sql_use_transaction'])) {
  616. $foot .= 'COMMIT;' . $crlf;
  617. }
  618. // restore connection settings
  619. if ($this->sentCharset) {
  620. $foot .= $crlf
  621. . '/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;'
  622. . $crlf
  623. . '/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;'
  624. . $crlf
  625. . '/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;'
  626. . $crlf;
  627. $this->sentCharset = false;
  628. }
  629. /* Restore timezone */
  630. if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) {
  631. $dbi->query('SET time_zone = "' . $GLOBALS['old_tz'] . '"');
  632. }
  633. return $this->export->outputHandler($foot);
  634. }
  635. /**
  636. * Outputs export header. It is the first method to be called, so all
  637. * the required variables are initialized here.
  638. */
  639. public function exportHeader(): bool
  640. {
  641. global $crlf, $cfg, $dbi;
  642. if (isset($GLOBALS['sql_compatibility'])) {
  643. $tmpCompat = $GLOBALS['sql_compatibility'];
  644. if ($tmpCompat === 'NONE') {
  645. $tmpCompat = '';
  646. }
  647. $dbi->tryQuery('SET SQL_MODE="' . $tmpCompat . '"');
  648. unset($tmpCompat);
  649. }
  650. $head = $this->exportComment('phpMyAdmin SQL Dump')
  651. . $this->exportComment('version ' . Version::VERSION)
  652. . $this->exportComment('https://www.phpmyadmin.net/')
  653. . $this->exportComment();
  654. $hostString = __('Host:') . ' ' . $cfg['Server']['host'];
  655. if (! empty($cfg['Server']['port'])) {
  656. $hostString .= ':' . $cfg['Server']['port'];
  657. }
  658. $head .= $this->exportComment($hostString);
  659. $head .= $this->exportComment(
  660. __('Generation Time:') . ' '
  661. . Util::localisedDate()
  662. )
  663. . $this->exportComment(
  664. __('Server version:') . ' ' . $dbi->getVersionString()
  665. )
  666. . $this->exportComment(__('PHP Version:') . ' ' . PHP_VERSION)
  667. . $this->possibleCRLF();
  668. if (isset($GLOBALS['sql_header_comment']) && ! empty($GLOBALS['sql_header_comment'])) {
  669. // '\n' is not a newline (like "\n" would be), it's the characters
  670. // backslash and n, as explained on the export interface
  671. $lines = explode('\n', $GLOBALS['sql_header_comment']);
  672. $head .= $this->exportComment();
  673. foreach ($lines as $oneLine) {
  674. $head .= $this->exportComment($oneLine);
  675. }
  676. $head .= $this->exportComment();
  677. }
  678. if (isset($GLOBALS['sql_disable_fk'])) {
  679. $head .= 'SET FOREIGN_KEY_CHECKS=0;' . $crlf;
  680. }
  681. // We want exported AUTO_INCREMENT columns to have still same value,
  682. // do this only for recent MySQL exports
  683. if (! isset($GLOBALS['sql_compatibility']) || $GLOBALS['sql_compatibility'] === 'NONE') {
  684. $head .= 'SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";' . $crlf;
  685. }
  686. if (isset($GLOBALS['sql_use_transaction'])) {
  687. $head .= 'START TRANSACTION;' . $crlf;
  688. }
  689. /* Change timezone if we should export timestamps in UTC */
  690. if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) {
  691. $head .= 'SET time_zone = "+00:00";' . $crlf;
  692. $GLOBALS['old_tz'] = $dbi
  693. ->fetchValue('SELECT @@session.time_zone');
  694. $dbi->query('SET time_zone = "+00:00"');
  695. }
  696. $head .= $this->possibleCRLF();
  697. if (! empty($GLOBALS['asfile'])) {
  698. // we are saving as file, therefore we provide charset information
  699. // so that a utility like the mysql client can interpret
  700. // the file correctly
  701. if (isset($GLOBALS['charset'], Charsets::$mysqlCharsetMap[$GLOBALS['charset']])) {
  702. // we got a charset from the export dialog
  703. $setNames = Charsets::$mysqlCharsetMap[$GLOBALS['charset']];
  704. } else {
  705. // by default we use the connection charset
  706. $setNames = Charsets::$mysqlCharsetMap['utf-8'];
  707. }
  708. if ($setNames === 'utf8' && $dbi->getVersion() > 50503) {
  709. $setNames = 'utf8mb4';
  710. }
  711. $head .= $crlf
  712. . '/*!40101 SET @OLD_CHARACTER_SET_CLIENT='
  713. . '@@CHARACTER_SET_CLIENT */;' . $crlf
  714. . '/*!40101 SET @OLD_CHARACTER_SET_RESULTS='
  715. . '@@CHARACTER_SET_RESULTS */;' . $crlf
  716. . '/*!40101 SET @OLD_COLLATION_CONNECTION='
  717. . '@@COLLATION_CONNECTION */;' . $crlf
  718. . '/*!40101 SET NAMES ' . $setNames . ' */;' . $crlf . $crlf;
  719. $this->sentCharset = true;
  720. }
  721. return $this->export->outputHandler($head);
  722. }
  723. /**
  724. * Outputs CREATE DATABASE statement
  725. *
  726. * @param string $db Database name
  727. * @param string $exportType 'server', 'database', 'table'
  728. * @param string $dbAlias Aliases of db
  729. */
  730. public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
  731. {
  732. global $crlf, $dbi;
  733. if (empty($dbAlias)) {
  734. $dbAlias = $db;
  735. }
  736. if (isset($GLOBALS['sql_compatibility'])) {
  737. $compat = $GLOBALS['sql_compatibility'];
  738. } else {
  739. $compat = 'NONE';
  740. }
  741. $exportStructure = ! isset($GLOBALS['sql_structure_or_data'])
  742. || in_array($GLOBALS['sql_structure_or_data'], ['structure', 'structure_and_data'], true);
  743. if ($exportStructure && isset($GLOBALS['sql_drop_database'])) {
  744. if (
  745. ! $this->export->outputHandler(
  746. 'DROP DATABASE IF EXISTS '
  747. . Util::backquoteCompat(
  748. $dbAlias,
  749. $compat,
  750. isset($GLOBALS['sql_backquotes'])
  751. )
  752. . ';' . $crlf
  753. )
  754. ) {
  755. return false;
  756. }
  757. }
  758. if ($exportType === 'database' && ! isset($GLOBALS['sql_create_database'])) {
  759. return true;
  760. }
  761. $createQuery = 'CREATE DATABASE IF NOT EXISTS '
  762. . Util::backquoteCompat($dbAlias, $compat, isset($GLOBALS['sql_backquotes']));
  763. $collation = $dbi->getDbCollation($db);
  764. if (mb_strpos($collation, '_')) {
  765. $createQuery .= ' DEFAULT CHARACTER SET '
  766. . mb_substr(
  767. $collation,
  768. 0,
  769. (int) mb_strpos($collation, '_')
  770. )
  771. . ' COLLATE ' . $collation;
  772. } else {
  773. $createQuery .= ' DEFAULT CHARACTER SET ' . $collation;
  774. }
  775. $createQuery .= ';' . $crlf;
  776. if (! $this->export->outputHandler($createQuery)) {
  777. return false;
  778. }
  779. return $this->exportUseStatement($dbAlias, $compat);
  780. }
  781. /**
  782. * Outputs USE statement
  783. *
  784. * @param string $db db to use
  785. * @param string $compat sql compatibility
  786. */
  787. private function exportUseStatement($db, $compat): bool
  788. {
  789. global $crlf;
  790. if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] === 'NONE') {
  791. $result = $this->export->outputHandler(
  792. 'USE '
  793. . Util::backquoteCompat(
  794. $db,
  795. $compat,
  796. isset($GLOBALS['sql_backquotes'])
  797. )
  798. . ';' . $crlf
  799. );
  800. } else {
  801. $result = $this->export->outputHandler('USE ' . $db . ';' . $crlf);
  802. }
  803. return $result;
  804. }
  805. /**
  806. * Outputs database header
  807. *
  808. * @param string $db Database name
  809. * @param string $dbAlias Alias of db
  810. */
  811. public function exportDBHeader($db, $dbAlias = ''): bool
  812. {
  813. if (empty($dbAlias)) {
  814. $dbAlias = $db;
  815. }
  816. if (isset($GLOBALS['sql_compatibility'])) {
  817. $compat = $GLOBALS['sql_compatibility'];
  818. } else {
  819. $compat = 'NONE';
  820. }
  821. $head = $this->exportComment()
  822. . $this->exportComment(
  823. __('Database:') . ' '
  824. . Util::backquoteCompat(
  825. $dbAlias,
  826. $compat,
  827. isset($GLOBALS['sql_backquotes'])
  828. )
  829. )
  830. . $this->exportComment();
  831. return $this->export->outputHandler($head);
  832. }
  833. /**
  834. * Outputs database footer
  835. *
  836. * @param string $db Database name
  837. */
  838. public function exportDBFooter($db): bool
  839. {
  840. global $crlf;
  841. $result = true;
  842. //add indexes to the sql dump file
  843. if (isset($GLOBALS['sql_indexes'])) {
  844. $result = $this->export->outputHandler($GLOBALS['sql_indexes']);
  845. unset($GLOBALS['sql_indexes']);
  846. }
  847. //add auto increments to the sql dump file
  848. if (isset($GLOBALS['sql_auto_increments'])) {
  849. $result = $this->export->outputHandler($GLOBALS['sql_auto_increments']);
  850. unset($GLOBALS['sql_auto_increments']);
  851. }
  852. //add views to the sql dump file
  853. if ($this->sqlViews !== '') {
  854. $result = $this->export->outputHandler($this->sqlViews);
  855. $this->sqlViews = '';
  856. }
  857. //add constraints to the sql dump file
  858. if (isset($GLOBALS['sql_constraints'])) {
  859. $result = $this->export->outputHandler($GLOBALS['sql_constraints']);
  860. unset($GLOBALS['sql_constraints']);
  861. }
  862. return $result;
  863. }
  864. /**
  865. * Exports events
  866. *
  867. * @param string $db Database
  868. */
  869. public function exportEvents($db): bool
  870. {
  871. global $crlf, $cfg, $dbi;
  872. $text = '';
  873. $delimiter = '$$';
  874. $eventNames = $dbi->fetchResult(
  875. 'SELECT EVENT_NAME FROM information_schema.EVENTS WHERE'
  876. . " EVENT_SCHEMA= '" . $dbi->escapeString($db)
  877. . "';"
  878. );
  879. if ($eventNames) {
  880. $text .= $crlf
  881. . 'DELIMITER ' . $delimiter . $crlf;
  882. $text .= $this->exportComment()
  883. . $this->exportComment(__('Events'))
  884. . $this->exportComment();
  885. foreach ($eventNames as $eventName) {
  886. if (! empty($GLOBALS['sql_drop_table'])) {
  887. $text .= 'DROP EVENT IF EXISTS '
  888. . Util::backquote($eventName)
  889. . $delimiter . $crlf;
  890. }
  891. $eventDef = $dbi->getDefinition($db, 'EVENT', $eventName);
  892. if (! empty($eventDef) && $cfg['Export']['remove_definer_from_definitions']) {
  893. // remove definer clause from the event definition
  894. $parser = new Parser('DELIMITER ' . $delimiter . $crlf . $eventDef);
  895. $statement = $parser->statements[0];
  896. $statement->options->remove('DEFINER');
  897. $eventDef = $statement->build();
  898. }
  899. $text .= $eventDef . $delimiter . $crlf . $crlf;
  900. }
  901. $text .= 'DELIMITER ;' . $crlf;
  902. }
  903. if (! empty($text)) {
  904. return $this->export->outputHandler($text);
  905. }
  906. return false;
  907. }
  908. /**
  909. * Exports metadata from Configuration Storage
  910. *
  911. * @param string $db database being exported
  912. * @param string|array $tables table(s) being exported
  913. * @param array $metadataTypes types of metadata to export
  914. */
  915. public function exportMetadata(
  916. $db,
  917. $tables,
  918. array $metadataTypes
  919. ): bool {
  920. $relationParameters = $this->relation->getRelationParameters();
  921. if ($relationParameters->db === null) {
  922. return true;
  923. }
  924. $comment = $this->possibleCRLF()
  925. . $this->possibleCRLF()
  926. . $this->exportComment()
  927. . $this->exportComment(__('Metadata'))
  928. . $this->exportComment();
  929. if (! $this->export->outputHandler($comment)) {
  930. return false;
  931. }
  932. if (! $this->exportUseStatement((string) $relationParameters->db, $GLOBALS['sql_compatibility'])) {
  933. return false;
  934. }
  935. $r = 1;
  936. if (is_array($tables)) {
  937. // export metadata for each table
  938. foreach ($tables as $table) {
  939. $r &= (int) $this->exportConfigurationMetadata($db, $table, $metadataTypes);
  940. }
  941. // export metadata for the database
  942. $r &= (int) $this->exportConfigurationMetadata($db, null, $metadataTypes);
  943. } else {
  944. // export metadata for single table
  945. $r &= (int) $this->exportConfigurationMetadata($db, $tables, $metadataTypes);
  946. }
  947. return (bool) $r;
  948. }
  949. /**
  950. * Exports metadata from Configuration Storage
  951. *
  952. * @param string $db database being exported
  953. * @param string|null $table table being exported
  954. * @param array $metadataTypes types of metadata to export
  955. */
  956. private function exportConfigurationMetadata(
  957. $db,
  958. $table,
  959. array $metadataTypes
  960. ): bool {
  961. global $dbi;
  962. $relationParameters = $this->relation->getRelationParameters();
  963. $relationParams = $relationParameters->toArray();
  964. if (isset($table)) {
  965. $types = [
  966. 'column_info' => 'db_name',
  967. 'table_uiprefs' => 'db_name',
  968. 'tracking' => 'db_name',
  969. ];
  970. } else {
  971. $types = [
  972. 'bookmark' => 'dbase',
  973. 'relation' => 'master_db',
  974. 'pdf_pages' => 'db_name',
  975. 'savedsearches' => 'db_name',
  976. 'central_columns' => 'db_name',
  977. ];
  978. }
  979. $aliases = [];
  980. $comment = $this->possibleCRLF()
  981. . $this->exportComment();
  982. if (isset($table)) {
  983. $comment .= $this->exportComment(
  984. sprintf(
  985. __('Metadata for table %s'),
  986. $table
  987. )
  988. );
  989. } else {
  990. $comment .= $this->exportComment(
  991. sprintf(
  992. __('Metadata for database %s'),
  993. $db
  994. )
  995. );
  996. }
  997. $comment .= $this->exportComment();
  998. if (! $this->export->outputHandler($comment)) {
  999. return false;
  1000. }
  1001. foreach ($types as $type => $dbNameColumn) {
  1002. if (! in_array($type, $metadataTypes) || ! isset($relationParams[$type])) {
  1003. continue;
  1004. }
  1005. // special case, designer pages and their coordinates
  1006. if ($type === 'pdf_pages') {
  1007. if ($relationParameters->pdfFeature === null) {
  1008. continue;
  1009. }
  1010. $sqlQuery = 'SELECT `page_nr`, `page_descr` FROM '
  1011. . Util::backquote($relationParameters->pdfFeature->database)
  1012. . '.' . Util::backquote($relationParameters->pdfFeature->pdfPages)
  1013. . ' WHERE `db_name` = \'' . $dbi->escapeString($db) . "'";
  1014. $result = $dbi->fetchResult($sqlQuery, 'page_nr', 'page_descr');
  1015. foreach (array_keys($result) as $page) {
  1016. // insert row for pdf_page
  1017. $sqlQueryRow = 'SELECT `db_name`, `page_descr` FROM '
  1018. . Util::backquote($relationParameters->pdfFeature->database)
  1019. . '.' . Util::backquote($relationParameters->pdfFeature->pdfPages)
  1020. . ' WHERE `db_name` = \'' . $dbi->escapeString($db) . "'"
  1021. . " AND `page_nr` = '" . intval($page) . "'";
  1022. if (
  1023. ! $this->exportData(
  1024. $relationParameters->pdfFeature->database->getName(),
  1025. $relationParameters->pdfFeature->pdfPages->getName(),
  1026. $GLOBALS['crlf'],
  1027. '',
  1028. $sqlQueryRow,
  1029. $aliases
  1030. )
  1031. ) {
  1032. return false;
  1033. }
  1034. $lastPage = $GLOBALS['crlf']
  1035. . 'SET @LAST_PAGE = LAST_INSERT_ID();'
  1036. . $GLOBALS['crlf'];
  1037. if (! $this->export->outputHandler($lastPage)) {
  1038. return false;
  1039. }
  1040. $sqlQueryCoords = 'SELECT `db_name`, `table_name`, '
  1041. . "'@LAST_PAGE' AS `pdf_page_number`, `x`, `y` FROM "
  1042. . Util::backquote($relationParameters->pdfFeature->database)
  1043. . '.' . Util::backquote($relationParameters->pdfFeature->tableCoords)
  1044. . " WHERE `pdf_page_number` = '" . $page . "'";
  1045. $GLOBALS['exporting_metadata'] = true;
  1046. if (
  1047. ! $this->exportData(
  1048. $relationParameters->pdfFeature->database->getName(),
  1049. $relationParameters->pdfFeature->tableCoords->getName(),
  1050. $GLOBALS['crlf'],
  1051. '',
  1052. $sqlQueryCoords,
  1053. $aliases
  1054. )
  1055. ) {
  1056. $GLOBALS['exporting_metadata'] = false;
  1057. return false;
  1058. }
  1059. $GLOBALS['exporting_metadata'] = false;
  1060. }
  1061. continue;
  1062. }
  1063. // remove auto_incrementing id field for some tables
  1064. if ($type === 'bookmark') {
  1065. $sqlQuery = 'SELECT `dbase`, `user`, `label`, `query` FROM ';
  1066. } elseif ($type === 'column_info') {
  1067. $sqlQuery = 'SELECT `db_name`, `table_name`, `column_name`,'
  1068. . ' `comment`, `mimetype`, `transformation`,'
  1069. . ' `transformation_options`, `input_transformation`,'
  1070. . ' `input_transformation_options` FROM';
  1071. } elseif ($type === 'savedsearches') {
  1072. $sqlQuery = 'SELECT `username`, `db_name`, `search_name`, `search_data` FROM';
  1073. } else {
  1074. $sqlQuery = 'SELECT * FROM ';
  1075. }
  1076. $sqlQuery .= Util::backquote($relationParameters->db)
  1077. . '.' . Util::backquote((string) $relationParams[$type])
  1078. . ' WHERE ' . Util::backquote($dbNameColumn)
  1079. . " = '" . $dbi->escapeString($db) . "'";
  1080. if (isset($table)) {
  1081. $sqlQuery .= " AND `table_name` = '"
  1082. . $dbi->escapeString($table) . "'";
  1083. }
  1084. if (
  1085. ! $this->exportData(
  1086. (string) $relationParameters->db,
  1087. (string) $relationParams[$type],
  1088. $GLOBALS['crlf'],
  1089. '',
  1090. $sqlQuery,
  1091. $aliases
  1092. )
  1093. ) {
  1094. return false;
  1095. }
  1096. }
  1097. return true;
  1098. }
  1099. /**
  1100. * Returns a stand-in CREATE definition to resolve view dependencies
  1101. *
  1102. * @param string $db the database name
  1103. * @param string $view the view name
  1104. * @param string $crlf the end of line sequence
  1105. * @param array $aliases Aliases of db/table/columns
  1106. *
  1107. * @return string resulting definition
  1108. */
  1109. public function getTableDefStandIn($db, $view, $crlf, $aliases = [])
  1110. {
  1111. global $dbi;
  1112. $dbAlias = $db;
  1113. $viewAlias = $view;
  1114. $this->initAlias($aliases, $dbAlias, $viewAlias);
  1115. $createQuery = '';
  1116. if (! empty($GLOBALS['sql_drop_table'])) {
  1117. $createQuery .= 'DROP VIEW IF EXISTS '
  1118. . Util::backquote($viewAlias)
  1119. . ';' . $crlf;
  1120. }
  1121. $createQuery .= 'CREATE TABLE ';
  1122. if (isset($GLOBALS['sql_if_not_exists']) && $GLOBALS['sql_if_not_exists']) {
  1123. $createQuery .= 'IF NOT EXISTS ';
  1124. }
  1125. $createQuery .= Util::backquote($viewAlias) . ' (' . $crlf;
  1126. $tmp = [];
  1127. $columns = $dbi->getColumnsFull($db, $view);
  1128. foreach ($columns as $columnName => $definition) {
  1129. $colAlias = $columnName;
  1130. if (! empty($aliases[$db]['tables'][$view]['columns'][$colAlias])) {
  1131. $colAlias = $aliases[$db]['tables'][$view]['columns'][$colAlias];
  1132. }
  1133. $tmp[] = Util::backquote($colAlias) . ' ' .
  1134. $definition['Type'] . $crlf;
  1135. }
  1136. return $createQuery . implode(',', $tmp) . ');' . $crlf;
  1137. }
  1138. /**
  1139. * Returns CREATE definition that matches $view's structure
  1140. *
  1141. * @param string $db the database name
  1142. * @param string $view the view name
  1143. * @param string $crlf the end of line sequence
  1144. * @param bool $addSemicolon whether to add semicolon and end-of-line at
  1145. * the end
  1146. * @param array $aliases Aliases of db/table/columns
  1147. *
  1148. * @return string resulting schema
  1149. */
  1150. private function getTableDefForView(
  1151. $db,
  1152. $view,
  1153. $crlf,
  1154. $addSemicolon = true,
  1155. array $aliases = []
  1156. ) {
  1157. global $dbi;
  1158. $dbAlias = $db;
  1159. $viewAlias = $view;
  1160. $this->initAlias($aliases, $dbAlias, $viewAlias);
  1161. $createQuery = 'CREATE TABLE';
  1162. if (isset($GLOBALS['sql_if_not_exists'])) {
  1163. $createQuery .= ' IF NOT EXISTS ';
  1164. }
  1165. $createQuery .= Util::backquote($viewAlias) . '(' . $crlf;
  1166. $columns = $dbi->getColumns($db, $view, true);
  1167. $firstCol = true;
  1168. foreach ($columns as $column) {
  1169. $colAlias = $column['Field'];
  1170. if (! empty($aliases[$db]['tables'][$view]['columns'][$colAlias])) {
  1171. $colAlias = $aliases[$db]['tables'][$view]['columns'][$colAlias];
  1172. }
  1173. $extractedColumnspec = Util::extractColumnSpec($column['Type']);
  1174. if (! $firstCol) {
  1175. $createQuery .= ',' . $crlf;
  1176. }
  1177. $createQuery .= ' ' . Util::backquote($colAlias);
  1178. $createQuery .= ' ' . $column['Type'];
  1179. if ($extractedColumnspec['can_contain_collation'] && ! empty($column['Collation'])) {
  1180. $createQuery .= ' COLLATE ' . $column['Collation'];
  1181. }
  1182. if ($column['Null'] === 'NO') {
  1183. $createQuery .= ' NOT NULL';
  1184. }
  1185. if (isset($column['Default'])) {
  1186. $createQuery .= " DEFAULT '"
  1187. . $dbi->escapeString($column['Default']) . "'";
  1188. } else {
  1189. if ($column['Null'] === 'YES') {
  1190. $createQuery .= ' DEFAULT NULL';
  1191. }
  1192. }
  1193. if (! empty($column['Comment'])) {
  1194. $createQuery .= " COMMENT '"
  1195. . $dbi->escapeString($column['Comment']) . "'";
  1196. }
  1197. $firstCol = false;
  1198. }
  1199. $createQuery .= $crlf . ')' . ($addSemicolon ? ';' : '') . $crlf;
  1200. if (isset($GLOBALS['sql_compatibility'])) {
  1201. $compat = $GLOBALS['sql_compatibility'];
  1202. } else {
  1203. $compat = 'NONE';
  1204. }
  1205. if ($compat === 'MSSQL') {
  1206. $createQuery = $this->makeCreateTableMSSQLCompatible($createQuery);
  1207. }
  1208. return $createQuery;
  1209. }
  1210. /**
  1211. * Returns $table's CREATE definition
  1212. *
  1213. * @param string $db the database name
  1214. * @param string $table the table name
  1215. * @param string $crlf the end of line sequence
  1216. * @param string $errorUrl the url to go back in case
  1217. * of error
  1218. * @param bool $showDates whether to include creation/
  1219. * update/check dates
  1220. * @param bool $addSemicolon whether to add semicolon and
  1221. * end-of-line at the end
  1222. * @param bool $view whether we're handling a view
  1223. * @param bool $updateIndexesIncrements whether we need to update
  1224. * two global variables
  1225. * @param array $aliases Aliases of db/table/columns
  1226. *
  1227. * @return string resulting schema
  1228. */
  1229. public function getTableDef(
  1230. $db,
  1231. $table,
  1232. $crlf,
  1233. $errorUrl,
  1234. $showDates = false,
  1235. $addSemicolon = true,
  1236. $view = false,
  1237. $updateIndexesIncrements = true,
  1238. array $aliases = []
  1239. ) {
  1240. global $sql_drop_table, $sql_backquotes, $sql_constraints,
  1241. $sql_constraints_query, $sql_indexes, $sql_indexes_query,
  1242. $sql_auto_increments, $sql_drop_foreign_keys, $dbi, $cfg;
  1243. $dbAlias = $db;
  1244. $tableAlias = $table;
  1245. $this->initAlias($aliases, $dbAlias, $tableAlias);
  1246. $schemaCreate = '';
  1247. $newCrlf = $crlf;
  1248. if (isset($GLOBALS['sql_compatibility'])) {
  1249. $compat = $GLOBALS['sql_compatibility'];
  1250. } else {
  1251. $compat = 'NONE';
  1252. }
  1253. $result = $dbi->tryQuery(
  1254. 'SHOW TABLE STATUS FROM ' . Util::backquote($db)
  1255. . ' WHERE Name = \'' . $dbi->escapeString((string) $table) . '\''
  1256. );
  1257. if ($result != false) {
  1258. if ($result->numRows() > 0) {
  1259. $tmpres = $result->fetchAssoc();
  1260. if ($showDates && isset($tmpres['Create_time']) && ! empty($tmpres['Create_time'])) {
  1261. $schemaCreate .= $this->exportComment(
  1262. __('Creation:') . ' '
  1263. . Util::localisedDate(
  1264. strtotime($tmpres['Create_time'])
  1265. )
  1266. );
  1267. $newCrlf = $this->exportComment() . $crlf;
  1268. }
  1269. if ($showDates && isset($tmpres['Update_time']) && ! empty($tmpres['Update_time'])) {
  1270. $schemaCreate .= $this->exportComment(
  1271. __('Last update:') . ' '
  1272. . Util::localisedDate(
  1273. strtotime($tmpres['Update_time'])
  1274. )
  1275. );
  1276. $newCrlf = $this->exportComment() . $crlf;
  1277. }
  1278. if ($showDates && isset($tmpres['Check_time']) && ! empty($tmpres['Check_time'])) {
  1279. $schemaCreate .= $this->exportComment(
  1280. __('Last check:') . ' '
  1281. . Util::localisedDate(
  1282. strtotime($tmpres['Check_time'])
  1283. )
  1284. );
  1285. $newCrlf = $this->exportComment() . $crlf;
  1286. }
  1287. }
  1288. }
  1289. $schemaCreate .= $newCrlf;
  1290. if (! empty($sql_drop_table) && $dbi->getTable($db, $table)->isView()) {
  1291. $schemaCreate .= 'DROP VIEW IF EXISTS '
  1292. . Util::backquoteCompat($tableAlias, 'NONE', $sql_backquotes) . ';'
  1293. . $crlf;
  1294. }
  1295. // no need to generate a DROP VIEW here, it was done earlier
  1296. if (! empty($sql_drop_table) && ! $dbi->getTable($db, $table)->isView()) {
  1297. $schemaCreate .= 'DROP TABLE IF EXISTS '
  1298. . Util::backquoteCompat($tableAlias, 'NONE', $sql_backquotes) . ';'
  1299. . $crlf;
  1300. }
  1301. // Complete table dump,
  1302. // Whether to quote table and column names or not
  1303. if ($sql_backquotes) {
  1304. $dbi->query('SET SQL_QUOTE_SHOW_CREATE = 1');
  1305. } else {
  1306. $dbi->query('SET SQL_QUOTE_SHOW_CREATE = 0');
  1307. }
  1308. // I don't see the reason why this unbuffered query could cause problems,
  1309. // because SHOW CREATE TABLE returns only one row, and we free the
  1310. // results below. Nonetheless, we got 2 user reports about this
  1311. // (see bug 1562533) so I removed the unbuffered mode.
  1312. // $result = $dbi->query('SHOW CREATE TABLE ' . backquote($db)
  1313. // . '.' . backquote($table), null, DatabaseInterface::QUERY_UNBUFFERED);
  1314. //
  1315. // Note: SHOW CREATE TABLE, at least in MySQL 5.1.23, does not
  1316. // produce a displayable result for the default value of a BIT
  1317. // column, nor does the mysqldump command. See MySQL bug 35796
  1318. $dbi->tryQuery('USE ' . Util::backquote($db));
  1319. $result = $dbi->tryQuery(
  1320. 'SHOW CREATE TABLE ' . Util::backquote($db) . '.'
  1321. . Util::backquote($table)
  1322. );
  1323. // an error can happen, for example the table is crashed
  1324. $tmpError = $dbi->getError();
  1325. if ($tmpError) {
  1326. $message = sprintf(__('Error reading structure for table %s:'), $db . '.' . $table);
  1327. $message .= ' ' . $tmpError;
  1328. if (! defined('TESTSUITE')) {
  1329. trigger_error($message, E_USER_ERROR);
  1330. }
  1331. return $this->exportComment($message);
  1332. }
  1333. // Old mode is stored so it can be restored once exporting is done.
  1334. $oldMode = Context::$MODE;
  1335. $warning = '';
  1336. $row = null;
  1337. if ($result !== false) {
  1338. $row = $result->fetchRow();
  1339. }
  1340. if ($row) {
  1341. $createQuery = $row[1];
  1342. unset($row);
  1343. // Convert end of line chars to one that we want (note that MySQL
  1344. // doesn't return query it will accept in all cases)
  1345. if (mb_strpos($createQuery, "(\r\n ")) {
  1346. $createQuery = str_replace("\r\n", $crlf, $createQuery);
  1347. } elseif (mb_strpos($createQuery, "(\n ")) {
  1348. $createQuery = str_replace("\n", $crlf, $createQuery);
  1349. } elseif (mb_strpos($createQuery, "(\r ")) {
  1350. $createQuery = str_replace("\r", $crlf, $createQuery);
  1351. }
  1352. /*
  1353. * Drop database name from VIEW creation.
  1354. *
  1355. * This is a bit tricky, but we need to issue SHOW CREATE TABLE with
  1356. * database name, but we don't want name to show up in CREATE VIEW
  1357. * statement.
  1358. */
  1359. if ($view) {
  1360. //TODO: use parser
  1361. $createQuery = preg_replace(
  1362. '/' . preg_quote(Util::backquote($db), '/') . '\./',
  1363. '',
  1364. $createQuery
  1365. );
  1366. $parser = new Parser($createQuery);
  1367. /**
  1368. * `CREATE TABLE` statement.
  1369. *
  1370. * @var CreateStatement
  1371. */
  1372. $statement = $parser->statements[0];
  1373. // exclude definition of current user
  1374. if ($cfg['Export']['remove_definer_from_definitions'] || isset($GLOBALS['sql_view_current_user'])) {
  1375. $statement->options->remove('DEFINER');
  1376. }
  1377. if (isset($GLOBALS['sql_simple_view_export'])) {
  1378. $statement->options->remove('SQL SECURITY');
  1379. $statement->options->remove('INVOKER');
  1380. $statement->options->remove('ALGORITHM');
  1381. $statement->options->remove('DEFINER');
  1382. }
  1383. $createQuery = $statement->build();
  1384. // whether to replace existing view or not
  1385. if (isset($GLOBALS['sql_or_replace_view'])) {
  1386. $createQuery = preg_replace('/^CREATE/', 'CREATE OR REPLACE', $createQuery);
  1387. }
  1388. }
  1389. // Substitute aliases in `CREATE` query.
  1390. $createQuery = $this->replaceWithAliases(null, $createQuery, $aliases, $db, $table, $flag);
  1391. // One warning per view.
  1392. if ($flag && $view) {
  1393. $warning = $this->exportComment()
  1394. . $this->exportComment(
  1395. __('It appears your database uses views;')
  1396. )
  1397. . $this->exportComment(
  1398. __('alias export may not work reliably in all cases.')
  1399. )
  1400. . $this->exportComment();
  1401. }
  1402. // Adding IF NOT EXISTS, if required.
  1403. if (isset($GLOBALS['sql_if_not_exists'])) {
  1404. $createQuery = (string) preg_replace('/^CREATE TABLE/', 'CREATE TABLE IF NOT EXISTS', $createQuery);
  1405. }
  1406. // Making the query MSSQL compatible.
  1407. if ($compat === 'MSSQL') {
  1408. $createQuery = $this->makeCreateTableMSSQLCompatible($createQuery);
  1409. }
  1410. // Views have no constraints, indexes, etc. They do not require any
  1411. // analysis.
  1412. if (! $view) {
  1413. if (empty($sql_backquotes)) {
  1414. // Option "Enclose table and column names with backquotes"
  1415. // was checked.
  1416. Context::$MODE |= Context::SQL_MODE_NO_ENCLOSING_QUOTES;
  1417. }
  1418. // Using appropriate quotes.
  1419. if (($compat === 'MSSQL') || ($sql_backquotes === '"')) {
  1420. Context::$MODE |= Context::SQL_MODE_ANSI_QUOTES;
  1421. }
  1422. }
  1423. /**
  1424. * Parser used for analysis.
  1425. */
  1426. $parser = new Parser($createQuery);
  1427. /**
  1428. * `CREATE TABLE` statement.
  1429. *
  1430. * @var CreateStatement
  1431. */
  1432. $statement = $parser->statements[0];
  1433. if (! empty($statement->entityOptions)) {
  1434. $engine = $statement->entityOptions->has('ENGINE');
  1435. } else {
  1436. $engine = '';
  1437. }
  1438. /* Avoid operation on ARCHIVE tables as those can not be altered */
  1439. if (
  1440. (! empty($statement->fields) && is_array($statement->fields))
  1441. && (empty($engine) || strtoupper($engine) !== 'ARCHIVE')
  1442. ) {
  1443. /**
  1444. * Fragments containing definition of each constraint.
  1445. *
  1446. * @var array
  1447. */
  1448. $constraints = [];
  1449. /**
  1450. * Fragments containing definition of each index.
  1451. *
  1452. * @var array
  1453. */
  1454. $indexes = [];
  1455. /**
  1456. * Fragments containing definition of each FULLTEXT index.
  1457. *
  1458. * @var array
  1459. */
  1460. $indexesFulltext = [];
  1461. /**
  1462. * Fragments containing definition of each foreign key that will
  1463. * be dropped.
  1464. *
  1465. * @var array
  1466. */
  1467. $dropped = [];
  1468. /**
  1469. * Fragment containing definition of the `AUTO_INCREMENT`.
  1470. *
  1471. * @var array
  1472. */
  1473. $autoIncrement = [];
  1474. // Scanning each field of the `CREATE` statement to fill the arrays
  1475. // above.
  1476. // If the field is used in any of the arrays above, it is removed
  1477. // from the original definition.
  1478. // Also, AUTO_INCREMENT attribute is removed.
  1479. /** @var CreateDefinition $field */
  1480. foreach ($statement->fields as $key => $field) {
  1481. if ($field->isConstraint) {
  1482. // Creating the parts that add constraints.
  1483. $constraints[] = $field::build($field);
  1484. unset($statement->fields[$key]);
  1485. } elseif (! empty($field->key)) {
  1486. // Creating the parts that add indexes (must not be
  1487. // constraints).
  1488. if ($field->key->type === 'FULLTEXT KEY') {
  1489. $indexesFulltext[] = $field::build($field);
  1490. unset($statement->fields[$key]);
  1491. } else {
  1492. if (empty($GLOBALS['sql_if_not_exists'])) {
  1493. $indexes[] = str_replace(
  1494. 'COMMENT=\'',
  1495. 'COMMENT \'',
  1496. $field::build($field)
  1497. );
  1498. unset($statement->fields[$key]);
  1499. }
  1500. }
  1501. }
  1502. // Creating the parts that drop foreign keys.
  1503. if (! empty($field->key)) {
  1504. if ($field->key->type === 'FOREIGN KEY') {
  1505. $dropped[] = 'FOREIGN KEY ' . Context::escape($field->name);
  1506. unset($statement->fields[$key]);
  1507. }
  1508. }
  1509. // Dropping AUTO_INCREMENT.
  1510. if (empty($field->options)) {
  1511. continue;
  1512. }
  1513. if (! $field->options->has('AUTO_INCREMENT') || ! empty($GLOBALS['sql_if_not_exists'])) {
  1514. continue;
  1515. }
  1516. $autoIncrement[] = $field::build($field);
  1517. $field->options->remove('AUTO_INCREMENT');
  1518. }
  1519. /**
  1520. * The header of the `ALTER` statement (`ALTER TABLE tbl`).
  1521. *
  1522. * @var string
  1523. */
  1524. $alterHeader = 'ALTER TABLE ' .
  1525. Util::backquoteCompat($tableAlias, $compat, $sql_backquotes);
  1526. /**
  1527. * The footer of the `ALTER` statement (usually ';')
  1528. *
  1529. * @var string
  1530. */
  1531. $alterFooter = ';' . $crlf;
  1532. // Generating constraints-related query.
  1533. if (! empty($constraints)) {
  1534. $sql_constraints_query = $alterHeader . $crlf . ' ADD '
  1535. . implode(',' . $crlf . ' ADD ', $constraints)
  1536. . $alterFooter;
  1537. $sql_constraints = $this->generateComment(
  1538. $crlf,
  1539. $sql_constraints,
  1540. __('Constraints for dumped tables'),
  1541. __('Constraints for table'),
  1542. $tableAlias,
  1543. $compat
  1544. ) . $sql_constraints_query;
  1545. }
  1546. // Generating indexes-related query.
  1547. $sql_indexes_query = '';
  1548. if (! empty($indexes)) {
  1549. $sql_indexes_query .= $alterHeader . $crlf . ' ADD '
  1550. . implode(',' . $crlf . ' ADD ', $indexes)
  1551. . $alterFooter;
  1552. }
  1553. if (! empty($indexesFulltext)) {
  1554. // InnoDB supports one FULLTEXT index creation at a time.
  1555. // So FULLTEXT indexes are created one-by-one after other
  1556. // indexes where created.
  1557. $sql_indexes_query .= $alterHeader .
  1558. ' ADD ' . implode($alterFooter . $alterHeader . ' ADD ', $indexesFulltext) . $alterFooter;
  1559. }
  1560. if (! empty($indexes) || ! empty($indexesFulltext)) {
  1561. $sql_indexes = $this->generateComment(
  1562. $crlf,
  1563. $sql_indexes,
  1564. __('Indexes for dumped tables'),
  1565. __('Indexes for table'),
  1566. $tableAlias,
  1567. $compat
  1568. ) . $sql_indexes_query;
  1569. }
  1570. // Generating drop foreign keys-related query.
  1571. if (! empty($dropped)) {
  1572. $sql_drop_foreign_keys = $alterHeader . $crlf . ' DROP '
  1573. . implode(',' . $crlf . ' DROP ', $dropped)
  1574. . $alterFooter;
  1575. }
  1576. // Generating auto-increment-related query.
  1577. if ($autoIncrement !== [] && $updateIndexesIncrements) {
  1578. $sqlAutoIncrementsQuery = $alterHeader . $crlf . ' MODIFY '
  1579. . implode(',' . $crlf . ' MODIFY ', $autoIncrement);
  1580. if (
  1581. isset($GLOBALS['sql_auto_increment'])
  1582. && ($statement->entityOptions->has('AUTO_INCREMENT') !== false)
  1583. ) {
  1584. if (
  1585. ! isset($GLOBALS['table_data'])
  1586. || (isset($GLOBALS['table_data'])
  1587. && in_array($table, $GLOBALS['table_data']))
  1588. ) {
  1589. $sqlAutoIncrementsQuery .= ', AUTO_INCREMENT='
  1590. . $statement->entityOptions->has('AUTO_INCREMENT');
  1591. }
  1592. }
  1593. $sqlAutoIncrementsQuery .= ';' . $crlf;
  1594. $sql_auto_increments = $this->generateComment(
  1595. $crlf,
  1596. $sql_auto_increments,
  1597. __('AUTO_INCREMENT for dumped tables'),
  1598. __('AUTO_INCREMENT for table'),
  1599. $tableAlias,
  1600. $compat
  1601. ) . $sqlAutoIncrementsQuery;
  1602. }
  1603. // Removing the `AUTO_INCREMENT` attribute from the `CREATE TABLE`
  1604. // too.
  1605. if (
  1606. ! empty($statement->entityOptions)
  1607. && (empty($GLOBALS['sql_if_not_exists'])
  1608. || empty($GLOBALS['sql_auto_increment']))
  1609. ) {
  1610. $statement->entityOptions->remove('AUTO_INCREMENT');
  1611. }
  1612. // Rebuilding the query.
  1613. $createQuery = $statement->build();
  1614. }
  1615. $schemaCreate .= $createQuery;
  1616. }
  1617. // Restoring old mode.
  1618. Context::$MODE = $oldMode;
  1619. return $warning . $schemaCreate . ($addSemicolon ? ';' . $crlf : '');
  1620. }
  1621. /**
  1622. * Returns $table's comments, relations etc.
  1623. *
  1624. * @param string $db database name
  1625. * @param string $table table name
  1626. * @param bool $doRelation whether to include relation comments
  1627. * @param bool $doMime whether to include mime comments
  1628. * @param array $aliases Aliases of db/table/columns
  1629. *
  1630. * @return string resulting comments
  1631. */
  1632. private function getTableComments(
  1633. $db,
  1634. $table,
  1635. $doRelation = false,
  1636. $doMime = false,
  1637. array $aliases = []
  1638. ) {
  1639. global $sql_backquotes;
  1640. $dbAlias = $db;
  1641. $tableAlias = $table;
  1642. $this->initAlias($aliases, $dbAlias, $tableAlias);
  1643. $relationParameters = $this->relation->getRelationParameters();
  1644. $schemaCreate = '';
  1645. // Check if we can use Relations
  1646. [$resRel, $haveRel] = $this->relation->getRelationsAndStatus(
  1647. $doRelation && $relationParameters->relationFeature !== null,
  1648. $db,
  1649. $table
  1650. );
  1651. if ($doMime && $relationParameters->browserTransformationFeature !== null) {
  1652. $mimeMap = $this->transformations->getMime($db, $table, true);
  1653. if ($mimeMap === null) {
  1654. unset($mimeMap);
  1655. }
  1656. }
  1657. if (isset($mimeMap) && count($mimeMap) > 0) {
  1658. $schemaCreate .= $this->possibleCRLF()
  1659. . $this->exportComment()
  1660. . $this->exportComment(
  1661. __('MEDIA TYPES FOR TABLE') . ' '
  1662. . Util::backquoteCompat($table, 'NONE', $sql_backquotes) . ':'
  1663. );
  1664. foreach ($mimeMap as $mimeField => $mime) {
  1665. $schemaCreate .= $this->exportComment(
  1666. ' '
  1667. . Util::backquoteCompat($mimeField, 'NONE', $sql_backquotes)
  1668. )
  1669. . $this->exportComment(
  1670. ' '
  1671. . Util::backquoteCompat(
  1672. $mime['mimetype'],
  1673. 'NONE',
  1674. $sql_backquotes
  1675. )
  1676. );
  1677. }
  1678. $schemaCreate .= $this->exportComment();
  1679. }
  1680. if ($haveRel) {
  1681. $schemaCreate .= $this->possibleCRLF()
  1682. . $this->exportComment()
  1683. . $this->exportComment(
  1684. __('RELATIONSHIPS FOR TABLE') . ' '
  1685. . Util::backquoteCompat($tableAlias, 'NONE', $sql_backquotes)
  1686. . ':'
  1687. );
  1688. foreach ($resRel as $relField => $rel) {
  1689. if ($relField !== 'foreign_keys_data') {
  1690. $relFieldAlias = ! empty(
  1691. $aliases[$db]['tables'][$table]['columns'][$relField]
  1692. ) ? $aliases[$db]['tables'][$table]['columns'][$relField]
  1693. : $relField;
  1694. $schemaCreate .= $this->exportComment(
  1695. ' '
  1696. . Util::backquoteCompat(
  1697. $relFieldAlias,
  1698. 'NONE',
  1699. $sql_backquotes
  1700. )
  1701. )
  1702. . $this->exportComment(
  1703. ' '
  1704. . Util::backquoteCompat(
  1705. $rel['foreign_table'],
  1706. 'NONE',
  1707. $sql_backquotes
  1708. )
  1709. . ' -> '
  1710. . Util::backquoteCompat(
  1711. $rel['foreign_field'],
  1712. 'NONE',
  1713. $sql_backquotes
  1714. )
  1715. );
  1716. } else {
  1717. foreach ($rel as $oneKey) {
  1718. foreach ($oneKey['index_list'] as $index => $field) {
  1719. $relFieldAlias = ! empty(
  1720. $aliases[$db]['tables'][$table]['columns'][$field]
  1721. ) ? $aliases[$db]['tables'][$table]['columns'][$field]
  1722. : $field;
  1723. $schemaCreate .= $this->exportComment(
  1724. ' '
  1725. . Util::backquoteCompat(
  1726. $relFieldAlias,
  1727. 'NONE',
  1728. $sql_backquotes
  1729. )
  1730. )
  1731. . $this->exportComment(
  1732. ' '
  1733. . Util::backquoteCompat(
  1734. $oneKey['ref_table_name'],
  1735. 'NONE',
  1736. $sql_backquotes
  1737. )
  1738. . ' -> '
  1739. . Util::backquoteCompat(
  1740. $oneKey['ref_index_list'][$index],
  1741. 'NONE',
  1742. $sql_backquotes
  1743. )
  1744. );
  1745. }
  1746. }
  1747. }
  1748. }
  1749. $schemaCreate .= $this->exportComment();
  1750. }
  1751. return $schemaCreate;
  1752. }
  1753. /**
  1754. * Outputs a raw query
  1755. *
  1756. * @param string $errorUrl the url to go back in case of error
  1757. * @param string|null $db the database where the query is executed
  1758. * @param string $sqlQuery the rawquery to output
  1759. * @param string $crlf the end of line sequence
  1760. */
  1761. public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
  1762. {
  1763. global $dbi;
  1764. if ($db !== null) {
  1765. $dbi->selectDb($db);
  1766. }
  1767. return $this->exportData($db ?? '', '', $crlf, $errorUrl, $sqlQuery);
  1768. }
  1769. /**
  1770. * Outputs table's structure
  1771. *
  1772. * @param string $db database name
  1773. * @param string $table table name
  1774. * @param string $crlf the end of line sequence
  1775. * @param string $errorUrl the url to go back in case of error
  1776. * @param string $exportMode 'create_table','triggers','create_view',
  1777. * 'stand_in'
  1778. * @param string $exportType 'server', 'database', 'table'
  1779. * @param bool $relation whether to include relation comments
  1780. * @param bool $comments whether to include the pmadb-style column
  1781. * comments as comments in the structure; this is
  1782. * deprecated but the parameter is left here
  1783. * because /export calls exportStructure()
  1784. * also for other export types which use this
  1785. * parameter
  1786. * @param bool $mime whether to include mime comments
  1787. * @param bool $dates whether to include creation/update/check dates
  1788. * @param array $aliases Aliases of db/table/columns
  1789. */
  1790. public function exportStructure(
  1791. $db,
  1792. $table,
  1793. $crlf,
  1794. $errorUrl,
  1795. $exportMode,
  1796. $exportType,
  1797. $relation = false,
  1798. $comments = false,
  1799. $mime = false,
  1800. $dates = false,
  1801. array $aliases = []
  1802. ): bool {
  1803. global $dbi;
  1804. $dbAlias = $db;
  1805. $tableAlias = $table;
  1806. $this->initAlias($aliases, $dbAlias, $tableAlias);
  1807. if (isset($GLOBALS['sql_compatibility'])) {
  1808. $compat = $GLOBALS['sql_compatibility'];
  1809. } else {
  1810. $compat = 'NONE';
  1811. }
  1812. $formattedTableName = Util::backquoteCompat($tableAlias, $compat, isset($GLOBALS['sql_backquotes']));
  1813. $dump = $this->possibleCRLF()
  1814. . $this->exportComment(str_repeat('-', 56))
  1815. . $this->possibleCRLF()
  1816. . $this->exportComment();
  1817. switch ($exportMode) {
  1818. case 'create_table':
  1819. $dump .= $this->exportComment(
  1820. __('Table structure for table') . ' ' . $formattedTableName
  1821. );
  1822. $dump .= $this->exportComment();
  1823. $dump .= $this->getTableDef($db, $table, $crlf, $errorUrl, $dates, true, false, true, $aliases);
  1824. $dump .= $this->getTableComments($db, $table, $relation, $mime, $aliases);
  1825. break;
  1826. case 'triggers':
  1827. $dump = '';
  1828. $delimiter = '$$';
  1829. $triggers = $dbi->getTriggers($db, $table, $delimiter);
  1830. if ($triggers) {
  1831. $dump .= $this->possibleCRLF()
  1832. . $this->exportComment()
  1833. . $this->exportComment(
  1834. __('Triggers') . ' ' . $formattedTableName
  1835. )
  1836. . $this->exportComment();
  1837. $usedAlias = false;
  1838. $triggerQuery = '';
  1839. foreach ($triggers as $trigger) {
  1840. if (! empty($GLOBALS['sql_drop_table'])) {
  1841. $triggerQuery .= $trigger['drop'] . ';' . $crlf;
  1842. }
  1843. $triggerQuery .= 'DELIMITER ' . $delimiter . $crlf;
  1844. $triggerQuery .= $this->replaceWithAliases(
  1845. $delimiter,
  1846. $trigger['create'],
  1847. $aliases,
  1848. $db,
  1849. $table,
  1850. $flag
  1851. );
  1852. if ($flag) {
  1853. $usedAlias = true;
  1854. }
  1855. $triggerQuery .= $delimiter . $crlf . 'DELIMITER ;' . $crlf;
  1856. }
  1857. // One warning per table.
  1858. if ($usedAlias) {
  1859. $dump .= $this->exportComment(
  1860. __('It appears your table uses triggers;')
  1861. )
  1862. . $this->exportComment(
  1863. __('alias export may not work reliably in all cases.')
  1864. )
  1865. . $this->exportComment();
  1866. }
  1867. $dump .= $triggerQuery;
  1868. }
  1869. break;
  1870. case 'create_view':
  1871. if (empty($GLOBALS['sql_views_as_tables'])) {
  1872. $dump .= $this->exportComment(
  1873. __('Structure for view')
  1874. . ' '
  1875. . $formattedTableName
  1876. )
  1877. . $this->exportComment();
  1878. // delete the stand-in table previously created (if any)
  1879. if ($exportType !== 'table') {
  1880. $dump .= 'DROP TABLE IF EXISTS '
  1881. . Util::backquote($tableAlias) . ';' . $crlf;
  1882. }
  1883. $dump .= $this->getTableDef($db, $table, $crlf, $errorUrl, $dates, true, true, true, $aliases);
  1884. } else {
  1885. $dump .= $this->exportComment(
  1886. sprintf(
  1887. __('Structure for view %s exported as a table'),
  1888. $formattedTableName
  1889. )
  1890. )
  1891. . $this->exportComment();
  1892. // delete the stand-in table previously created (if any)
  1893. if ($exportType !== 'table') {
  1894. $dump .= 'DROP TABLE IF EXISTS '
  1895. . Util::backquote($tableAlias) . ';' . $crlf;
  1896. }
  1897. $dump .= $this->getTableDefForView($db, $table, $crlf, true, $aliases);
  1898. }
  1899. if (empty($GLOBALS['sql_views_as_tables'])) {
  1900. // Save views, to be inserted after indexes
  1901. // in case the view uses USE INDEX syntax
  1902. $this->sqlViews .= $dump;
  1903. $dump = '';
  1904. }
  1905. break;
  1906. case 'stand_in':
  1907. $dump .= $this->exportComment(
  1908. __('Stand-in structure for view') . ' ' . $formattedTableName
  1909. )
  1910. . $this->exportComment(
  1911. __('(See below for the actual view)')
  1912. )
  1913. . $this->exportComment();
  1914. // export a stand-in definition to resolve view dependencies
  1915. $dump .= $this->getTableDefStandIn($db, $table, $crlf, $aliases);
  1916. }
  1917. // this one is built by getTableDef() to use in table copy/move
  1918. // but not in the case of export
  1919. unset($GLOBALS['sql_constraints_query']);
  1920. return $this->export->outputHandler($dump);
  1921. }
  1922. /**
  1923. * Outputs the content of a table in SQL format
  1924. *
  1925. * @param string $db database name
  1926. * @param string $table table name
  1927. * @param string $crlf the end of line sequence
  1928. * @param string $errorUrl the url to go back in case of error
  1929. * @param string $sqlQuery SQL query for obtaining data
  1930. * @param array $aliases Aliases of db/table/columns
  1931. */
  1932. public function exportData(
  1933. $db,
  1934. $table,
  1935. $crlf,
  1936. $errorUrl,
  1937. $sqlQuery,
  1938. array $aliases = []
  1939. ): bool {
  1940. global $current_row, $sql_backquotes, $dbi;
  1941. // Do not export data for merge tables
  1942. if ($dbi->getTable($db, $table)->isMerge()) {
  1943. return true;
  1944. }
  1945. $dbAlias = $db;
  1946. $tableAlias = $table;
  1947. $this->initAlias($aliases, $dbAlias, $tableAlias);
  1948. if (isset($GLOBALS['sql_compatibility'])) {
  1949. $compat = $GLOBALS['sql_compatibility'];
  1950. } else {
  1951. $compat = 'NONE';
  1952. }
  1953. $formattedTableName = Util::backquoteCompat($tableAlias, $compat, $sql_backquotes);
  1954. // Do not export data for a VIEW, unless asked to export the view as a table
  1955. // (For a VIEW, this is called only when exporting a single VIEW)
  1956. if ($dbi->getTable($db, $table)->isView() && empty($GLOBALS['sql_views_as_tables'])) {
  1957. $head = $this->possibleCRLF()
  1958. . $this->exportComment()
  1959. . $this->exportComment('VIEW ' . $formattedTableName)
  1960. . $this->exportComment(__('Data:') . ' ' . __('None'))
  1961. . $this->exportComment()
  1962. . $this->possibleCRLF();
  1963. return $this->export->outputHandler($head);
  1964. }
  1965. $result = $dbi->tryQuery($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
  1966. // a possible error: the table has crashed
  1967. $tmpError = $dbi->getError();
  1968. if ($tmpError) {
  1969. $message = sprintf(__('Error reading data for table %s:'), $db . '.' . $table);
  1970. $message .= ' ' . $tmpError;
  1971. if (! defined('TESTSUITE')) {
  1972. trigger_error($message, E_USER_ERROR);
  1973. }
  1974. return $this->export->outputHandler(
  1975. $this->exportComment($message)
  1976. );
  1977. }
  1978. if ($result === false) {
  1979. return true;
  1980. }
  1981. $fieldsCnt = $result->numFields();
  1982. // Get field information
  1983. /** @var FieldMetadata[] $fieldsMeta */
  1984. $fieldsMeta = $dbi->getFieldsMeta($result);
  1985. $fieldSet = [];
  1986. for ($j = 0; $j < $fieldsCnt; $j++) {
  1987. $colAs = $fieldsMeta[$j]->name;
  1988. if (! empty($aliases[$db]['tables'][$table]['columns'][$colAs])) {
  1989. $colAs = $aliases[$db]['tables'][$table]['columns'][$colAs];
  1990. }
  1991. $fieldSet[$j] = Util::backquoteCompat($colAs, $compat, $sql_backquotes);
  1992. }
  1993. if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] === 'UPDATE') {
  1994. // update
  1995. $schemaInsert = 'UPDATE ';
  1996. if (isset($GLOBALS['sql_ignore'])) {
  1997. $schemaInsert .= 'IGNORE ';
  1998. }
  1999. // avoid EOL blank
  2000. $schemaInsert .= Util::backquoteCompat($tableAlias, $compat, $sql_backquotes) . ' SET';
  2001. } else {
  2002. // insert or replace
  2003. if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] === 'REPLACE') {
  2004. $sqlCommand = 'REPLACE';
  2005. } else {
  2006. $sqlCommand = 'INSERT';
  2007. }
  2008. // delayed inserts?
  2009. if (isset($GLOBALS['sql_delayed'])) {
  2010. $insertDelayed = ' DELAYED';
  2011. } else {
  2012. $insertDelayed = '';
  2013. }
  2014. // insert ignore?
  2015. if (isset($GLOBALS['sql_type'], $GLOBALS['sql_ignore']) && $GLOBALS['sql_type'] === 'INSERT') {
  2016. $insertDelayed .= ' IGNORE';
  2017. }
  2018. //truncate table before insert
  2019. if (isset($GLOBALS['sql_truncate']) && $GLOBALS['sql_truncate'] && $sqlCommand === 'INSERT') {
  2020. $truncate = 'TRUNCATE TABLE '
  2021. . Util::backquoteCompat($tableAlias, $compat, $sql_backquotes) . ';';
  2022. $truncatehead = $this->possibleCRLF()
  2023. . $this->exportComment()
  2024. . $this->exportComment(
  2025. __('Truncate table before insert') . ' '
  2026. . $formattedTableName
  2027. )
  2028. . $this->exportComment()
  2029. . $crlf;
  2030. $this->export->outputHandler($truncatehead);
  2031. $this->export->outputHandler($truncate);
  2032. }
  2033. // scheme for inserting fields
  2034. if ($GLOBALS['sql_insert_syntax'] === 'complete' || $GLOBALS['sql_insert_syntax'] === 'both') {
  2035. $fields = implode(', ', $fieldSet);
  2036. $schemaInsert = $sqlCommand . $insertDelayed . ' INTO '
  2037. . Util::backquoteCompat($tableAlias, $compat, $sql_backquotes)
  2038. // avoid EOL blank
  2039. . ' (' . $fields . ') VALUES';
  2040. } else {
  2041. $schemaInsert = $sqlCommand . $insertDelayed . ' INTO '
  2042. . Util::backquoteCompat($tableAlias, $compat, $sql_backquotes)
  2043. . ' VALUES';
  2044. }
  2045. }
  2046. //\x08\\x09, not required
  2047. $current_row = 0;
  2048. $querySize = 0;
  2049. if (
  2050. ($GLOBALS['sql_insert_syntax'] === 'extended'
  2051. || $GLOBALS['sql_insert_syntax'] === 'both')
  2052. && (! isset($GLOBALS['sql_type'])
  2053. || $GLOBALS['sql_type'] !== 'UPDATE')
  2054. ) {
  2055. $separator = ',';
  2056. $schemaInsert .= $crlf;
  2057. } else {
  2058. $separator = ';';
  2059. }
  2060. while ($row = $result->fetchRow()) {
  2061. if ($current_row == 0) {
  2062. $head = $this->possibleCRLF()
  2063. . $this->exportComment()
  2064. . $this->exportComment(
  2065. __('Dumping data for table') . ' '
  2066. . $formattedTableName
  2067. )
  2068. . $this->exportComment()
  2069. . $crlf;
  2070. if (! $this->export->outputHandler($head)) {
  2071. return false;
  2072. }
  2073. }
  2074. // We need to SET IDENTITY_INSERT ON for MSSQL
  2075. if (
  2076. isset($GLOBALS['sql_compatibility'])
  2077. && $GLOBALS['sql_compatibility'] === 'MSSQL'
  2078. && $current_row == 0
  2079. ) {
  2080. if (
  2081. ! $this->export->outputHandler(
  2082. 'SET IDENTITY_INSERT '
  2083. . Util::backquoteCompat(
  2084. $tableAlias,
  2085. $compat,
  2086. $sql_backquotes
  2087. )
  2088. . ' ON ;' . $crlf
  2089. )
  2090. ) {
  2091. return false;
  2092. }
  2093. }
  2094. $current_row++;
  2095. $values = [];
  2096. for ($j = 0; $j < $fieldsCnt; $j++) {
  2097. // NULL
  2098. if (! isset($row[$j])) {
  2099. $values[] = 'NULL';
  2100. } elseif (
  2101. $fieldsMeta[$j]->isNumeric
  2102. ) {
  2103. // a number
  2104. $values[] = $row[$j];
  2105. } elseif ($fieldsMeta[$j]->isBinary && isset($GLOBALS['sql_hex_for_binary'])) {
  2106. // a true BLOB
  2107. // - mysqldump only generates hex data when the --hex-blob
  2108. // option is used, for fields having the binary attribute
  2109. // no hex is generated
  2110. // - a TEXT field returns type blob but a real blob
  2111. // returns also the 'binary' flag
  2112. // empty blobs need to be different, but '0' is also empty
  2113. // :-(
  2114. if (empty($row[$j]) && $row[$j] != '0') {
  2115. $values[] = '\'\'';
  2116. } else {
  2117. $values[] = '0x' . bin2hex($row[$j]);
  2118. }
  2119. } elseif ($fieldsMeta[$j]->isMappedTypeBit) {
  2120. // detection of 'bit' works only on mysqli extension
  2121. $values[] = "b'" . Util::printableBitValue(
  2122. (int) $row[$j],
  2123. (int) $fieldsMeta[$j]->length
  2124. ) . "'";
  2125. } elseif ($fieldsMeta[$j]->isMappedTypeGeometry) {
  2126. // export GIS types as hex
  2127. $values[] = '0x' . bin2hex($row[$j]);
  2128. } elseif (! empty($GLOBALS['exporting_metadata']) && $row[$j] === '@LAST_PAGE') {
  2129. $values[] = '@LAST_PAGE';
  2130. } elseif ($row[$j] === '') {
  2131. $values[] = "''";
  2132. } else {
  2133. // something else -> treat as a string
  2134. $values[] = '\'' . $dbi->escapeString($row[$j]) . '\'';
  2135. }
  2136. }
  2137. // should we make update?
  2138. if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] === 'UPDATE') {
  2139. $insertLine = $schemaInsert;
  2140. for ($i = 0; $i < $fieldsCnt; $i++) {
  2141. if ($i == 0) {
  2142. $insertLine .= ' ';
  2143. }
  2144. if ($i > 0) {
  2145. // avoid EOL blank
  2146. $insertLine .= ',';
  2147. }
  2148. $insertLine .= $fieldSet[$i] . ' = ' . $values[$i];
  2149. }
  2150. [$tmpUniqueCondition, $tmpClauseIsUnique] = Util::getUniqueCondition(
  2151. $fieldsCnt,
  2152. $fieldsMeta,
  2153. $row
  2154. );
  2155. $insertLine .= ' WHERE ' . $tmpUniqueCondition;
  2156. unset($tmpUniqueCondition, $tmpClauseIsUnique);
  2157. } else {
  2158. // Extended inserts case
  2159. if ($GLOBALS['sql_insert_syntax'] === 'extended' || $GLOBALS['sql_insert_syntax'] === 'both') {
  2160. if ($current_row == 1) {
  2161. $insertLine = $schemaInsert . '('
  2162. . implode(', ', $values) . ')';
  2163. } else {
  2164. $insertLine = '(' . implode(', ', $values) . ')';
  2165. $insertLineSize = mb_strlen($insertLine);
  2166. $sqlMaxSize = $GLOBALS['sql_max_query_size'];
  2167. if (isset($sqlMaxSize) && $sqlMaxSize > 0 && $querySize + $insertLineSize > $sqlMaxSize) {
  2168. if (! $this->export->outputHandler(';' . $crlf)) {
  2169. return false;
  2170. }
  2171. $querySize = 0;
  2172. $current_row = 1;
  2173. $insertLine = $schemaInsert . $insertLine;
  2174. }
  2175. }
  2176. $querySize += mb_strlen($insertLine);
  2177. // Other inserts case
  2178. } else {
  2179. $insertLine = $schemaInsert
  2180. . '(' . implode(', ', $values) . ')';
  2181. }
  2182. }
  2183. unset($values);
  2184. if (! $this->export->outputHandler(($current_row == 1 ? '' : $separator . $crlf) . $insertLine)) {
  2185. return false;
  2186. }
  2187. }
  2188. if ($current_row > 0) {
  2189. if (! $this->export->outputHandler(';' . $crlf)) {
  2190. return false;
  2191. }
  2192. }
  2193. // We need to SET IDENTITY_INSERT OFF for MSSQL
  2194. if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] === 'MSSQL' && $current_row > 0) {
  2195. $outputSucceeded = $this->export->outputHandler(
  2196. $crlf . 'SET IDENTITY_INSERT '
  2197. . Util::backquoteCompat(
  2198. $tableAlias,
  2199. $compat,
  2200. $sql_backquotes
  2201. )
  2202. . ' OFF;' . $crlf
  2203. );
  2204. if (! $outputSucceeded) {
  2205. return false;
  2206. }
  2207. }
  2208. return true;
  2209. }
  2210. /**
  2211. * Make a create table statement compatible with MSSQL
  2212. *
  2213. * @param string $createQuery MySQL create table statement
  2214. *
  2215. * @return string MSSQL compatible create table statement
  2216. */
  2217. private function makeCreateTableMSSQLCompatible($createQuery)
  2218. {
  2219. // In MSSQL
  2220. // 1. No 'IF NOT EXISTS' in CREATE TABLE
  2221. // 2. DATE field doesn't exists, we will use DATETIME instead
  2222. // 3. UNSIGNED attribute doesn't exist
  2223. // 4. No length on INT, TINYINT, SMALLINT, BIGINT and no precision on
  2224. // FLOAT fields
  2225. // 5. No KEY and INDEX inside CREATE TABLE
  2226. // 6. DOUBLE field doesn't exists, we will use FLOAT instead
  2227. $createQuery = (string) preg_replace('/^CREATE TABLE IF NOT EXISTS/', 'CREATE TABLE', (string) $createQuery);
  2228. // first we need to replace all lines ended with '" DATE ...,\n'
  2229. // last preg_replace preserve us from situation with date text
  2230. // inside DEFAULT field value
  2231. $createQuery = (string) preg_replace(
  2232. "/\" date DEFAULT NULL(,)?\n/",
  2233. '" datetime DEFAULT NULL$1' . "\n",
  2234. $createQuery
  2235. );
  2236. $createQuery = (string) preg_replace("/\" date NOT NULL(,)?\n/", '" datetime NOT NULL$1' . "\n", $createQuery);
  2237. $createQuery = (string) preg_replace(
  2238. '/" date NOT NULL DEFAULT \'([^\'])/',
  2239. '" datetime NOT NULL DEFAULT \'$1',
  2240. $createQuery
  2241. );
  2242. // next we need to replace all lines ended with ') UNSIGNED ...,'
  2243. // last preg_replace preserve us from situation with unsigned text
  2244. // inside DEFAULT field value
  2245. $createQuery = (string) preg_replace("/\) unsigned NOT NULL(,)?\n/", ') NOT NULL$1' . "\n", $createQuery);
  2246. $createQuery = (string) preg_replace(
  2247. "/\) unsigned DEFAULT NULL(,)?\n/",
  2248. ') DEFAULT NULL$1' . "\n",
  2249. $createQuery
  2250. );
  2251. $createQuery = (string) preg_replace(
  2252. '/\) unsigned NOT NULL DEFAULT \'([^\'])/',
  2253. ') NOT NULL DEFAULT \'$1',
  2254. $createQuery
  2255. );
  2256. // we need to replace all lines ended with
  2257. // '" INT|TINYINT([0-9]{1,}) ...,' last preg_replace preserve us
  2258. // from situation with int([0-9]{1,}) text inside DEFAULT field
  2259. // value
  2260. $createQuery = (string) preg_replace(
  2261. '/" (int|tinyint|smallint|bigint)\([0-9]+\) DEFAULT NULL(,)?\n/',
  2262. '" $1 DEFAULT NULL$2' . "\n",
  2263. $createQuery
  2264. );
  2265. $createQuery = (string) preg_replace(
  2266. '/" (int|tinyint|smallint|bigint)\([0-9]+\) NOT NULL(,)?\n/',
  2267. '" $1 NOT NULL$2' . "\n",
  2268. $createQuery
  2269. );
  2270. $createQuery = (string) preg_replace(
  2271. '/" (int|tinyint|smallint|bigint)\([0-9]+\) NOT NULL DEFAULT \'([^\'])/',
  2272. '" $1 NOT NULL DEFAULT \'$2',
  2273. $createQuery
  2274. );
  2275. // we need to replace all lines ended with
  2276. // '" FLOAT|DOUBLE([0-9,]{1,}) ...,'
  2277. // last preg_replace preserve us from situation with
  2278. // float([0-9,]{1,}) text inside DEFAULT field value
  2279. $createQuery = (string) preg_replace(
  2280. '/" (float|double)(\([0-9]+,[0-9,]+\))? DEFAULT NULL(,)?\n/',
  2281. '" float DEFAULT NULL$3' . "\n",
  2282. $createQuery
  2283. );
  2284. $createQuery = (string) preg_replace(
  2285. '/" (float|double)(\([0-9,]+,[0-9,]+\))? NOT NULL(,)?\n/',
  2286. '" float NOT NULL$3' . "\n",
  2287. $createQuery
  2288. );
  2289. return (string) preg_replace(
  2290. '/" (float|double)(\([0-9,]+,[0-9,]+\))? NOT NULL DEFAULT \'([^\'])/',
  2291. '" float NOT NULL DEFAULT \'$3',
  2292. $createQuery
  2293. );
  2294. // @todo remove indexes from CREATE TABLE
  2295. }
  2296. /**
  2297. * replaces db/table/column names with their aliases
  2298. *
  2299. * @param string|null $delimiter The delimiter for the parser (";" or "$$")
  2300. * @param string $sqlQuery SQL query in which aliases are to be substituted
  2301. * @param array $aliases Alias information for db/table/column
  2302. * @param string $db the database name
  2303. * @param string $table the tablename
  2304. * @param string $flag the flag denoting whether any replacement was done
  2305. *
  2306. * @return string query replaced with aliases
  2307. */
  2308. public function replaceWithAliases(
  2309. ?string $delimiter,
  2310. $sqlQuery,
  2311. array $aliases,
  2312. $db,
  2313. $table = '',
  2314. &$flag = null
  2315. ) {
  2316. $flag = false;
  2317. /**
  2318. * The parser of this query.
  2319. */
  2320. $parser = new Parser(empty($delimiter) ? $sqlQuery : 'DELIMITER ' . $delimiter . "\n" . $sqlQuery);
  2321. if (empty($parser->statements[0])) {
  2322. return $sqlQuery;
  2323. }
  2324. /**
  2325. * The statement that represents the query.
  2326. *
  2327. * @var CreateStatement $statement
  2328. */
  2329. $statement = $parser->statements[0];
  2330. /**
  2331. * Old database name.
  2332. */
  2333. $oldDatabase = $db;
  2334. // Replacing aliases in `CREATE TABLE` statement.
  2335. if ($statement->options->has('TABLE')) {
  2336. // Extracting the name of the old database and table from the
  2337. // statement to make sure the parameters are correct.
  2338. if (! empty($statement->name->database)) {
  2339. $oldDatabase = $statement->name->database;
  2340. }
  2341. /**
  2342. * Old table name.
  2343. */
  2344. $oldTable = $statement->name->table;
  2345. // Finding the aliased database name.
  2346. // The database might be empty so we have to add a few checks.
  2347. $newDatabase = null;
  2348. if (! empty($statement->name->database)) {
  2349. $newDatabase = $statement->name->database;
  2350. if (! empty($aliases[$oldDatabase]['alias'])) {
  2351. $newDatabase = $aliases[$oldDatabase]['alias'];
  2352. }
  2353. }
  2354. // Finding the aliases table name.
  2355. $newTable = $oldTable;
  2356. if (! empty($aliases[$oldDatabase]['tables'][$oldTable]['alias'])) {
  2357. $newTable = $aliases[$oldDatabase]['tables'][$oldTable]['alias'];
  2358. }
  2359. // Replacing new values.
  2360. if (($statement->name->database !== $newDatabase) || ($statement->name->table !== $newTable)) {
  2361. $statement->name->database = $newDatabase;
  2362. $statement->name->table = $newTable;
  2363. $statement->name->expr = ''; // Force rebuild.
  2364. $flag = true;
  2365. }
  2366. /** @var CreateDefinition[] $fields */
  2367. $fields = $statement->fields;
  2368. foreach ($fields as $field) {
  2369. // Column name.
  2370. if (! empty($field->type)) {
  2371. if (! empty($aliases[$oldDatabase]['tables'][$oldTable]['columns'][$field->name])) {
  2372. $field->name = $aliases[$oldDatabase]['tables'][$oldTable]['columns'][$field->name];
  2373. $flag = true;
  2374. }
  2375. }
  2376. // Key's columns.
  2377. if (! empty($field->key)) {
  2378. foreach ($field->key->columns as $key => $column) {
  2379. if (! isset($column['name'])) {
  2380. // In case the column has no name field
  2381. continue;
  2382. }
  2383. if (empty($aliases[$oldDatabase]['tables'][$oldTable]['columns'][$column['name']])) {
  2384. continue;
  2385. }
  2386. $columnAliases = $aliases[$oldDatabase]['tables'][$oldTable]['columns'];
  2387. $field->key->columns[$key]['name'] = $columnAliases[$column['name']];
  2388. $flag = true;
  2389. }
  2390. }
  2391. // References.
  2392. if (empty($field->references)) {
  2393. continue;
  2394. }
  2395. $refTable = $field->references->table->table;
  2396. // Replacing table.
  2397. if (! empty($aliases[$oldDatabase]['tables'][$refTable]['alias'])) {
  2398. $field->references->table->table = $aliases[$oldDatabase]['tables'][$refTable]['alias'];
  2399. $field->references->table->expr = '';
  2400. $flag = true;
  2401. }
  2402. // Replacing column names.
  2403. foreach ($field->references->columns as $key => $column) {
  2404. if (empty($aliases[$oldDatabase]['tables'][$refTable]['columns'][$column])) {
  2405. continue;
  2406. }
  2407. $field->references->columns[$key] = $aliases[$oldDatabase]['tables'][$refTable]['columns'][$column];
  2408. $flag = true;
  2409. }
  2410. }
  2411. } elseif ($statement->options->has('TRIGGER')) {
  2412. // Extracting the name of the old database and table from the
  2413. // statement to make sure the parameters are correct.
  2414. if (! empty($statement->table->database)) {
  2415. $oldDatabase = $statement->table->database;
  2416. }
  2417. /**
  2418. * Old table name.
  2419. */
  2420. $oldTable = $statement->table->table;
  2421. if (! empty($aliases[$oldDatabase]['tables'][$oldTable]['alias'])) {
  2422. $statement->table->table = $aliases[$oldDatabase]['tables'][$oldTable]['alias'];
  2423. $statement->table->expr = ''; // Force rebuild.
  2424. $flag = true;
  2425. }
  2426. }
  2427. if (
  2428. $statement->options->has('TRIGGER')
  2429. || $statement->options->has('PROCEDURE')
  2430. || $statement->options->has('FUNCTION')
  2431. || $statement->options->has('VIEW')
  2432. ) {
  2433. // Replacing the body.
  2434. for ($i = 0, $count = count((array) $statement->body); $i < $count; ++$i) {
  2435. /**
  2436. * Token parsed at this moment.
  2437. *
  2438. * @var Token $token
  2439. */
  2440. $token = $statement->body[$i];
  2441. // Replacing only symbols (that are not variables) and unknown
  2442. // identifiers.
  2443. $isSymbol = $token->type === Token::TYPE_SYMBOL;
  2444. $isKeyword = $token->type === Token::TYPE_KEYWORD;
  2445. $isNone = $token->type === Token::TYPE_NONE;
  2446. $replaceToken = $isSymbol
  2447. && (! ($token->flags & Token::FLAG_SYMBOL_VARIABLE))
  2448. || ($isKeyword
  2449. && (! ($token->flags & Token::FLAG_KEYWORD_RESERVED))
  2450. || $isNone);
  2451. if (! $replaceToken) {
  2452. continue;
  2453. }
  2454. $alias = $this->getAlias($aliases, $token->value);
  2455. if (empty($alias)) {
  2456. continue;
  2457. }
  2458. // Replacing the token.
  2459. $token->token = Context::escape($alias);
  2460. $flag = true;
  2461. }
  2462. }
  2463. return $statement->build();
  2464. }
  2465. /**
  2466. * Generate comment
  2467. *
  2468. * @param string $crlf Carriage return character
  2469. * @param string|null $sqlStatement SQL statement
  2470. * @param string $comment1 Comment for dumped table
  2471. * @param string $comment2 Comment for current table
  2472. * @param string $tableAlias Table alias
  2473. * @param string $compat Compatibility mode
  2474. *
  2475. * @return string
  2476. */
  2477. protected function generateComment(
  2478. $crlf,
  2479. ?string $sqlStatement,
  2480. $comment1,
  2481. $comment2,
  2482. $tableAlias,
  2483. $compat
  2484. ) {
  2485. if (! isset($sqlStatement)) {
  2486. if (isset($GLOBALS['no_constraints_comments'])) {
  2487. $sqlStatement = '';
  2488. } else {
  2489. $sqlStatement = $crlf
  2490. . $this->exportComment()
  2491. . $this->exportComment($comment1)
  2492. . $this->exportComment();
  2493. }
  2494. }
  2495. // comments for current table
  2496. if (! isset($GLOBALS['no_constraints_comments'])) {
  2497. $sqlStatement .= $crlf
  2498. . $this->exportComment()
  2499. . $this->exportComment(
  2500. $comment2 . ' ' . Util::backquoteCompat(
  2501. $tableAlias,
  2502. $compat,
  2503. isset($GLOBALS['sql_backquotes'])
  2504. )
  2505. )
  2506. . $this->exportComment();
  2507. }
  2508. return $sqlStatement;
  2509. }
  2510. }