Mysqldump.php 71 KB

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