Mysqldump.php 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318
  1. <?php
  2. /**
  3. * PHP version of mysqldump cli that comes with MySQL.
  4. *
  5. * Tags: mysql mysqldump pdo php7 php5 database php sql hhvm mariadb mysql-backup.
  6. *
  7. * @category Library
  8. * @package Ifsnop\Mysqldump
  9. * @author Diego Torres <ifsnop@github.com>
  10. * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
  11. * @link https://github.com/ifsnop/mysqldump-php
  12. *
  13. */
  14. namespace Ifsnop\Mysqldump;
  15. use Exception;
  16. use PDO;
  17. use PDOException;
  18. /**
  19. * Class Mysqldump.
  20. *
  21. * @category Library
  22. * @author Diego Torres <ifsnop@github.com>
  23. * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
  24. * @link https://github.com/ifsnop/mysqldump-php
  25. *
  26. */
  27. class Mysqldump
  28. {
  29. // Same as mysqldump.
  30. const MAXLINESIZE = 1000000;
  31. // List of available compression methods as constants.
  32. const GZIP = 'Gzip';
  33. const BZIP2 = 'Bzip2';
  34. const NONE = 'None';
  35. const GZIPSTREAM = 'Gzipstream';
  36. // List of available connection strings.
  37. const UTF8 = 'utf8';
  38. const UTF8MB4 = 'utf8mb4';
  39. /**
  40. * Database username.
  41. * @var string
  42. */
  43. public $user;
  44. /**
  45. * Database password.
  46. * @var string
  47. */
  48. public $pass;
  49. /**
  50. * Connection string for PDO.
  51. * @var string
  52. */
  53. public $dsn;
  54. /**
  55. * Destination filename, defaults to stdout.
  56. * @var string
  57. */
  58. public $fileName = 'php://stdout';
  59. // Internal stuff.
  60. private $tables = array();
  61. private $views = array();
  62. private $triggers = array();
  63. private $procedures = array();
  64. private $functions = array();
  65. private $events = array();
  66. private $dbHandler = null;
  67. private $dbType = "";
  68. private $compressManager;
  69. private $typeAdapter;
  70. private $dumpSettings = array();
  71. private $pdoSettings = array();
  72. private $version;
  73. private $tableColumnTypes = array();
  74. private $transformColumnValueCallable;
  75. /**
  76. * Database name, parsed from dsn.
  77. * @var string
  78. */
  79. private $dbName;
  80. /**
  81. * Host name, parsed from dsn.
  82. * @var string
  83. */
  84. private $host;
  85. /**
  86. * Dsn string parsed as an array.
  87. * @var array
  88. */
  89. private $dsnArray = array();
  90. /**
  91. * Keyed on table name, with the value as the conditions.
  92. * e.g. - 'users' => 'date_registered > NOW() - INTERVAL 6 MONTH'
  93. *
  94. * @var array
  95. */
  96. private $tableWheres = array();
  97. private $tableLimits = array();
  98. /**
  99. * Constructor of Mysqldump. Note that in the case of an SQLite database
  100. * connection, the filename must be in the $db parameter.
  101. *
  102. * @param string $dsn PDO DSN connection string
  103. * @param string $user SQL account username
  104. * @param string $pass SQL account password
  105. * @param array $dumpSettings SQL database settings
  106. * @param array $pdoSettings PDO configured attributes
  107. */
  108. public function __construct(
  109. $dsn = '',
  110. $user = '',
  111. $pass = '',
  112. $dumpSettings = array(),
  113. $pdoSettings = array()
  114. ) {
  115. $dumpSettingsDefault = array(
  116. 'include-tables' => array(),
  117. 'exclude-tables' => array(),
  118. 'compress' => Mysqldump::NONE,
  119. 'init_commands' => array(),
  120. 'no-data' => array(),
  121. 'reset-auto-increment' => false,
  122. 'add-drop-database' => false,
  123. 'add-drop-table' => false,
  124. 'add-drop-trigger' => true,
  125. 'add-locks' => true,
  126. 'complete-insert' => false,
  127. 'databases' => false,
  128. 'default-character-set' => Mysqldump::UTF8,
  129. 'disable-keys' => true,
  130. 'extended-insert' => true,
  131. 'events' => false,
  132. 'hex-blob' => true, /* faster than escaped content */
  133. 'insert-ignore' => false,
  134. 'net_buffer_length' => self::MAXLINESIZE,
  135. 'no-autocommit' => true,
  136. 'no-create-info' => false,
  137. 'lock-tables' => true,
  138. 'routines' => false,
  139. 'single-transaction' => true,
  140. 'skip-triggers' => false,
  141. 'skip-tz-utc' => false,
  142. 'skip-comments' => false,
  143. 'skip-dump-date' => false,
  144. 'skip-definer' => false,
  145. 'where' => '',
  146. 'include-views' => array(),
  147. /* deprecated */
  148. 'disable-foreign-keys-check' => true
  149. );
  150. $pdoSettingsDefault = array(
  151. PDO::ATTR_PERSISTENT => true,
  152. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  153. );
  154. $this->user = $user;
  155. $this->pass = $pass;
  156. $this->parseDsn($dsn);
  157. // This drops MYSQL dependency, only use the constant if it's defined.
  158. if ("mysql" === $this->dbType) {
  159. $pdoSettingsDefault[PDO::MYSQL_ATTR_USE_BUFFERED_QUERY] = false;
  160. }
  161. $this->pdoSettings = self::array_replace_recursive($pdoSettingsDefault, $pdoSettings);
  162. $this->dumpSettings = self::array_replace_recursive($dumpSettingsDefault, $dumpSettings);
  163. $this->dumpSettings['init_commands'][] = "SET NAMES ".$this->dumpSettings['default-character-set'];
  164. if (false === $this->dumpSettings['skip-tz-utc']) {
  165. $this->dumpSettings['init_commands'][] = "SET TIME_ZONE='+00:00'";
  166. }
  167. $diff = array_diff(array_keys($this->dumpSettings), array_keys($dumpSettingsDefault));
  168. if (count($diff) > 0) {
  169. throw new Exception("Unexpected value in dumpSettings: (".implode(",", $diff).")");
  170. }
  171. if (!is_array($this->dumpSettings['include-tables']) ||
  172. !is_array($this->dumpSettings['exclude-tables'])) {
  173. throw new Exception("Include-tables and exclude-tables should be arrays");
  174. }
  175. // Dump the same views as tables, mimic mysqldump behaviour
  176. //$this->dumpSettings['include-views'] = $this->dumpSettings['include-tables'];
  177. // Create a new compressManager to manage compressed output
  178. $this->compressManager = CompressManagerFactory::create($this->dumpSettings['compress']);
  179. }
  180. /**
  181. * Destructor of Mysqldump. Unsets dbHandlers and database objects.
  182. */
  183. public function __destruct()
  184. {
  185. $this->dbHandler = null;
  186. }
  187. /**
  188. * Custom array_replace_recursive to be used if PHP < 5.3
  189. * Replaces elements from passed arrays into the first array recursively.
  190. *
  191. * @param array $array1 The array in which elements are replaced
  192. * @param array $array2 The array from which elements will be extracted
  193. *
  194. * @return array Returns an array, or NULL if an error occurs.
  195. */
  196. public static function array_replace_recursive($array1, $array2)
  197. {
  198. if (function_exists('array_replace_recursive')) {
  199. return array_replace_recursive($array1, $array2);
  200. }
  201. foreach ($array2 as $key => $value) {
  202. if (is_array($value)) {
  203. $array1[$key] = self::array_replace_recursive($array1[$key], $value);
  204. } else {
  205. $array1[$key] = $value;
  206. }
  207. }
  208. return $array1;
  209. }
  210. /**
  211. * Keyed by table name, with the value as the conditions:
  212. * e.g. 'users' => 'date_registered > NOW() - INTERVAL 6 MONTH AND deleted=0'
  213. *
  214. * @param array $tableWheres
  215. */
  216. public function setTableWheres(array $tableWheres)
  217. {
  218. $this->tableWheres = $tableWheres;
  219. }
  220. /**
  221. * @param $tableName
  222. *
  223. * @return boolean|mixed
  224. */
  225. public function getTableWhere($tableName)
  226. {
  227. if (!empty($this->tableWheres[$tableName])) {
  228. return $this->tableWheres[$tableName];
  229. } elseif ($this->dumpSettings['where']) {
  230. return $this->dumpSettings['where'];
  231. }
  232. return false;
  233. }
  234. /**
  235. * Keyed by table name, with the value as the numeric limit:
  236. * e.g. 'users' => 3000
  237. *
  238. * @param array $tableLimits
  239. */
  240. public function setTableLimits(array $tableLimits)
  241. {
  242. $this->tableLimits = $tableLimits;
  243. }
  244. /**
  245. * Returns the LIMIT for the table. Must be numeric to be returned.
  246. * @param $tableName
  247. * @return boolean
  248. */
  249. public function getTableLimit($tableName)
  250. {
  251. if (empty($this->tableLimits[$tableName])) {
  252. return false;
  253. }
  254. $limit = $this->tableLimits[$tableName];
  255. if (!is_numeric($limit)) {
  256. return false;
  257. }
  258. return $limit;
  259. }
  260. /**
  261. * Parse DSN string and extract dbname value
  262. * Several examples of a DSN string
  263. * mysql:host=localhost;dbname=testdb
  264. * mysql:host=localhost;port=3307;dbname=testdb
  265. * mysql:unix_socket=/tmp/mysql.sock;dbname=testdb
  266. *
  267. * @param string $dsn dsn string to parse
  268. * @return boolean
  269. */
  270. private function parseDsn($dsn)
  271. {
  272. if (empty($dsn) || (false === ($pos = strpos($dsn, ":")))) {
  273. throw new Exception("Empty DSN string");
  274. }
  275. $this->dsn = $dsn;
  276. $this->dbType = strtolower(substr($dsn, 0, $pos)); // always returns a string
  277. if (empty($this->dbType)) {
  278. throw new Exception("Missing database type from DSN string");
  279. }
  280. $dsn = substr($dsn, $pos + 1);
  281. foreach (explode(";", $dsn) as $kvp) {
  282. $kvpArr = explode("=", $kvp);
  283. $this->dsnArray[strtolower($kvpArr[0])] = $kvpArr[1];
  284. }
  285. if (empty($this->dsnArray['host']) &&
  286. empty($this->dsnArray['unix_socket'])) {
  287. throw new Exception("Missing host from DSN string");
  288. }
  289. $this->host = (!empty($this->dsnArray['host'])) ?
  290. $this->dsnArray['host'] : $this->dsnArray['unix_socket'];
  291. if (empty($this->dsnArray['dbname'])) {
  292. throw new Exception("Missing database name from DSN string");
  293. }
  294. $this->dbName = $this->dsnArray['dbname'];
  295. return true;
  296. }
  297. /**
  298. * Connect with PDO.
  299. *
  300. * @return null
  301. */
  302. private function connect()
  303. {
  304. // Connecting with PDO.
  305. try {
  306. switch ($this->dbType) {
  307. case 'sqlite':
  308. $this->dbHandler = @new PDO("sqlite:".$this->dbName, null, null, $this->pdoSettings);
  309. break;
  310. case 'mysql':
  311. case 'pgsql':
  312. case 'dblib':
  313. $this->dbHandler = @new PDO(
  314. $this->dsn,
  315. $this->user,
  316. $this->pass,
  317. $this->pdoSettings
  318. );
  319. // Execute init commands once connected
  320. foreach ($this->dumpSettings['init_commands'] as $stmt) {
  321. $this->dbHandler->exec($stmt);
  322. }
  323. // Store server version
  324. $this->version = $this->dbHandler->getAttribute(PDO::ATTR_SERVER_VERSION);
  325. break;
  326. default:
  327. throw new Exception("Unsupported database type (".$this->dbType.")");
  328. }
  329. } catch (PDOException $e) {
  330. throw new Exception(
  331. "Connection to ".$this->dbType." failed with message: ".
  332. $e->getMessage()
  333. );
  334. }
  335. if (is_null($this->dbHandler)) {
  336. throw new Exception("Connection to ".$this->dbType."failed");
  337. }
  338. $this->dbHandler->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
  339. $this->typeAdapter = TypeAdapterFactory::create($this->dbType, $this->dbHandler, $this->dumpSettings);
  340. }
  341. /**
  342. * Primary function, triggers dumping.
  343. *
  344. * @param string $filename Name of file to write sql dump to
  345. * @return null
  346. * @throws \Exception
  347. */
  348. public function start($filename = '')
  349. {
  350. // Output file can be redefined here
  351. if (!empty($filename)) {
  352. $this->fileName = $filename;
  353. }
  354. // Connect to database
  355. $this->connect();
  356. // Create output file
  357. $this->compressManager->open($this->fileName);
  358. // Write some basic info to output file
  359. $this->compressManager->write($this->getDumpFileHeader());
  360. // Store server settings and use sanner defaults to dump
  361. $this->compressManager->write(
  362. $this->typeAdapter->backup_parameters()
  363. );
  364. if ($this->dumpSettings['databases']) {
  365. $this->compressManager->write(
  366. $this->typeAdapter->getDatabaseHeader($this->dbName)
  367. );
  368. if ($this->dumpSettings['add-drop-database']) {
  369. $this->compressManager->write(
  370. $this->typeAdapter->add_drop_database($this->dbName)
  371. );
  372. }
  373. }
  374. // Get table, view, trigger, procedures, functions and events structures from
  375. // database.
  376. $this->getDatabaseStructureTables();
  377. $this->getDatabaseStructureViews();
  378. $this->getDatabaseStructureTriggers();
  379. $this->getDatabaseStructureProcedures();
  380. $this->getDatabaseStructureFunctions();
  381. $this->getDatabaseStructureEvents();
  382. if ($this->dumpSettings['databases']) {
  383. $this->compressManager->write(
  384. $this->typeAdapter->databases($this->dbName)
  385. );
  386. }
  387. // If there still are some tables/views in include-tables array,
  388. // that means that some tables or views weren't found.
  389. // Give proper error and exit.
  390. // This check will be removed once include-tables supports regexps.
  391. if (0 < count($this->dumpSettings['include-tables'])) {
  392. $name = implode(",", $this->dumpSettings['include-tables']);
  393. throw new Exception("Table (".$name.") not found in database");
  394. }
  395. $this->exportTables();
  396. $this->exportTriggers();
  397. $this->exportFunctions();
  398. $this->exportProcedures();
  399. $this->exportViews();
  400. $this->exportEvents();
  401. // Restore saved parameters.
  402. $this->compressManager->write(
  403. $this->typeAdapter->restore_parameters()
  404. );
  405. // Write some stats to output file.
  406. $this->compressManager->write($this->getDumpFileFooter());
  407. // Close output file.
  408. $this->compressManager->close();
  409. return;
  410. }
  411. /**
  412. * Returns header for dump file.
  413. *
  414. * @return string
  415. */
  416. private function getDumpFileHeader()
  417. {
  418. $header = '';
  419. if (!$this->dumpSettings['skip-comments']) {
  420. // Some info about software, source and time
  421. $header = "-- mysqldump-php https://github.com/ifsnop/mysqldump-php".PHP_EOL.
  422. "--".PHP_EOL.
  423. "-- Host: {$this->host}\tDatabase: {$this->dbName}".PHP_EOL.
  424. "-- ------------------------------------------------------".PHP_EOL;
  425. if (!empty($this->version)) {
  426. $header .= "-- Server version \t".$this->version.PHP_EOL;
  427. }
  428. if (!$this->dumpSettings['skip-dump-date']) {
  429. $header .= "-- Date: ".date('r').PHP_EOL.PHP_EOL;
  430. }
  431. }
  432. return $header;
  433. }
  434. /**
  435. * Returns footer for dump file.
  436. *
  437. * @return string
  438. */
  439. private function getDumpFileFooter()
  440. {
  441. $footer = '';
  442. if (!$this->dumpSettings['skip-comments']) {
  443. $footer .= '-- Dump completed';
  444. if (!$this->dumpSettings['skip-dump-date']) {
  445. $footer .= ' on: '.date('r');
  446. }
  447. $footer .= PHP_EOL;
  448. }
  449. return $footer;
  450. }
  451. /**
  452. * Reads table names from database.
  453. * Fills $this->tables array so they will be dumped later.
  454. *
  455. * @return null
  456. */
  457. private function getDatabaseStructureTables()
  458. {
  459. // Listing all tables from database
  460. if (empty($this->dumpSettings['include-tables'])) {
  461. // include all tables for now, blacklisting happens later
  462. foreach ($this->dbHandler->query($this->typeAdapter->show_tables($this->dbName)) as $row) {
  463. array_push($this->tables, current($row));
  464. }
  465. } else {
  466. // include only the tables mentioned in include-tables
  467. foreach ($this->dbHandler->query($this->typeAdapter->show_tables($this->dbName)) as $row) {
  468. if (in_array(current($row), $this->dumpSettings['include-tables'], true)) {
  469. array_push($this->tables, current($row));
  470. $elem = array_search(
  471. current($row),
  472. $this->dumpSettings['include-tables']
  473. );
  474. unset($this->dumpSettings['include-tables'][$elem]);
  475. }
  476. }
  477. }
  478. return;
  479. }
  480. /**
  481. * Reads view names from database.
  482. * Fills $this->tables array so they will be dumped later.
  483. *
  484. * @return null
  485. */
  486. private function getDatabaseStructureViews()
  487. {
  488. // Listing all views from database
  489. if (empty($this->dumpSettings['include-views'])) {
  490. // include all views for now, blacklisting happens later
  491. foreach ($this->dbHandler->query($this->typeAdapter->show_views($this->dbName)) as $row) {
  492. array_push($this->views, current($row));
  493. }
  494. } else {
  495. // include only the tables mentioned in include-tables
  496. foreach ($this->dbHandler->query($this->typeAdapter->show_views($this->dbName)) as $row) {
  497. if (in_array(current($row), $this->dumpSettings['include-views'], true)) {
  498. array_push($this->views, current($row));
  499. $elem = array_search(
  500. current($row),
  501. $this->dumpSettings['include-views']
  502. );
  503. unset($this->dumpSettings['include-views'][$elem]);
  504. }
  505. }
  506. }
  507. return;
  508. }
  509. /**
  510. * Reads trigger names from database.
  511. * Fills $this->tables array so they will be dumped later.
  512. *
  513. * @return null
  514. */
  515. private function getDatabaseStructureTriggers()
  516. {
  517. // Listing all triggers from database
  518. if (false === $this->dumpSettings['skip-triggers']) {
  519. foreach ($this->dbHandler->query($this->typeAdapter->show_triggers($this->dbName)) as $row) {
  520. array_push($this->triggers, $row['Trigger']);
  521. }
  522. }
  523. return;
  524. }
  525. /**
  526. * Reads procedure names from database.
  527. * Fills $this->tables array so they will be dumped later.
  528. *
  529. * @return null
  530. */
  531. private function getDatabaseStructureProcedures()
  532. {
  533. // Listing all procedures from database
  534. if ($this->dumpSettings['routines']) {
  535. foreach ($this->dbHandler->query($this->typeAdapter->show_procedures($this->dbName)) as $row) {
  536. array_push($this->procedures, $row['procedure_name']);
  537. }
  538. }
  539. return;
  540. }
  541. /**
  542. * Reads functions names from database.
  543. * Fills $this->tables array so they will be dumped later.
  544. *
  545. * @return null
  546. */
  547. private function getDatabaseStructureFunctions()
  548. {
  549. // Listing all functions from database
  550. if ($this->dumpSettings['routines']) {
  551. foreach ($this->dbHandler->query($this->typeAdapter->show_functions($this->dbName)) as $row) {
  552. array_push($this->functions, $row['function_name']);
  553. }
  554. }
  555. return;
  556. }
  557. /**
  558. * Reads event names from database.
  559. * Fills $this->tables array so they will be dumped later.
  560. *
  561. * @return null
  562. */
  563. private function getDatabaseStructureEvents()
  564. {
  565. // Listing all events from database
  566. if ($this->dumpSettings['events']) {
  567. foreach ($this->dbHandler->query($this->typeAdapter->show_events($this->dbName)) as $row) {
  568. array_push($this->events, $row['event_name']);
  569. }
  570. }
  571. return;
  572. }
  573. /**
  574. * Compare if $table name matches with a definition inside $arr
  575. * @param $table string
  576. * @param $arr array with strings or patterns
  577. * @return boolean
  578. */
  579. private function matches($table, $arr)
  580. {
  581. $match = false;
  582. foreach ($arr as $pattern) {
  583. if ('/' != $pattern[0]) {
  584. continue;
  585. }
  586. if (1 == preg_match($pattern, $table)) {
  587. $match = true;
  588. }
  589. }
  590. return in_array($table, $arr) || $match;
  591. }
  592. /**
  593. * Exports all the tables selected from database
  594. *
  595. * @return null
  596. */
  597. private function exportTables()
  598. {
  599. // Exporting tables one by one
  600. foreach ($this->tables as $table) {
  601. if ($this->matches($table, $this->dumpSettings['exclude-tables'])) {
  602. continue;
  603. }
  604. $this->getTableStructure($table);
  605. if (false === $this->dumpSettings['no-data']) { // don't break compatibility with old trigger
  606. $this->listValues($table);
  607. } elseif (true === $this->dumpSettings['no-data']
  608. || $this->matches($table, $this->dumpSettings['no-data'])) {
  609. continue;
  610. } else {
  611. $this->listValues($table);
  612. }
  613. }
  614. }
  615. /**
  616. * Exports all the views found in database
  617. *
  618. * @return null
  619. */
  620. private function exportViews()
  621. {
  622. if (false === $this->dumpSettings['no-create-info']) {
  623. // Exporting views one by one
  624. foreach ($this->views as $view) {
  625. if ($this->matches($view, $this->dumpSettings['exclude-tables'])) {
  626. continue;
  627. }
  628. $this->tableColumnTypes[$view] = $this->getTableColumnTypes($view);
  629. $this->getViewStructureTable($view);
  630. }
  631. foreach ($this->views as $view) {
  632. if ($this->matches($view, $this->dumpSettings['exclude-tables'])) {
  633. continue;
  634. }
  635. $this->getViewStructureView($view);
  636. }
  637. }
  638. }
  639. /**
  640. * Exports all the triggers found in database
  641. *
  642. * @return null
  643. */
  644. private function exportTriggers()
  645. {
  646. // Exporting triggers one by one
  647. foreach ($this->triggers as $trigger) {
  648. $this->getTriggerStructure($trigger);
  649. }
  650. }
  651. /**
  652. * Exports all the procedures found in database
  653. *
  654. * @return null
  655. */
  656. private function exportProcedures()
  657. {
  658. // Exporting triggers one by one
  659. foreach ($this->procedures as $procedure) {
  660. $this->getProcedureStructure($procedure);
  661. }
  662. }
  663. /**
  664. * Exports all the functions found in database
  665. *
  666. * @return null
  667. */
  668. private function exportFunctions()
  669. {
  670. // Exporting triggers one by one
  671. foreach ($this->functions as $function) {
  672. $this->getFunctionStructure($function);
  673. }
  674. }
  675. /**
  676. * Exports all the events found in database
  677. *
  678. * @return null
  679. */
  680. private function exportEvents()
  681. {
  682. // Exporting triggers one by one
  683. foreach ($this->events as $event) {
  684. $this->getEventStructure($event);
  685. }
  686. }
  687. /**
  688. * Table structure extractor
  689. *
  690. * @todo move specific mysql code to typeAdapter
  691. * @param string $tableName Name of table to export
  692. * @return null
  693. */
  694. private function getTableStructure($tableName)
  695. {
  696. if (!$this->dumpSettings['no-create-info']) {
  697. $ret = '';
  698. if (!$this->dumpSettings['skip-comments']) {
  699. $ret = "--".PHP_EOL.
  700. "-- Table structure for table `$tableName`".PHP_EOL.
  701. "--".PHP_EOL.PHP_EOL;
  702. }
  703. $stmt = $this->typeAdapter->show_create_table($tableName);
  704. foreach ($this->dbHandler->query($stmt) as $r) {
  705. $this->compressManager->write($ret);
  706. if ($this->dumpSettings['add-drop-table']) {
  707. $this->compressManager->write(
  708. $this->typeAdapter->drop_table($tableName)
  709. );
  710. }
  711. $this->compressManager->write(
  712. $this->typeAdapter->create_table($r)
  713. );
  714. break;
  715. }
  716. }
  717. $this->tableColumnTypes[$tableName] = $this->getTableColumnTypes($tableName);
  718. return;
  719. }
  720. /**
  721. * Store column types to create data dumps and for Stand-In tables
  722. *
  723. * @param string $tableName Name of table to export
  724. * @return array type column types detailed
  725. */
  726. private function getTableColumnTypes($tableName)
  727. {
  728. $columnTypes = array();
  729. $columns = $this->dbHandler->query(
  730. $this->typeAdapter->show_columns($tableName)
  731. );
  732. $columns->setFetchMode(PDO::FETCH_ASSOC);
  733. foreach ($columns as $key => $col) {
  734. $types = $this->typeAdapter->parseColumnType($col);
  735. $columnTypes[$col['Field']] = array(
  736. 'is_numeric'=> $types['is_numeric'],
  737. 'is_blob' => $types['is_blob'],
  738. 'type' => $types['type'],
  739. 'type_sql' => $col['Type'],
  740. 'is_virtual' => $types['is_virtual']
  741. );
  742. }
  743. return $columnTypes;
  744. }
  745. /**
  746. * View structure extractor, create table (avoids cyclic references)
  747. *
  748. * @todo move mysql specific code to typeAdapter
  749. * @param string $viewName Name of view to export
  750. * @return null
  751. */
  752. private function getViewStructureTable($viewName)
  753. {
  754. if (!$this->dumpSettings['skip-comments']) {
  755. $ret = "--".PHP_EOL.
  756. "-- Stand-In structure for view `${viewName}`".PHP_EOL.
  757. "--".PHP_EOL.PHP_EOL;
  758. $this->compressManager->write($ret);
  759. }
  760. $stmt = $this->typeAdapter->show_create_view($viewName);
  761. // create views as tables, to resolve dependencies
  762. foreach ($this->dbHandler->query($stmt) as $r) {
  763. if ($this->dumpSettings['add-drop-table']) {
  764. $this->compressManager->write(
  765. $this->typeAdapter->drop_view($viewName)
  766. );
  767. }
  768. $this->compressManager->write(
  769. $this->createStandInTable($viewName)
  770. );
  771. break;
  772. }
  773. }
  774. /**
  775. * Write a create table statement for the table Stand-In, show create
  776. * table would return a create algorithm when used on a view
  777. *
  778. * @param string $viewName Name of view to export
  779. * @return string create statement
  780. */
  781. public function createStandInTable($viewName)
  782. {
  783. $ret = array();
  784. foreach ($this->tableColumnTypes[$viewName] as $k => $v) {
  785. $ret[] = "`${k}` ${v['type_sql']}";
  786. }
  787. $ret = implode(PHP_EOL.",", $ret);
  788. $ret = "CREATE TABLE IF NOT EXISTS `$viewName` (".
  789. PHP_EOL.$ret.PHP_EOL.");".PHP_EOL;
  790. return $ret;
  791. }
  792. /**
  793. * View structure extractor, create view
  794. *
  795. * @todo move mysql specific code to typeAdapter
  796. * @param string $viewName Name of view to export
  797. * @return null
  798. */
  799. private function getViewStructureView($viewName)
  800. {
  801. if (!$this->dumpSettings['skip-comments']) {
  802. $ret = "--".PHP_EOL.
  803. "-- View structure for view `${viewName}`".PHP_EOL.
  804. "--".PHP_EOL.PHP_EOL;
  805. $this->compressManager->write($ret);
  806. }
  807. $stmt = $this->typeAdapter->show_create_view($viewName);
  808. // create views, to resolve dependencies
  809. // replacing tables with views
  810. foreach ($this->dbHandler->query($stmt) as $r) {
  811. // because we must replace table with view, we should delete it
  812. $this->compressManager->write(
  813. $this->typeAdapter->drop_view($viewName)
  814. );
  815. $this->compressManager->write(
  816. $this->typeAdapter->create_view($r)
  817. );
  818. break;
  819. }
  820. }
  821. /**
  822. * Trigger structure extractor
  823. *
  824. * @param string $triggerName Name of trigger to export
  825. * @return null
  826. */
  827. private function getTriggerStructure($triggerName)
  828. {
  829. $stmt = $this->typeAdapter->show_create_trigger($triggerName);
  830. foreach ($this->dbHandler->query($stmt) as $r) {
  831. if ($this->dumpSettings['add-drop-trigger']) {
  832. $this->compressManager->write(
  833. $this->typeAdapter->add_drop_trigger($triggerName)
  834. );
  835. }
  836. $this->compressManager->write(
  837. $this->typeAdapter->create_trigger($r)
  838. );
  839. return;
  840. }
  841. }
  842. /**
  843. * Procedure structure extractor
  844. *
  845. * @param string $procedureName Name of procedure to export
  846. * @return null
  847. */
  848. private function getProcedureStructure($procedureName)
  849. {
  850. if (!$this->dumpSettings['skip-comments']) {
  851. $ret = "--".PHP_EOL.
  852. "-- Dumping routines for database '".$this->dbName."'".PHP_EOL.
  853. "--".PHP_EOL.PHP_EOL;
  854. $this->compressManager->write($ret);
  855. }
  856. $stmt = $this->typeAdapter->show_create_procedure($procedureName);
  857. foreach ($this->dbHandler->query($stmt) as $r) {
  858. $this->compressManager->write(
  859. $this->typeAdapter->create_procedure($r)
  860. );
  861. return;
  862. }
  863. }
  864. /**
  865. * Function structure extractor
  866. *
  867. * @param string $functionName Name of function to export
  868. * @return null
  869. */
  870. private function getFunctionStructure($functionName)
  871. {
  872. if (!$this->dumpSettings['skip-comments']) {
  873. $ret = "--".PHP_EOL.
  874. "-- Dumping routines for database '".$this->dbName."'".PHP_EOL.
  875. "--".PHP_EOL.PHP_EOL;
  876. $this->compressManager->write($ret);
  877. }
  878. $stmt = $this->typeAdapter->show_create_function($functionName);
  879. foreach ($this->dbHandler->query($stmt) as $r) {
  880. $this->compressManager->write(
  881. $this->typeAdapter->create_function($r)
  882. );
  883. return;
  884. }
  885. }
  886. /**
  887. * Event structure extractor
  888. *
  889. * @param string $eventName Name of event to export
  890. * @return null
  891. */
  892. private function getEventStructure($eventName)
  893. {
  894. if (!$this->dumpSettings['skip-comments']) {
  895. $ret = "--".PHP_EOL.
  896. "-- Dumping events for database '".$this->dbName."'".PHP_EOL.
  897. "--".PHP_EOL.PHP_EOL;
  898. $this->compressManager->write($ret);
  899. }
  900. $stmt = $this->typeAdapter->show_create_event($eventName);
  901. foreach ($this->dbHandler->query($stmt) as $r) {
  902. $this->compressManager->write(
  903. $this->typeAdapter->create_event($r)
  904. );
  905. return;
  906. }
  907. }
  908. /**
  909. * Prepare values for output
  910. *
  911. * @param string $tableName Name of table which contains rows
  912. * @param array $row Associative array of column names and values to be
  913. * quoted
  914. *
  915. * @return array
  916. */
  917. private function prepareColumnValues($tableName, $row)
  918. {
  919. $ret = array();
  920. $columnTypes = $this->tableColumnTypes[$tableName];
  921. foreach ($row as $colName => $colValue) {
  922. $colValue = $this->hookTransformColumnValue($tableName, $colName, $colValue, $row);
  923. $ret[] = $this->escape($colValue, $columnTypes[$colName]);
  924. }
  925. return $ret;
  926. }
  927. /**
  928. * Escape values with quotes when needed
  929. *
  930. * @param string $tableName Name of table which contains rows
  931. * @param array $row Associative array of column names and values to be quoted
  932. *
  933. * @return string
  934. */
  935. private function escape($colValue, $colType)
  936. {
  937. if (is_null($colValue)) {
  938. return "NULL";
  939. } elseif ($this->dumpSettings['hex-blob'] && $colType['is_blob']) {
  940. if ($colType['type'] == 'bit' || !empty($colValue)) {
  941. return "0x${colValue}";
  942. } else {
  943. return "''";
  944. }
  945. } elseif ($colType['is_numeric']) {
  946. return $colValue;
  947. }
  948. return $this->dbHandler->quote($colValue);
  949. }
  950. /**
  951. * Set a callable that will will be used to transform column values.
  952. *
  953. * @param callable $callable
  954. *
  955. * @return void
  956. */
  957. public function setTransformColumnValueHook($callable)
  958. {
  959. $this->transformColumnValueCallable = $callable;
  960. }
  961. /**
  962. * Give extending classes an opportunity to transform column values
  963. *
  964. * @param string $tableName Name of table which contains rows
  965. * @param string $colName Name of the column in question
  966. * @param string $colValue Value of the column in question
  967. *
  968. * @return string
  969. */
  970. protected function hookTransformColumnValue($tableName, $colName, $colValue, $row)
  971. {
  972. if (!$this->transformColumnValueCallable) {
  973. return $colValue;
  974. }
  975. return call_user_func_array($this->transformColumnValueCallable, array(
  976. $tableName,
  977. $colName,
  978. $colValue,
  979. $row
  980. ));
  981. }
  982. /**
  983. * Table rows extractor
  984. *
  985. * @param string $tableName Name of table to export
  986. *
  987. * @return null
  988. */
  989. private function listValues($tableName)
  990. {
  991. $this->prepareListValues($tableName);
  992. $onlyOnce = true;
  993. $lineSize = 0;
  994. // colStmt is used to form a query to obtain row values
  995. $colStmt = $this->getColumnStmt($tableName);
  996. // colNames is used to get the name of the columns when using complete-insert
  997. if ($this->dumpSettings['complete-insert']) {
  998. $colNames = $this->getColumnNames($tableName);
  999. }
  1000. $stmt = "SELECT ".implode(",", $colStmt)." FROM `$tableName`";
  1001. // Table specific conditions override the default 'where'
  1002. $condition = $this->getTableWhere($tableName);
  1003. if ($condition) {
  1004. $stmt .= " WHERE {$condition}";
  1005. }
  1006. $limit = $this->getTableLimit($tableName);
  1007. if ($limit) {
  1008. $stmt .= " LIMIT {$limit}";
  1009. }
  1010. $resultSet = $this->dbHandler->query($stmt);
  1011. $resultSet->setFetchMode(PDO::FETCH_ASSOC);
  1012. $ignore = $this->dumpSettings['insert-ignore'] ? ' IGNORE' : '';
  1013. $count = 0;
  1014. foreach ($resultSet as $row) {
  1015. $count++;
  1016. $vals = $this->prepareColumnValues($tableName, $row);
  1017. if ($onlyOnce || !$this->dumpSettings['extended-insert']) {
  1018. if ($this->dumpSettings['complete-insert']) {
  1019. $lineSize += $this->compressManager->write(
  1020. "INSERT$ignore INTO `$tableName` (".
  1021. implode(", ", $colNames).
  1022. ") VALUES (".implode(",", $vals).")"
  1023. );
  1024. } else {
  1025. $lineSize += $this->compressManager->write(
  1026. "INSERT$ignore INTO `$tableName` VALUES (".implode(",", $vals).")"
  1027. );
  1028. }
  1029. $onlyOnce = false;
  1030. } else {
  1031. $lineSize += $this->compressManager->write(",(".implode(",", $vals).")");
  1032. }
  1033. if (($lineSize > $this->dumpSettings['net_buffer_length']) ||
  1034. !$this->dumpSettings['extended-insert']) {
  1035. $onlyOnce = true;
  1036. $lineSize = $this->compressManager->write(";".PHP_EOL);
  1037. }
  1038. }
  1039. $resultSet->closeCursor();
  1040. if (!$onlyOnce) {
  1041. $this->compressManager->write(";".PHP_EOL);
  1042. }
  1043. $this->endListValues($tableName, $count);
  1044. }
  1045. /**
  1046. * Table rows extractor, append information prior to dump
  1047. *
  1048. * @param string $tableName Name of table to export
  1049. *
  1050. * @return null
  1051. */
  1052. public function prepareListValues($tableName)
  1053. {
  1054. if (!$this->dumpSettings['skip-comments']) {
  1055. $this->compressManager->write(
  1056. "--".PHP_EOL.
  1057. "-- Dumping data for table `$tableName`".PHP_EOL.
  1058. "--".PHP_EOL.PHP_EOL
  1059. );
  1060. }
  1061. if ($this->dumpSettings['single-transaction']) {
  1062. $this->dbHandler->exec($this->typeAdapter->setup_transaction());
  1063. $this->dbHandler->exec($this->typeAdapter->start_transaction());
  1064. }
  1065. if ($this->dumpSettings['lock-tables'] && !$this->dumpSettings['single-transaction']) {
  1066. $this->typeAdapter->lock_table($tableName);
  1067. }
  1068. if ($this->dumpSettings['add-locks']) {
  1069. $this->compressManager->write(
  1070. $this->typeAdapter->start_add_lock_table($tableName)
  1071. );
  1072. }
  1073. if ($this->dumpSettings['disable-keys']) {
  1074. $this->compressManager->write(
  1075. $this->typeAdapter->start_add_disable_keys($tableName)
  1076. );
  1077. }
  1078. // Disable autocommit for faster reload
  1079. if ($this->dumpSettings['no-autocommit']) {
  1080. $this->compressManager->write(
  1081. $this->typeAdapter->start_disable_autocommit()
  1082. );
  1083. }
  1084. return;
  1085. }
  1086. /**
  1087. * Table rows extractor, close locks and commits after dump
  1088. *
  1089. * @param string $tableName Name of table to export.
  1090. * @param integer $count Number of rows inserted.
  1091. *
  1092. * @return void
  1093. */
  1094. public function endListValues($tableName, $count = 0)
  1095. {
  1096. if ($this->dumpSettings['disable-keys']) {
  1097. $this->compressManager->write(
  1098. $this->typeAdapter->end_add_disable_keys($tableName)
  1099. );
  1100. }
  1101. if ($this->dumpSettings['add-locks']) {
  1102. $this->compressManager->write(
  1103. $this->typeAdapter->end_add_lock_table($tableName)
  1104. );
  1105. }
  1106. if ($this->dumpSettings['single-transaction']) {
  1107. $this->dbHandler->exec($this->typeAdapter->commit_transaction());
  1108. }
  1109. if ($this->dumpSettings['lock-tables'] && !$this->dumpSettings['single-transaction']) {
  1110. $this->typeAdapter->unlock_table($tableName);
  1111. }
  1112. // Commit to enable autocommit
  1113. if ($this->dumpSettings['no-autocommit']) {
  1114. $this->compressManager->write(
  1115. $this->typeAdapter->end_disable_autocommit()
  1116. );
  1117. }
  1118. $this->compressManager->write(PHP_EOL);
  1119. if (!$this->dumpSettings['skip-comments']) {
  1120. $this->compressManager->write(
  1121. "-- Dumped table `".$tableName."` with $count row(s)".PHP_EOL.
  1122. '--'.PHP_EOL.PHP_EOL
  1123. );
  1124. }
  1125. return;
  1126. }
  1127. /**
  1128. * Build SQL List of all columns on current table which will be used for selecting
  1129. *
  1130. * @param string $tableName Name of table to get columns
  1131. *
  1132. * @return array SQL sentence with columns for select
  1133. */
  1134. public function getColumnStmt($tableName)
  1135. {
  1136. $colStmt = array();
  1137. foreach ($this->tableColumnTypes[$tableName] as $colName => $colType) {
  1138. if ($colType['type'] == 'bit' && $this->dumpSettings['hex-blob']) {
  1139. $colStmt[] = "LPAD(HEX(`${colName}`),2,'0') AS `${colName}`";
  1140. } elseif ($colType['is_blob'] && $this->dumpSettings['hex-blob']) {
  1141. $colStmt[] = "HEX(`${colName}`) AS `${colName}`";
  1142. } elseif ($colType['is_virtual']) {
  1143. $this->dumpSettings['complete-insert'] = true;
  1144. continue;
  1145. } else {
  1146. $colStmt[] = "`${colName}`";
  1147. }
  1148. }
  1149. return $colStmt;
  1150. }
  1151. /**
  1152. * Build SQL List of all columns on current table which will be used for inserting
  1153. *
  1154. * @param string $tableName Name of table to get columns
  1155. *
  1156. * @return array columns for sql sentence for insert
  1157. */
  1158. public function getColumnNames($tableName)
  1159. {
  1160. $colNames = array();
  1161. foreach ($this->tableColumnTypes[$tableName] as $colName => $colType) {
  1162. if ($colType['is_virtual']) {
  1163. $this->dumpSettings['complete-insert'] = true;
  1164. continue;
  1165. } else {
  1166. $colNames[] = "`${colName}`";
  1167. }
  1168. }
  1169. return $colNames;
  1170. }
  1171. }
  1172. /**
  1173. * Enum with all available compression methods
  1174. *
  1175. */
  1176. abstract class CompressMethod
  1177. {
  1178. public static $enums = array(
  1179. Mysqldump::NONE,
  1180. Mysqldump::GZIP,
  1181. Mysqldump::BZIP2,
  1182. Mysqldump::GZIPSTREAM,
  1183. );
  1184. /**
  1185. * @param string $c
  1186. * @return boolean
  1187. */
  1188. public static function isValid($c)
  1189. {
  1190. return in_array($c, self::$enums);
  1191. }
  1192. }
  1193. abstract class CompressManagerFactory
  1194. {
  1195. /**
  1196. * @param string $c
  1197. * @return CompressBzip2|CompressGzip|CompressNone
  1198. */
  1199. public static function create($c)
  1200. {
  1201. $c = ucfirst(strtolower($c));
  1202. if (!CompressMethod::isValid($c)) {
  1203. throw new Exception("Compression method ($c) is not defined yet");
  1204. }
  1205. $method = __NAMESPACE__."\\"."Compress".$c;
  1206. return new $method;
  1207. }
  1208. }
  1209. class CompressBzip2 extends CompressManagerFactory
  1210. {
  1211. private $fileHandler = null;
  1212. public function __construct()
  1213. {
  1214. if (!function_exists("bzopen")) {
  1215. throw new Exception("Compression is enabled, but bzip2 lib is not installed or configured properly");
  1216. }
  1217. }
  1218. /**
  1219. * @param string $filename
  1220. */
  1221. public function open($filename)
  1222. {
  1223. $this->fileHandler = bzopen($filename, "w");
  1224. if (false === $this->fileHandler) {
  1225. throw new Exception("Output file is not writable");
  1226. }
  1227. return true;
  1228. }
  1229. public function write($str)
  1230. {
  1231. $bytesWritten = bzwrite($this->fileHandler, $str);
  1232. if (false === $bytesWritten) {
  1233. throw new Exception("Writting to file failed! Probably, there is no more free space left?");
  1234. }
  1235. return $bytesWritten;
  1236. }
  1237. public function close()
  1238. {
  1239. return bzclose($this->fileHandler);
  1240. }
  1241. }
  1242. class CompressGzip extends CompressManagerFactory
  1243. {
  1244. private $fileHandler = null;
  1245. public function __construct()
  1246. {
  1247. if (!function_exists("gzopen")) {
  1248. throw new Exception("Compression is enabled, but gzip lib is not installed or configured properly");
  1249. }
  1250. }
  1251. /**
  1252. * @param string $filename
  1253. */
  1254. public function open($filename)
  1255. {
  1256. $this->fileHandler = gzopen($filename, "wb");
  1257. if (false === $this->fileHandler) {
  1258. throw new Exception("Output file is not writable");
  1259. }
  1260. return true;
  1261. }
  1262. public function write($str)
  1263. {
  1264. $bytesWritten = gzwrite($this->fileHandler, $str);
  1265. if (false === $bytesWritten) {
  1266. throw new Exception("Writting to file failed! Probably, there is no more free space left?");
  1267. }
  1268. return $bytesWritten;
  1269. }
  1270. public function close()
  1271. {
  1272. return gzclose($this->fileHandler);
  1273. }
  1274. }
  1275. class CompressNone extends CompressManagerFactory
  1276. {
  1277. private $fileHandler = null;
  1278. /**
  1279. * @param string $filename
  1280. */
  1281. public function open($filename)
  1282. {
  1283. $this->fileHandler = fopen($filename, "wb");
  1284. if (false === $this->fileHandler) {
  1285. throw new Exception("Output file is not writable");
  1286. }
  1287. return true;
  1288. }
  1289. public function write($str)
  1290. {
  1291. $bytesWritten = fwrite($this->fileHandler, $str);
  1292. if (false === $bytesWritten) {
  1293. throw new Exception("Writting to file failed! Probably, there is no more free space left?");
  1294. }
  1295. return $bytesWritten;
  1296. }
  1297. public function close()
  1298. {
  1299. return fclose($this->fileHandler);
  1300. }
  1301. }
  1302. class CompressGzipstream extends CompressManagerFactory
  1303. {
  1304. private $fileHandler = null;
  1305. private $compressContext;
  1306. /**
  1307. * @param string $filename
  1308. */
  1309. public function open($filename)
  1310. {
  1311. $this->fileHandler = fopen($filename, "wb");
  1312. if (false === $this->fileHandler) {
  1313. throw new Exception("Output file is not writable");
  1314. }
  1315. $this->compressContext = deflate_init(ZLIB_ENCODING_GZIP, array('level' => 9));
  1316. return true;
  1317. }
  1318. public function write($str)
  1319. {
  1320. $bytesWritten = fwrite($this->fileHandler, deflate_add($this->compressContext, $str, ZLIB_NO_FLUSH));
  1321. if (false === $bytesWritten) {
  1322. throw new Exception("Writting to file failed! Probably, there is no more free space left?");
  1323. }
  1324. return $bytesWritten;
  1325. }
  1326. public function close()
  1327. {
  1328. fwrite($this->fileHandler, deflate_add($this->compressContext, '', ZLIB_FINISH));
  1329. return fclose($this->fileHandler);
  1330. }
  1331. }
  1332. /**
  1333. * Enum with all available TypeAdapter implementations
  1334. *
  1335. */
  1336. abstract class TypeAdapter
  1337. {
  1338. public static $enums = array(
  1339. "Sqlite",
  1340. "Mysql"
  1341. );
  1342. /**
  1343. * @param string $c
  1344. * @return boolean
  1345. */
  1346. public static function isValid($c)
  1347. {
  1348. return in_array($c, self::$enums);
  1349. }
  1350. }
  1351. /**
  1352. * TypeAdapter Factory
  1353. *
  1354. */
  1355. abstract class TypeAdapterFactory
  1356. {
  1357. protected $dbHandler = null;
  1358. protected $dumpSettings = array();
  1359. /**
  1360. * @param string $c Type of database factory to create (Mysql, Sqlite,...)
  1361. * @param PDO $dbHandler
  1362. */
  1363. public static function create($c, $dbHandler = null, $dumpSettings = array())
  1364. {
  1365. $c = ucfirst(strtolower($c));
  1366. if (!TypeAdapter::isValid($c)) {
  1367. throw new Exception("Database type support for ($c) not yet available");
  1368. }
  1369. $method = __NAMESPACE__."\\"."TypeAdapter".$c;
  1370. return new $method($dbHandler, $dumpSettings);
  1371. }
  1372. public function __construct($dbHandler = null, $dumpSettings = array())
  1373. {
  1374. $this->dbHandler = $dbHandler;
  1375. $this->dumpSettings = $dumpSettings;
  1376. }
  1377. /**
  1378. * function databases Add sql to create and use database
  1379. * @todo make it do something with sqlite
  1380. */
  1381. public function databases()
  1382. {
  1383. return "";
  1384. }
  1385. public function show_create_table($tableName)
  1386. {
  1387. return "SELECT tbl_name as 'Table', sql as 'Create Table' ".
  1388. "FROM sqlite_master ".
  1389. "WHERE type='table' AND tbl_name='$tableName'";
  1390. }
  1391. /**
  1392. * function create_table Get table creation code from database
  1393. * @todo make it do something with sqlite
  1394. */
  1395. public function create_table($row)
  1396. {
  1397. return "";
  1398. }
  1399. public function show_create_view($viewName)
  1400. {
  1401. return "SELECT tbl_name as 'View', sql as 'Create View' ".
  1402. "FROM sqlite_master ".
  1403. "WHERE type='view' AND tbl_name='$viewName'";
  1404. }
  1405. /**
  1406. * function create_view Get view creation code from database
  1407. * @todo make it do something with sqlite
  1408. */
  1409. public function create_view($row)
  1410. {
  1411. return "";
  1412. }
  1413. /**
  1414. * function show_create_trigger Get trigger creation code from database
  1415. * @todo make it do something with sqlite
  1416. */
  1417. public function show_create_trigger($triggerName)
  1418. {
  1419. return "";
  1420. }
  1421. /**
  1422. * function create_trigger Modify trigger code, add delimiters, etc
  1423. * @todo make it do something with sqlite
  1424. */
  1425. public function create_trigger($triggerName)
  1426. {
  1427. return "";
  1428. }
  1429. /**
  1430. * function create_procedure Modify procedure code, add delimiters, etc
  1431. * @todo make it do something with sqlite
  1432. */
  1433. public function create_procedure($procedureName)
  1434. {
  1435. return "";
  1436. }
  1437. /**
  1438. * function create_function Modify function code, add delimiters, etc
  1439. * @todo make it do something with sqlite
  1440. */
  1441. public function create_function($functionName)
  1442. {
  1443. return "";
  1444. }
  1445. public function show_tables()
  1446. {
  1447. return "SELECT tbl_name FROM sqlite_master WHERE type='table'";
  1448. }
  1449. public function show_views()
  1450. {
  1451. return "SELECT tbl_name FROM sqlite_master WHERE type='view'";
  1452. }
  1453. public function show_triggers()
  1454. {
  1455. return "SELECT name FROM sqlite_master WHERE type='trigger'";
  1456. }
  1457. public function show_columns()
  1458. {
  1459. if (func_num_args() != 1) {
  1460. return "";
  1461. }
  1462. $args = func_get_args();
  1463. return "pragma table_info(${args[0]})";
  1464. }
  1465. public function show_procedures()
  1466. {
  1467. return "";
  1468. }
  1469. public function show_functions()
  1470. {
  1471. return "";
  1472. }
  1473. public function show_events()
  1474. {
  1475. return "";
  1476. }
  1477. public function setup_transaction()
  1478. {
  1479. return "";
  1480. }
  1481. public function start_transaction()
  1482. {
  1483. return "BEGIN EXCLUSIVE";
  1484. }
  1485. public function commit_transaction()
  1486. {
  1487. return "COMMIT";
  1488. }
  1489. public function lock_table()
  1490. {
  1491. return "";
  1492. }
  1493. public function unlock_table()
  1494. {
  1495. return "";
  1496. }
  1497. public function start_add_lock_table()
  1498. {
  1499. return PHP_EOL;
  1500. }
  1501. public function end_add_lock_table()
  1502. {
  1503. return PHP_EOL;
  1504. }
  1505. public function start_add_disable_keys()
  1506. {
  1507. return PHP_EOL;
  1508. }
  1509. public function end_add_disable_keys()
  1510. {
  1511. return PHP_EOL;
  1512. }
  1513. public function start_disable_foreign_keys_check()
  1514. {
  1515. return PHP_EOL;
  1516. }
  1517. public function end_disable_foreign_keys_check()
  1518. {
  1519. return PHP_EOL;
  1520. }
  1521. public function add_drop_database()
  1522. {
  1523. return PHP_EOL;
  1524. }
  1525. public function add_drop_trigger()
  1526. {
  1527. return PHP_EOL;
  1528. }
  1529. public function drop_table()
  1530. {
  1531. return PHP_EOL;
  1532. }
  1533. public function drop_view()
  1534. {
  1535. return PHP_EOL;
  1536. }
  1537. /**
  1538. * Decode column metadata and fill info structure.
  1539. * type, is_numeric and is_blob will always be available.
  1540. *
  1541. * @param array $colType Array returned from "SHOW COLUMNS FROM tableName"
  1542. * @return array
  1543. */
  1544. public function parseColumnType($colType)
  1545. {
  1546. return array();
  1547. }
  1548. public function backup_parameters()
  1549. {
  1550. return PHP_EOL;
  1551. }
  1552. public function restore_parameters()
  1553. {
  1554. return PHP_EOL;
  1555. }
  1556. }
  1557. class TypeAdapterPgsql extends TypeAdapterFactory
  1558. {
  1559. }
  1560. class TypeAdapterDblib extends TypeAdapterFactory
  1561. {
  1562. }
  1563. class TypeAdapterSqlite extends TypeAdapterFactory
  1564. {
  1565. }
  1566. class TypeAdapterMysql extends TypeAdapterFactory
  1567. {
  1568. const DEFINER_RE = 'DEFINER=`(?:[^`]|``)*`@`(?:[^`]|``)*`';
  1569. // Numerical Mysql types
  1570. public $mysqlTypes = array(
  1571. 'numerical' => array(
  1572. 'bit',
  1573. 'tinyint',
  1574. 'smallint',
  1575. 'mediumint',
  1576. 'int',
  1577. 'integer',
  1578. 'bigint',
  1579. 'real',
  1580. 'double',
  1581. 'float',
  1582. 'decimal',
  1583. 'numeric'
  1584. ),
  1585. 'blob' => array(
  1586. 'tinyblob',
  1587. 'blob',
  1588. 'mediumblob',
  1589. 'longblob',
  1590. 'binary',
  1591. 'varbinary',
  1592. 'bit',
  1593. 'geometry', /* http://bugs.mysql.com/bug.php?id=43544 */
  1594. 'point',
  1595. 'linestring',
  1596. 'polygon',
  1597. 'multipoint',
  1598. 'multilinestring',
  1599. 'multipolygon',
  1600. 'geometrycollection',
  1601. )
  1602. );
  1603. public function databases()
  1604. {
  1605. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1606. $args = func_get_args();
  1607. $databaseName = $args[0];
  1608. $resultSet = $this->dbHandler->query("SHOW VARIABLES LIKE 'character_set_database';");
  1609. $characterSet = $resultSet->fetchColumn(1);
  1610. $resultSet->closeCursor();
  1611. $resultSet = $this->dbHandler->query("SHOW VARIABLES LIKE 'collation_database';");
  1612. $collationDb = $resultSet->fetchColumn(1);
  1613. $resultSet->closeCursor();
  1614. $ret = "";
  1615. $ret .= "CREATE DATABASE /*!32312 IF NOT EXISTS*/ `${databaseName}`".
  1616. " /*!40100 DEFAULT CHARACTER SET ${characterSet} ".
  1617. " COLLATE ${collationDb} */;".PHP_EOL.PHP_EOL.
  1618. "USE `${databaseName}`;".PHP_EOL.PHP_EOL;
  1619. return $ret;
  1620. }
  1621. public function show_create_table($tableName)
  1622. {
  1623. return "SHOW CREATE TABLE `$tableName`";
  1624. }
  1625. public function show_create_view($viewName)
  1626. {
  1627. return "SHOW CREATE VIEW `$viewName`";
  1628. }
  1629. public function show_create_trigger($triggerName)
  1630. {
  1631. return "SHOW CREATE TRIGGER `$triggerName`";
  1632. }
  1633. public function show_create_procedure($procedureName)
  1634. {
  1635. return "SHOW CREATE PROCEDURE `$procedureName`";
  1636. }
  1637. public function show_create_function($functionName)
  1638. {
  1639. return "SHOW CREATE FUNCTION `$functionName`";
  1640. }
  1641. public function show_create_event($eventName)
  1642. {
  1643. return "SHOW CREATE EVENT `$eventName`";
  1644. }
  1645. public function create_table($row)
  1646. {
  1647. if (!isset($row['Create Table'])) {
  1648. throw new Exception("Error getting table code, unknown output");
  1649. }
  1650. $createTable = $row['Create Table'];
  1651. if ($this->dumpSettings['reset-auto-increment']) {
  1652. $match = "/AUTO_INCREMENT=[0-9]+/s";
  1653. $replace = "";
  1654. $createTable = preg_replace($match, $replace, $createTable);
  1655. }
  1656. $ret = "/*!40101 SET @saved_cs_client = @@character_set_client */;".PHP_EOL.
  1657. "/*!40101 SET character_set_client = ".$this->dumpSettings['default-character-set']." */;".PHP_EOL.
  1658. $createTable.";".PHP_EOL.
  1659. "/*!40101 SET character_set_client = @saved_cs_client */;".PHP_EOL.
  1660. PHP_EOL;
  1661. return $ret;
  1662. }
  1663. public function create_view($row)
  1664. {
  1665. $ret = "";
  1666. if (!isset($row['Create View'])) {
  1667. throw new Exception("Error getting view structure, unknown output");
  1668. }
  1669. $viewStmt = $row['Create View'];
  1670. $definerStr = $this->dumpSettings['skip-definer'] ? '' : '/*!50013 \2 */'.PHP_EOL;
  1671. if ($viewStmtReplaced = preg_replace(
  1672. '/^(CREATE(?:\s+ALGORITHM=(?:UNDEFINED|MERGE|TEMPTABLE))?)\s+('
  1673. .self::DEFINER_RE.'(?:\s+SQL SECURITY DEFINER|INVOKER)?)?\s+(VIEW .+)$/',
  1674. '/*!50001 \1 */'.PHP_EOL.$definerStr.'/*!50001 \3 */',
  1675. $viewStmt,
  1676. 1
  1677. )) {
  1678. $viewStmt = $viewStmtReplaced;
  1679. };
  1680. $ret .= $viewStmt.';'.PHP_EOL.PHP_EOL;
  1681. return $ret;
  1682. }
  1683. public function create_trigger($row)
  1684. {
  1685. $ret = "";
  1686. if (!isset($row['SQL Original Statement'])) {
  1687. throw new Exception("Error getting trigger code, unknown output");
  1688. }
  1689. $triggerStmt = $row['SQL Original Statement'];
  1690. $definerStr = $this->dumpSettings['skip-definer'] ? '' : '/*!50017 \2*/ ';
  1691. if ($triggerStmtReplaced = preg_replace(
  1692. '/^(CREATE)\s+('.self::DEFINER_RE.')?\s+(TRIGGER\s.*)$/s',
  1693. '/*!50003 \1*/ '.$definerStr.'/*!50003 \3 */',
  1694. $triggerStmt,
  1695. 1
  1696. )) {
  1697. $triggerStmt = $triggerStmtReplaced;
  1698. }
  1699. $ret .= "DELIMITER ;;".PHP_EOL.
  1700. $triggerStmt.";;".PHP_EOL.
  1701. "DELIMITER ;".PHP_EOL.PHP_EOL;
  1702. return $ret;
  1703. }
  1704. public function create_procedure($row)
  1705. {
  1706. $ret = "";
  1707. if (!isset($row['Create Procedure'])) {
  1708. throw new Exception("Error getting procedure code, unknown output. ".
  1709. "Please check 'https://bugs.mysql.com/bug.php?id=14564'");
  1710. }
  1711. $procedureStmt = $row['Create Procedure'];
  1712. if ( $this->dumpSettings['skip-definer'] ) {
  1713. if ($procedureStmtReplaced = preg_replace(
  1714. '/^(CREATE)\s+('.self::DEFINER_RE.')?\s+(PROCEDURE\s.*)$/s',
  1715. '\1 \3',
  1716. $procedureStmt,
  1717. 1
  1718. )) {
  1719. $procedureStmt = $procedureStmtReplaced;
  1720. }
  1721. }
  1722. $ret .= "/*!50003 DROP PROCEDURE IF EXISTS `".
  1723. $row['Procedure']."` */;".PHP_EOL.
  1724. "/*!40101 SET @saved_cs_client = @@character_set_client */;".PHP_EOL.
  1725. "/*!40101 SET character_set_client = ".$this->dumpSettings['default-character-set']." */;".PHP_EOL.
  1726. "DELIMITER ;;".PHP_EOL.
  1727. $procedureStmt." ;;".PHP_EOL.
  1728. "DELIMITER ;".PHP_EOL.
  1729. "/*!40101 SET character_set_client = @saved_cs_client */;".PHP_EOL.PHP_EOL;
  1730. return $ret;
  1731. }
  1732. public function create_function($row)
  1733. {
  1734. $ret = "";
  1735. if (!isset($row['Create Function'])) {
  1736. throw new Exception("Error getting function code, unknown output. ".
  1737. "Please check 'https://bugs.mysql.com/bug.php?id=14564'");
  1738. }
  1739. $functionStmt = $row['Create Function'];
  1740. $characterSetClient = $row['character_set_client'];
  1741. $collationConnection = $row['collation_connection'];
  1742. $sqlMode = $row['sql_mode'];
  1743. if ( $this->dumpSettings['skip-definer'] ) {
  1744. if ($functionStmtReplaced = preg_replace(
  1745. '/^(CREATE)\s+('.self::DEFINER_RE.')?\s+(FUNCTION\s.*)$/s',
  1746. '\1 \3',
  1747. $functionStmt,
  1748. 1
  1749. )) {
  1750. $functionStmt = $functionStmtReplaced;
  1751. }
  1752. }
  1753. $ret .= "/*!50003 DROP FUNCTION IF EXISTS `".
  1754. $row['Function']."` */;".PHP_EOL.
  1755. "/*!40101 SET @saved_cs_client = @@character_set_client */;".PHP_EOL.
  1756. "/*!50003 SET @saved_cs_results = @@character_set_results */ ;".PHP_EOL.
  1757. "/*!50003 SET @saved_col_connection = @@collation_connection */ ;".PHP_EOL.
  1758. "/*!40101 SET character_set_client = ".$characterSetClient." */;".PHP_EOL.
  1759. "/*!40101 SET character_set_results = ".$characterSetClient." */;".PHP_EOL.
  1760. "/*!50003 SET collation_connection = ".$collationConnection." */ ;".PHP_EOL.
  1761. "/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;".PHP_EOL.
  1762. "/*!50003 SET sql_mode = '".$sqlMode."' */ ;;".PHP_EOL.
  1763. "/*!50003 SET @saved_time_zone = @@time_zone */ ;;".PHP_EOL.
  1764. "/*!50003 SET time_zone = 'SYSTEM' */ ;;".PHP_EOL.
  1765. "DELIMITER ;;".PHP_EOL.
  1766. $functionStmt." ;;".PHP_EOL.
  1767. "DELIMITER ;".PHP_EOL.
  1768. "/*!50003 SET sql_mode = @saved_sql_mode */ ;".PHP_EOL.
  1769. "/*!50003 SET character_set_client = @saved_cs_client */ ;".PHP_EOL.
  1770. "/*!50003 SET character_set_results = @saved_cs_results */ ;".PHP_EOL.
  1771. "/*!50003 SET collation_connection = @saved_col_connection */ ;".PHP_EOL.
  1772. "/*!50106 SET TIME_ZONE= @saved_time_zone */ ;".PHP_EOL.PHP_EOL;
  1773. return $ret;
  1774. }
  1775. public function create_event($row)
  1776. {
  1777. $ret = "";
  1778. if (!isset($row['Create Event'])) {
  1779. throw new Exception("Error getting event code, unknown output. ".
  1780. "Please check 'http://stackoverflow.com/questions/10853826/mysql-5-5-create-event-gives-syntax-error'");
  1781. }
  1782. $eventName = $row['Event'];
  1783. $eventStmt = $row['Create Event'];
  1784. $sqlMode = $row['sql_mode'];
  1785. $definerStr = $this->dumpSettings['skip-definer'] ? '' : '/*!50117 \2*/ ';
  1786. if ($eventStmtReplaced = preg_replace(
  1787. '/^(CREATE)\s+('.self::DEFINER_RE.')?\s+(EVENT .*)$/',
  1788. '/*!50106 \1*/ '.$definerStr.'/*!50106 \3 */',
  1789. $eventStmt,
  1790. 1
  1791. )) {
  1792. $eventStmt = $eventStmtReplaced;
  1793. }
  1794. $ret .= "/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;".PHP_EOL.
  1795. "/*!50106 DROP EVENT IF EXISTS `".$eventName."` */;".PHP_EOL.
  1796. "DELIMITER ;;".PHP_EOL.
  1797. "/*!50003 SET @saved_cs_client = @@character_set_client */ ;;".PHP_EOL.
  1798. "/*!50003 SET @saved_cs_results = @@character_set_results */ ;;".PHP_EOL.
  1799. "/*!50003 SET @saved_col_connection = @@collation_connection */ ;;".PHP_EOL.
  1800. "/*!50003 SET character_set_client = utf8 */ ;;".PHP_EOL.
  1801. "/*!50003 SET character_set_results = utf8 */ ;;".PHP_EOL.
  1802. "/*!50003 SET collation_connection = utf8_general_ci */ ;;".PHP_EOL.
  1803. "/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;".PHP_EOL.
  1804. "/*!50003 SET sql_mode = '".$sqlMode."' */ ;;".PHP_EOL.
  1805. "/*!50003 SET @saved_time_zone = @@time_zone */ ;;".PHP_EOL.
  1806. "/*!50003 SET time_zone = 'SYSTEM' */ ;;".PHP_EOL.
  1807. $eventStmt." ;;".PHP_EOL.
  1808. "/*!50003 SET time_zone = @saved_time_zone */ ;;".PHP_EOL.
  1809. "/*!50003 SET sql_mode = @saved_sql_mode */ ;;".PHP_EOL.
  1810. "/*!50003 SET character_set_client = @saved_cs_client */ ;;".PHP_EOL.
  1811. "/*!50003 SET character_set_results = @saved_cs_results */ ;;".PHP_EOL.
  1812. "/*!50003 SET collation_connection = @saved_col_connection */ ;;".PHP_EOL.
  1813. "DELIMITER ;".PHP_EOL.
  1814. "/*!50106 SET TIME_ZONE= @save_time_zone */ ;".PHP_EOL.PHP_EOL;
  1815. // Commented because we are doing this in restore_parameters()
  1816. // "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;" . PHP_EOL . PHP_EOL;
  1817. return $ret;
  1818. }
  1819. public function show_tables()
  1820. {
  1821. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1822. $args = func_get_args();
  1823. return "SELECT TABLE_NAME AS tbl_name ".
  1824. "FROM INFORMATION_SCHEMA.TABLES ".
  1825. "WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='${args[0]}'";
  1826. }
  1827. public function show_views()
  1828. {
  1829. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1830. $args = func_get_args();
  1831. return "SELECT TABLE_NAME AS tbl_name ".
  1832. "FROM INFORMATION_SCHEMA.TABLES ".
  1833. "WHERE TABLE_TYPE='VIEW' AND TABLE_SCHEMA='${args[0]}'";
  1834. }
  1835. public function show_triggers()
  1836. {
  1837. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1838. $args = func_get_args();
  1839. return "SHOW TRIGGERS FROM `${args[0]}`;";
  1840. }
  1841. public function show_columns()
  1842. {
  1843. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1844. $args = func_get_args();
  1845. return "SHOW COLUMNS FROM `${args[0]}`;";
  1846. }
  1847. public function show_procedures()
  1848. {
  1849. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1850. $args = func_get_args();
  1851. return "SELECT SPECIFIC_NAME AS procedure_name ".
  1852. "FROM INFORMATION_SCHEMA.ROUTINES ".
  1853. "WHERE ROUTINE_TYPE='PROCEDURE' AND ROUTINE_SCHEMA='${args[0]}'";
  1854. }
  1855. public function show_functions()
  1856. {
  1857. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1858. $args = func_get_args();
  1859. return "SELECT SPECIFIC_NAME AS function_name ".
  1860. "FROM INFORMATION_SCHEMA.ROUTINES ".
  1861. "WHERE ROUTINE_TYPE='FUNCTION' AND ROUTINE_SCHEMA='${args[0]}'";
  1862. }
  1863. /**
  1864. * Get query string to ask for names of events from current database.
  1865. *
  1866. * @param string Name of database
  1867. * @return string
  1868. */
  1869. public function show_events()
  1870. {
  1871. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1872. $args = func_get_args();
  1873. return "SELECT EVENT_NAME AS event_name ".
  1874. "FROM INFORMATION_SCHEMA.EVENTS ".
  1875. "WHERE EVENT_SCHEMA='${args[0]}'";
  1876. }
  1877. public function setup_transaction()
  1878. {
  1879. return "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";
  1880. }
  1881. public function start_transaction()
  1882. {
  1883. return "START TRANSACTION " .
  1884. "/*!40100 WITH CONSISTENT SNAPSHOT */";
  1885. }
  1886. public function commit_transaction()
  1887. {
  1888. return "COMMIT";
  1889. }
  1890. public function lock_table()
  1891. {
  1892. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1893. $args = func_get_args();
  1894. return $this->dbHandler->exec("LOCK TABLES `${args[0]}` READ LOCAL");
  1895. }
  1896. public function unlock_table()
  1897. {
  1898. return $this->dbHandler->exec("UNLOCK TABLES");
  1899. }
  1900. public function start_add_lock_table()
  1901. {
  1902. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1903. $args = func_get_args();
  1904. return "LOCK TABLES `${args[0]}` WRITE;".PHP_EOL;
  1905. }
  1906. public function end_add_lock_table()
  1907. {
  1908. return "UNLOCK TABLES;".PHP_EOL;
  1909. }
  1910. public function start_add_disable_keys()
  1911. {
  1912. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1913. $args = func_get_args();
  1914. return "/*!40000 ALTER TABLE `${args[0]}` DISABLE KEYS */;".
  1915. PHP_EOL;
  1916. }
  1917. public function end_add_disable_keys()
  1918. {
  1919. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1920. $args = func_get_args();
  1921. return "/*!40000 ALTER TABLE `${args[0]}` ENABLE KEYS */;".
  1922. PHP_EOL;
  1923. }
  1924. public function start_disable_autocommit()
  1925. {
  1926. return "SET autocommit=0;".PHP_EOL;
  1927. }
  1928. public function end_disable_autocommit()
  1929. {
  1930. return "COMMIT;".PHP_EOL;
  1931. }
  1932. public function add_drop_database()
  1933. {
  1934. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1935. $args = func_get_args();
  1936. return "/*!40000 DROP DATABASE IF EXISTS `${args[0]}`*/;".
  1937. PHP_EOL.PHP_EOL;
  1938. }
  1939. public function add_drop_trigger()
  1940. {
  1941. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1942. $args = func_get_args();
  1943. return "DROP TRIGGER IF EXISTS `${args[0]}`;".PHP_EOL;
  1944. }
  1945. public function drop_table()
  1946. {
  1947. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1948. $args = func_get_args();
  1949. return "DROP TABLE IF EXISTS `${args[0]}`;".PHP_EOL;
  1950. }
  1951. public function drop_view()
  1952. {
  1953. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1954. $args = func_get_args();
  1955. return "DROP TABLE IF EXISTS `${args[0]}`;".PHP_EOL.
  1956. "/*!50001 DROP VIEW IF EXISTS `${args[0]}`*/;".PHP_EOL;
  1957. }
  1958. public function getDatabaseHeader()
  1959. {
  1960. $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
  1961. $args = func_get_args();
  1962. return "--".PHP_EOL.
  1963. "-- Current Database: `${args[0]}`".PHP_EOL.
  1964. "--".PHP_EOL.PHP_EOL;
  1965. }
  1966. /**
  1967. * Decode column metadata and fill info structure.
  1968. * type, is_numeric and is_blob will always be available.
  1969. *
  1970. * @param array $colType Array returned from "SHOW COLUMNS FROM tableName"
  1971. * @return array
  1972. */
  1973. public function parseColumnType($colType)
  1974. {
  1975. $colInfo = array();
  1976. $colParts = explode(" ", $colType['Type']);
  1977. if ($fparen = strpos($colParts[0], "(")) {
  1978. $colInfo['type'] = substr($colParts[0], 0, $fparen);
  1979. $colInfo['length'] = str_replace(")", "", substr($colParts[0], $fparen + 1));
  1980. $colInfo['attributes'] = isset($colParts[1]) ? $colParts[1] : null;
  1981. } else {
  1982. $colInfo['type'] = $colParts[0];
  1983. }
  1984. $colInfo['is_numeric'] = in_array($colInfo['type'], $this->mysqlTypes['numerical']);
  1985. $colInfo['is_blob'] = in_array($colInfo['type'], $this->mysqlTypes['blob']);
  1986. // for virtual columns that are of type 'Extra', column type
  1987. // could by "STORED GENERATED" or "VIRTUAL GENERATED"
  1988. // MySQL reference: https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html
  1989. $colInfo['is_virtual'] = strpos($colType['Extra'], "VIRTUAL GENERATED") !== false || strpos($colType['Extra'], "STORED GENERATED") !== false;
  1990. return $colInfo;
  1991. }
  1992. public function backup_parameters()
  1993. {
  1994. $ret = "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;".PHP_EOL.
  1995. "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;".PHP_EOL.
  1996. "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;".PHP_EOL.
  1997. "/*!40101 SET NAMES ".$this->dumpSettings['default-character-set']." */;".PHP_EOL;
  1998. if (false === $this->dumpSettings['skip-tz-utc']) {
  1999. $ret .= "/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;".PHP_EOL.
  2000. "/*!40103 SET TIME_ZONE='+00:00' */;".PHP_EOL;
  2001. }
  2002. $ret .= "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;".PHP_EOL.
  2003. "/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;".PHP_EOL.
  2004. "/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;".PHP_EOL.
  2005. "/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;".PHP_EOL.PHP_EOL;
  2006. return $ret;
  2007. }
  2008. public function restore_parameters()
  2009. {
  2010. $ret = "";
  2011. if (false === $this->dumpSettings['skip-tz-utc']) {
  2012. $ret .= "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;".PHP_EOL;
  2013. }
  2014. $ret .= "/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;".PHP_EOL.
  2015. "/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;".PHP_EOL.
  2016. "/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;".PHP_EOL.
  2017. "/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;".PHP_EOL.
  2018. "/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;".PHP_EOL.
  2019. "/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;".PHP_EOL.
  2020. "/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;".PHP_EOL.PHP_EOL;
  2021. return $ret;
  2022. }
  2023. /**
  2024. * Check number of parameters passed to function, useful when inheriting.
  2025. * Raise exception if unexpected.
  2026. *
  2027. * @param integer $num_args
  2028. * @param integer $expected_num_args
  2029. * @param string $method_name
  2030. */
  2031. private function check_parameters($num_args, $expected_num_args, $method_name)
  2032. {
  2033. if ($num_args != $expected_num_args) {
  2034. throw new Exception("Unexpected parameter passed to $method_name");
  2035. }
  2036. return;
  2037. }
  2038. }