Mysqldump.php 69 KB

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