├── LICENSE ├── README.md ├── composer.json └── src └── Ifsnop └── Mysqldump └── Mysqldump.php /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | MySQLDump - PHP 2 | ========= 3 | 4 | [Requirements](https://github.com/ifsnop/mysqldump-php#requirements) | 5 | [Installing](https://github.com/ifsnop/mysqldump-php#installing) | 6 | [Getting started](https://github.com/ifsnop/mysqldump-php#getting-started) | 7 | [API](https://github.com/ifsnop/mysqldump-php#constructor-and-default-parameters) | 8 | [Settings](https://github.com/ifsnop/mysqldump-php#dump-settings) | 9 | [PDO Settings](https://github.com/ifsnop/mysqldump-php#pdo-settings) | 10 | [TODO](https://github.com/ifsnop/mysqldump-php#todo) | 11 | [License](https://github.com/ifsnop/mysqldump-php#license) | 12 | [Credits](https://github.com/ifsnop/mysqldump-php#credits) 13 | 14 | [![Build Status](https://travis-ci.org/ifsnop/mysqldump-php.svg?branch=devel)](https://travis-ci.org/ifsnop/mysqldump-php) 15 | [![Total Downloads](https://poser.pugx.org/ifsnop/mysqldump-php/downloads)](https://packagist.org/packages/ifsnop/mysqldump-php) 16 | [![Monthly Downloads](https://poser.pugx.org/ifsnop/mysqldump-php/d/monthly)](https://packagist.org/packages/ifsnop/mysqldump-php) 17 | [![Daily Downloads](https://poser.pugx.org/ifsnop/mysqldump-php/d/daily)](https://packagist.org/packages/ifsnop/mysqldump-php) 18 | [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/ifsnop/mysqldump-php/badges/quality-score.png?s=d02891e196a3ca1298619032a538ce8ae8cafd2b)](https://scrutinizer-ci.com/g/ifsnop/mysqldump-php/) 19 | [![Latest Stable Version](https://poser.pugx.org/ifsnop/mysqldump-php/v/stable.png)](https://packagist.org/packages/ifsnop/mysqldump-php) 20 | 21 | This is a php version of mysqldump cli that comes with MySQL, without dependencies, output compression and sane defaults. 22 | 23 | Out of the box, MySQLDump-PHP supports backing up table structures, the data itself, views, triggers and events. 24 | 25 | MySQLDump-PHP is the only library that supports: 26 | * output binary blobs as hex. 27 | * resolves view dependencies (using Stand-In tables). 28 | * output compared against original mysqldump. Linked to travis-ci testing system (testing from php 5.3 to 7.3 & hhvm) 29 | * dumps stored routines (functions and procedures). 30 | * dumps events. 31 | * does extended-insert and/or complete-insert. 32 | * supports virtual columns from MySQL 5.7. 33 | * does insert-ignore, like a REPLACE but ignoring errors if a duplicate key exists. 34 | * modifying data from database on-the-fly when dumping, using hooks. 35 | * can save directly to google cloud storage over a compressed stream wrapper (GZIPSTREAM). 36 | * can restore a dump from a file, when no mysql executable is available. 37 | 38 | ## Important 39 | 40 | From version 2.0, connections to database are made using the standard DSN, documented in [PDO connection string](https://secure.php.net/manual/en/ref.pdo-mysql.connection.php). 41 | 42 | ## Requirements 43 | 44 | - PHP 5.3.0 or newer 45 | - MySQL 4.1.0 or newer 46 | - [PDO](https://secure.php.net/pdo) 47 | 48 | ## Installing 49 | 50 | Using [Composer](https://getcomposer.org/): 51 | 52 | ``` 53 | $ composer require ifsnop/mysqldump-php 54 | 55 | ``` 56 | 57 | Using [Curl](https://curl.haxx.se/) to always download and decompress the latest release: 58 | 59 | ``` 60 | $ curl --silent --location https://api.github.com/repos/ifsnop/mysqldump-php/releases | grep -i tarball_url | head -n 1 | cut -d '"' -f 4 | xargs curl --location --silent | tar xvz 61 | ``` 62 | 63 | ## Getting started 64 | 65 | With [Autoloader](https://www.php-fig.org/psr/psr-4/)/[Composer](https://getcomposer.org): 66 | 67 | ```php 68 | start('storage/work/dump.sql'); 75 | } catch (\Exception $e) { 76 | echo 'mysqldump-php error: ' . $e->getMessage(); 77 | } 78 | ``` 79 | 80 | Plain old PHP: 81 | 82 | ```php 83 | start('storage/work/dump.sql'); 88 | ``` 89 | 90 | Refer to the [wiki](https://github.com/ifsnop/mysqldump-php/wiki/Full-usage-example) for some examples and a comparision between mysqldump and mysqldump-php dumps. 91 | 92 | ## Changing values when exporting 93 | 94 | You can register a callable that will be used to transform values during the export. An example use-case for this is removing sensitive data from database dumps: 95 | 96 | ```php 97 | $dumper = new IMysqldump\Mysqldump('mysql:host=localhost;dbname=testdb', 'username', 'password'); 98 | 99 | $dumper->setTransformTableRowHook(function ($tableName, array $row) { 100 | if ($tableName === 'customers') { 101 | $row['social_security_number'] = (string) rand(1000000, 9999999); 102 | } 103 | 104 | return $row; 105 | }); 106 | 107 | $dumper->start('storage/work/dump.sql'); 108 | ``` 109 | 110 | ## Getting information about the dump 111 | 112 | You can register a callable that will be used to report on the progress of the dump 113 | 114 | ```php 115 | $dumper->setInfoHook(function($object, $info) { 116 | if ($object === 'table') { 117 | echo $info['name'], $info['rowCount']; 118 | }); 119 | ``` 120 | 121 | ## Table specific export conditions 122 | 123 | You can register table specific 'where' clauses to limit data on a per table basis. These override the default `where` dump setting: 124 | 125 | ```php 126 | $dumper = new IMysqldump\Mysqldump('mysql:host=localhost;dbname=testdb', 'username', 'password'); 127 | 128 | $dumper->setTableWheres(array( 129 | 'users' => 'date_registered > NOW() - INTERVAL 3 MONTH AND deleted=0', 130 | 'logs' => 'date_logged > NOW() - INTERVAL 1 DAY', 131 | 'posts' => 'isLive=1' 132 | )); 133 | ``` 134 | 135 | ## Table specific export limits 136 | 137 | You can register table specific 'limits' to limit the returned rows on a per table basis: 138 | 139 | ```php 140 | $dumper = new IMysqldump\Mysqldump('mysql:host=localhost;dbname=testdb', 'username', 'password'); 141 | 142 | $dumper->setTableLimits(array( 143 | 'users' => 300, 144 | 'logs' => 50, 145 | 'posts' => 10 146 | )); 147 | ``` 148 | 149 | ## Constructor and default parameters 150 | 151 | ```php 152 | /** 153 | * Constructor of Mysqldump. Note that in the case of an SQLite database 154 | * connection, the filename must be in the $db parameter. 155 | * 156 | * @param string $dsn PDO DSN connection string 157 | * @param string $user SQL account username 158 | * @param string $pass SQL account password 159 | * @param array $dumpSettings SQL database settings 160 | * @param array $pdoSettings PDO configured attributes 161 | */ 162 | public function __construct( 163 | $dsn = '', 164 | $user = '', 165 | $pass = '', 166 | $dumpSettings = array(), 167 | $pdoSettings = array() 168 | ) 169 | 170 | $dumpSettingsDefault = array( 171 | 'include-tables' => array(), 172 | 'exclude-tables' => array(), 173 | 'compress' => Mysqldump::NONE, 174 | 'init_commands' => array(), 175 | 'no-data' => array(), 176 | 'if-not-exists' => false, 177 | 'reset-auto-increment' => false, 178 | 'add-drop-database' => false, 179 | 'add-drop-table' => false, 180 | 'add-drop-trigger' => true, 181 | 'add-locks' => true, 182 | 'complete-insert' => false, 183 | 'databases' => false, 184 | 'default-character-set' => Mysqldump::UTF8, 185 | 'disable-keys' => true, 186 | 'extended-insert' => true, 187 | 'events' => false, 188 | 'hex-blob' => true, /* faster than escaped content */ 189 | 'insert-ignore' => false, 190 | 'net_buffer_length' => self::MAXLINESIZE, 191 | 'no-autocommit' => true, 192 | 'no-create-db' => false, 193 | 'no-create-info' => false, 194 | 'lock-tables' => true, 195 | 'routines' => false, 196 | 'single-transaction' => true, 197 | 'skip-triggers' => false, 198 | 'skip-tz-utc' => false, 199 | 'skip-comments' => false, 200 | 'skip-dump-date' => false, 201 | 'skip-definer' => false, 202 | 'where' => '', 203 | /* deprecated */ 204 | 'disable-foreign-keys-check' => true 205 | ); 206 | 207 | $pdoSettingsDefaults = array( 208 | PDO::ATTR_PERSISTENT => true, 209 | PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 210 | PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false 211 | ); 212 | 213 | // missing settings in constructor will be replaced by default options 214 | $this->_pdoSettings = self::array_replace_recursive($pdoSettingsDefault, $pdoSettings); 215 | $this->_dumpSettings = self::array_replace_recursive($dumpSettingsDefault, $dumpSettings); 216 | ``` 217 | 218 | ## Dump Settings 219 | 220 | - **include-tables** 221 | - Only include these tables (array of table names), include all if empty. 222 | - **exclude-tables** 223 | - Exclude these tables (array of table names), include all if empty, supports regexps. 224 | - **include-views** 225 | - Only include these views (array of view names), include all if empty. By default, all views named as the include-tables array are included. 226 | - **if-not-exists** 227 | - Only create a new table when a table of the same name does not already exist. No error message is thrown if the table already exists. 228 | - **compress** 229 | - Gzip, Bzip2, None. 230 | - Could be specified using the declared consts: IMysqldump\Mysqldump::GZIP, IMysqldump\Mysqldump::BZIP2 or IMysqldump\Mysqldump::NONE 231 | - **reset-auto-increment** 232 | - Removes the AUTO_INCREMENT option from the database definition 233 | - Useful when used with no-data, so when db is recreated, it will start from 1 instead of using an old value 234 | - **add-drop-database** 235 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_add-drop-database 236 | - **add-drop-table** 237 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_add-drop-table 238 | - **add-drop-triggers** 239 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_add-drop-trigger 240 | - **add-locks** 241 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_add-locks 242 | - **complete-insert** 243 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_complete-insert 244 | - **databases** 245 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_databases 246 | - **default-character-set** 247 | - utf8 (default, compatible option), utf8mb4 (for full utf8 compliance) 248 | - Could be specified using the declared consts: IMysqldump\Mysqldump::UTF8 or IMysqldump\Mysqldump::UTF8MB4BZIP2 249 | - https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html 250 | - https://mathiasbynens.be/notes/mysql-utf8mb4 251 | - **disable-keys** 252 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_disable-keys 253 | - **events** 254 | - https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_events 255 | - **extended-insert** 256 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_extended-insert 257 | - **hex-blob** 258 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_hex-blob 259 | - **insert-ignore** 260 | - https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_insert-ignore 261 | - **lock-tables** 262 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_lock-tables 263 | - **net_buffer_length** 264 | - https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_net_buffer_length 265 | - **no-autocommit** 266 | - Option to disable autocommit (faster inserts, no problems with index keys) 267 | - https://dev.mysql.com/doc/refman/4.1/en/commit.html 268 | - **no-create-db** 269 | - Option to disable the dump of create database statements. 270 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_no-create-db 271 | - **no-create-info** 272 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_no-create-info 273 | - **no-data** 274 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_no-data 275 | - Do not dump data for these tables (array of table names), support regexps, `true` to ignore all tables 276 | - **routines** 277 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_routines 278 | - **single-transaction** 279 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_single-transaction 280 | - **skip-comments** 281 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_comments 282 | - **skip-dump-date** 283 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_dump-date 284 | - **skip-triggers** 285 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_triggers 286 | - **skip-tz-utc** 287 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_tz-utc 288 | - **skip-definer** 289 | - https://dev.mysql.com/doc/refman/5.7/en/mysqlpump.html#option_mysqlpump_skip-definer 290 | - **where** 291 | - https://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_where 292 | 293 | The following options are now enabled by default, and there is no way to disable them since 294 | they should always be used. 295 | 296 | - **disable-foreign-keys-check** 297 | - https://dev.mysql.com/doc/refman/5.5/en/optimizing-innodb-bulk-data-loading.html 298 | 299 | ## PDO Settings 300 | 301 | - **PDO::ATTR_PERSISTENT** 302 | - **PDO::ATTR_ERRMODE** 303 | - **PDO::MYSQL_ATTR_INIT_COMMAND** 304 | - **PDO::MYSQL_ATTR_USE_BUFFERED_QUERY** 305 | - https://secure.php.net/manual/en/ref.pdo-mysql.php 306 | - https://stackoverflow.com/questions/13728106/unexpectedly-hitting-php-memory-limit-with-a-single-pdo-query/13729745#13729745 307 | - https://secure.php.net/manual/en/mysqlinfo.concepts.buffering.php 308 | 309 | ## Errors 310 | 311 | To dump a database, you need the following privileges : 312 | 313 | - **SELECT** 314 | - In order to dump table structures and data. 315 | - **SHOW VIEW** 316 | - If any databases has views, else you will get an error. 317 | - **TRIGGER** 318 | - If any table has one or more triggers. 319 | - **LOCK TABLES** 320 | - If "lock tables" option was enabled. 321 | 322 | Use **SHOW GRANTS FOR user@host;** to know what privileges user has. See the following link for more information: 323 | 324 | [Which are the minimum privileges required to get a backup of a MySQL database schema?](https://dba.stackexchange.com/questions/55546/which-are-the-minimum-privileges-required-to-get-a-backup-of-a-mysql-database-sc/55572#55572) 325 | 326 | ## Tests 327 | 328 | Current code for testing is an ugly hack. Probably there are much better ways 329 | of doing them using PHPUnit, so PR's are welcomed. The testing script creates 330 | and populates a database using all possible datatypes. Then it exports it 331 | using both mysqldump-php and mysqldump, and compares the output. Only if 332 | it is identical tests are OK. After [this](https://github.com/ifsnop/mysqldump-php/commit/8496fbb1b26dde404804bc8865ec32044da5b813) 333 | commit, some test are performed using phpunit. 334 | 335 | Some tests are skipped if mysql server doesn't support them. 336 | 337 | A couple of tests are only comparing between original sql code and 338 | mysqldump-php generated sql, because some options are not available in 339 | mysqldump. 340 | 341 | ## Bugs (from mysqldump, not from mysqldump-php) 342 | 343 | After [this](https://bugs.mysql.com/bug.php?id=80150) bug report, a new 344 | one has been introduced. _binary is appended also when hex-blob option is 345 | used, if the value is empty. 346 | 347 | ## Backporting 348 | 349 | mysqldump-php is not backwards compatible with php 5.2 because we it uses 350 | namespaces. However, it could be trivially fixed if needed. 351 | 352 | ## Todo 353 | 354 | Write more tests, test with mariadb also. 355 | 356 | ## Contributing 357 | 358 | Format all code to PHP-FIG standards. 359 | https://www.php-fig.org/ 360 | 361 | ## License 362 | 363 | This project is open-sourced software licensed under the [GPL license](https://www.gnu.org/copyleft/gpl.html) 364 | 365 | ## Credits 366 | 367 | After more than 8 years, there is barely anything left from the original source code, but: 368 | 369 | Originally based on James Elliott's script from 2009. 370 | https://code.google.com/archive/p/db-mysqldump/ 371 | 372 | Adapted and extended by Michael J. Calkins. 373 | https://github.com/clouddueling 374 | 375 | Currently maintained, developed and improved by Diego Torres. 376 | https://github.com/ifsnop 377 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ifsnop/mysqldump-php", 3 | "description": "PHP version of mysqldump cli that comes with MySQL", 4 | "type": "library", 5 | "keywords": ["mysql", "mysqldump", "pdo", "php7", "php5", "database", "php", "sql", "hhvm", "mariadb", "mysql-backup"], 6 | "homepage": "https://github.com/ifsnop/mysqldump-php", 7 | "license": "GPL-3.0-or-later", 8 | "minimum-stability": "stable", 9 | "authors": [ 10 | { 11 | "name" : "Diego Torres", 12 | "homepage": "https://github.com/ifsnop", 13 | "role": "Developer" 14 | } 15 | ], 16 | "require": { 17 | "php": ">=5.3.0" 18 | }, 19 | "require-dev": { 20 | "squizlabs/php_codesniffer": "1.*", 21 | "phpunit/phpunit": "4.8.36" 22 | }, 23 | "autoload": { 24 | "psr-4": {"Ifsnop\\": "src/Ifsnop/"} 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Ifsnop/Mysqldump/Mysqldump.php: -------------------------------------------------------------------------------- 1 | 11 | * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 12 | * @link https://github.com/ifsnop/mysqldump-php 13 | * 14 | */ 15 | 16 | namespace Ifsnop\Mysqldump; 17 | 18 | use Exception; 19 | use PDO; 20 | use PDOException; 21 | 22 | /** 23 | * Class Mysqldump. 24 | * 25 | * @category Library 26 | * @author Diego Torres 27 | * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 28 | * @link https://github.com/ifsnop/mysqldump-php 29 | * 30 | */ 31 | class Mysqldump 32 | { 33 | 34 | // Same as mysqldump. 35 | const MAXLINESIZE = 1000000; 36 | 37 | // List of available compression methods as constants. 38 | const GZIP = 'Gzip'; 39 | const BZIP2 = 'Bzip2'; 40 | const NONE = 'None'; 41 | const GZIPSTREAM = 'Gzipstream'; 42 | 43 | // List of available connection strings. 44 | const UTF8 = 'utf8'; 45 | const UTF8MB4 = 'utf8mb4'; 46 | const BINARY = 'binary'; 47 | 48 | /** 49 | * Database username. 50 | * @var string 51 | */ 52 | public $user; 53 | 54 | /** 55 | * Database password. 56 | * @var string 57 | */ 58 | public $pass; 59 | 60 | /** 61 | * Connection string for PDO. 62 | * @var string 63 | */ 64 | public $dsn; 65 | 66 | /** 67 | * Destination filename, defaults to stdout. 68 | * @var string 69 | */ 70 | public $fileName = 'php://stdout'; 71 | 72 | // Internal stuff. 73 | private $tables = array(); 74 | private $views = array(); 75 | private $triggers = array(); 76 | private $procedures = array(); 77 | private $functions = array(); 78 | private $events = array(); 79 | protected $dbHandler = null; 80 | private $dbType = ""; 81 | private $compressManager; 82 | private $typeAdapter; 83 | protected $dumpSettings = array(); 84 | protected $pdoSettings = array(); 85 | private $version; 86 | private $tableColumnTypes = array(); 87 | private $transformTableRowCallable; 88 | private $transformColumnValueCallable; 89 | private $infoCallable; 90 | 91 | /** 92 | * Database name, parsed from dsn. 93 | * @var string 94 | */ 95 | private $dbName; 96 | 97 | /** 98 | * Host name, parsed from dsn. 99 | * @var string 100 | */ 101 | private $host; 102 | 103 | /** 104 | * Dsn string parsed as an array. 105 | * @var array 106 | */ 107 | private $dsnArray = array(); 108 | 109 | /** 110 | * Keyed on table name, with the value as the conditions. 111 | * e.g. - 'users' => 'date_registered > NOW() - INTERVAL 6 MONTH' 112 | * 113 | * @var array 114 | */ 115 | private $tableWheres = array(); 116 | private $tableLimits = array(); 117 | 118 | protected $dumpSettingsDefault = array( 119 | 'include-tables' => array(), 120 | 'exclude-tables' => array(), 121 | 'include-views' => array(), 122 | 'compress' => Mysqldump::NONE, 123 | 'init_commands' => array(), 124 | 'no-data' => array(), 125 | 'if-not-exists' => false, 126 | 'reset-auto-increment' => false, 127 | 'add-drop-database' => false, 128 | 'add-drop-table' => false, 129 | 'add-drop-trigger' => true, 130 | 'add-locks' => true, 131 | 'complete-insert' => false, 132 | 'databases' => false, 133 | 'default-character-set' => Mysqldump::UTF8, 134 | 'disable-keys' => true, 135 | 'extended-insert' => true, 136 | 'events' => false, 137 | 'hex-blob' => true, /* faster than escaped content */ 138 | 'insert-ignore' => false, 139 | 'net_buffer_length' => self::MAXLINESIZE, 140 | 'no-autocommit' => true, 141 | 'no-create-db' => false, 142 | 'no-create-info' => false, 143 | 'lock-tables' => true, 144 | 'routines' => false, 145 | 'single-transaction' => true, 146 | 'skip-triggers' => false, 147 | 'skip-tz-utc' => false, 148 | 'skip-comments' => false, 149 | 'skip-dump-date' => false, 150 | 'skip-definer' => false, 151 | 'where' => '', 152 | /* deprecated */ 153 | 'disable-foreign-keys-check' => true 154 | ); 155 | 156 | protected $pdoSettingsDefault = array( 157 | PDO::ATTR_PERSISTENT => true, 158 | PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 159 | ); 160 | 161 | /** 162 | * Constructor of Mysqldump. Note that in the case of an SQLite database 163 | * connection, the filename must be in the $db parameter. 164 | * 165 | * @param string $dsn PDO DSN connection string 166 | * @param string $user SQL account username 167 | * @param string $pass SQL account password 168 | * @param array $dumpSettings SQL database settings 169 | * @param array $pdoSettings PDO configured attributes 170 | */ 171 | public function __construct( 172 | $dsn = '', 173 | $user = '', 174 | $pass = '', 175 | $dumpSettings = array(), 176 | $pdoSettings = array() 177 | ) { 178 | 179 | $this->user = $user; 180 | $this->pass = $pass; 181 | $this->parseDsn($dsn); 182 | 183 | // This drops MYSQL dependency, only use the constant if it's defined. 184 | if ("mysql" === $this->dbType) { 185 | $this->pdoSettingsDefault[PDO::MYSQL_ATTR_USE_BUFFERED_QUERY] = false; 186 | } 187 | 188 | $this->pdoSettings = array_replace_recursive($this->pdoSettingsDefault, $pdoSettings); 189 | $this->dumpSettings = array_replace_recursive($this->dumpSettingsDefault, $dumpSettings); 190 | $this->dumpSettings['init_commands'][] = "SET NAMES ".$this->dumpSettings['default-character-set']; 191 | 192 | if (false === $this->dumpSettings['skip-tz-utc']) { 193 | $this->dumpSettings['init_commands'][] = "SET TIME_ZONE='+00:00'"; 194 | } 195 | 196 | $diff = array_diff(array_keys($this->dumpSettings), array_keys($this->dumpSettingsDefault)); 197 | if (count($diff) > 0) { 198 | throw new Exception("Unexpected value in dumpSettings: (".implode(",", $diff).")"); 199 | } 200 | 201 | if (!is_array($this->dumpSettings['include-tables']) || 202 | !is_array($this->dumpSettings['exclude-tables'])) { 203 | throw new Exception("Include-tables and exclude-tables should be arrays"); 204 | } 205 | 206 | // If no include-views is passed in, dump the same views as tables, mimic mysqldump behaviour. 207 | if (!isset($dumpSettings['include-views'])) { 208 | $this->dumpSettings['include-views'] = $this->dumpSettings['include-tables']; 209 | } 210 | 211 | // Create a new compressManager to manage compressed output 212 | $this->compressManager = CompressManagerFactory::create($this->dumpSettings['compress']); 213 | } 214 | 215 | /** 216 | * Destructor of Mysqldump. Unsets dbHandlers and database objects. 217 | */ 218 | public function __destruct() 219 | { 220 | $this->dbHandler = null; 221 | } 222 | 223 | /** 224 | * Keyed by table name, with the value as the conditions: 225 | * e.g. 'users' => 'date_registered > NOW() - INTERVAL 6 MONTH AND deleted=0' 226 | * 227 | * @param array $tableWheres 228 | */ 229 | public function setTableWheres(array $tableWheres) 230 | { 231 | $this->tableWheres = $tableWheres; 232 | } 233 | 234 | /** 235 | * @param $tableName 236 | * 237 | * @return boolean|mixed 238 | */ 239 | public function getTableWhere($tableName) 240 | { 241 | if (!empty($this->tableWheres[$tableName])) { 242 | return $this->tableWheres[$tableName]; 243 | } elseif ($this->dumpSettings['where']) { 244 | return $this->dumpSettings['where']; 245 | } 246 | 247 | return false; 248 | } 249 | 250 | /** 251 | * Keyed by table name, with the value as the numeric limit: 252 | * e.g. 'users' => 3000 253 | * 254 | * @param array $tableLimits 255 | */ 256 | public function setTableLimits(array $tableLimits) 257 | { 258 | $this->tableLimits = $tableLimits; 259 | } 260 | 261 | /** 262 | * Returns the LIMIT for the table. Must be numeric to be returned. 263 | * @param $tableName 264 | * @return boolean 265 | */ 266 | public function getTableLimit($tableName) 267 | { 268 | if (!isset($this->tableLimits[$tableName])) { 269 | return false; 270 | } 271 | 272 | $limit = $this->tableLimits[$tableName]; 273 | if (!is_numeric($limit)) { 274 | return false; 275 | } 276 | 277 | return $limit; 278 | } 279 | 280 | /** 281 | * Import supplied SQL file 282 | * @param string $path Absolute path to imported *.sql file 283 | */ 284 | public function restore($path) 285 | { 286 | if(!$path || !is_file($path)){ 287 | throw new Exception("File {$path} does not exist."); 288 | } 289 | 290 | $handle = fopen($path , 'rb'); 291 | 292 | if(!$handle){ 293 | throw new Exception("Failed reading file {$path}. Check access permissions."); 294 | } 295 | 296 | if(!$this->dbHandler){ 297 | $this->connect(); 298 | } 299 | 300 | $buffer = ''; 301 | while ( !feof($handle) ) { 302 | $line = fgets($handle); 303 | 304 | if (substr($line, 0, 2) == '--' || !$line) { 305 | continue; // skip comments 306 | } 307 | 308 | $buffer .= $line; 309 | 310 | // if it has a semicolon at the end, it's the end of the query 311 | if (';' == substr(rtrim($line), -1, 1)) { 312 | $this->dbHandler->exec($buffer); 313 | $buffer = ''; 314 | } 315 | } 316 | 317 | fclose($handle); 318 | } 319 | 320 | /** 321 | * Parse DSN string and extract dbname value 322 | * Several examples of a DSN string 323 | * mysql:host=localhost;dbname=testdb 324 | * mysql:host=localhost;port=3307;dbname=testdb 325 | * mysql:unix_socket=/tmp/mysql.sock;dbname=testdb 326 | * 327 | * @param string $dsn dsn string to parse 328 | * @return boolean 329 | */ 330 | private function parseDsn($dsn) 331 | { 332 | if (empty($dsn) || (false === ($pos = strpos($dsn, ":")))) { 333 | throw new Exception("Empty DSN string"); 334 | } 335 | 336 | $this->dsn = $dsn; 337 | $this->dbType = strtolower(substr($dsn, 0, $pos)); // always returns a string 338 | 339 | if (empty($this->dbType)) { 340 | throw new Exception("Missing database type from DSN string"); 341 | } 342 | 343 | $dsn = substr($dsn, $pos + 1); 344 | 345 | foreach (explode(";", $dsn) as $kvp) { 346 | $kvpArr = explode("=", $kvp); 347 | $this->dsnArray[strtolower($kvpArr[0])] = $kvpArr[1]; 348 | } 349 | 350 | if (empty($this->dsnArray['host']) && 351 | empty($this->dsnArray['unix_socket'])) { 352 | throw new Exception("Missing host from DSN string"); 353 | } 354 | $this->host = (!empty($this->dsnArray['host'])) ? 355 | $this->dsnArray['host'] : $this->dsnArray['unix_socket']; 356 | 357 | if (empty($this->dsnArray['dbname'])) { 358 | throw new Exception("Missing database name from DSN string"); 359 | } 360 | 361 | $this->dbName = $this->dsnArray['dbname']; 362 | 363 | return true; 364 | } 365 | 366 | /** 367 | * Connect with PDO. 368 | * 369 | * @return null 370 | */ 371 | protected function connect() 372 | { 373 | // Connecting with PDO. 374 | try { 375 | switch ($this->dbType) { 376 | case 'sqlite': 377 | $this->dbHandler = @new PDO("sqlite:".$this->dbName, null, null, $this->pdoSettings); 378 | break; 379 | case 'mysql': 380 | case 'pgsql': 381 | case 'dblib': 382 | $this->dbHandler = @new PDO( 383 | $this->dsn, 384 | $this->user, 385 | $this->pass, 386 | $this->pdoSettings 387 | ); 388 | // Execute init commands once connected 389 | foreach ($this->dumpSettings['init_commands'] as $stmt) { 390 | $this->dbHandler->exec($stmt); 391 | } 392 | // Store server version 393 | $this->version = $this->dbHandler->getAttribute(PDO::ATTR_SERVER_VERSION); 394 | break; 395 | default: 396 | throw new Exception("Unsupported database type (".$this->dbType.")"); 397 | } 398 | } catch (PDOException $e) { 399 | throw new Exception( 400 | "Connection to ".$this->dbType." failed with message: ". 401 | $e->getMessage() 402 | ); 403 | } 404 | 405 | if (is_null($this->dbHandler)) { 406 | throw new Exception("Connection to ".$this->dbType."failed"); 407 | } 408 | 409 | $this->dbHandler->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL); 410 | $this->typeAdapter = TypeAdapterFactory::create($this->dbType, $this->dbHandler, $this->dumpSettings); 411 | } 412 | 413 | /** 414 | * Primary function, triggers dumping. 415 | * 416 | * @param string $filename Name of file to write sql dump to 417 | * @return null 418 | * @throws \Exception 419 | */ 420 | public function start($filename = '') 421 | { 422 | // Output file can be redefined here 423 | if (!empty($filename)) { 424 | $this->fileName = $filename; 425 | } 426 | 427 | // Connect to database 428 | $this->connect(); 429 | 430 | // Create output file 431 | $this->compressManager->open($this->fileName); 432 | 433 | // Write some basic info to output file 434 | $this->compressManager->write($this->getDumpFileHeader()); 435 | 436 | // initiate a transaction at global level to create a consistent snapshot 437 | if ($this->dumpSettings['single-transaction']) { 438 | $this->dbHandler->exec($this->typeAdapter->setup_transaction()); 439 | $this->dbHandler->exec($this->typeAdapter->start_transaction()); 440 | } 441 | 442 | // Store server settings and use sanner defaults to dump 443 | $this->compressManager->write( 444 | $this->typeAdapter->backup_parameters() 445 | ); 446 | 447 | if ($this->dumpSettings['databases']) { 448 | $this->compressManager->write( 449 | $this->typeAdapter->getDatabaseHeader($this->dbName) 450 | ); 451 | if ($this->dumpSettings['add-drop-database']) { 452 | $this->compressManager->write( 453 | $this->typeAdapter->add_drop_database($this->dbName) 454 | ); 455 | } 456 | } 457 | 458 | // Get table, view, trigger, procedures, functions and events structures from 459 | // database. 460 | $this->getDatabaseStructureTables(); 461 | $this->getDatabaseStructureViews(); 462 | $this->getDatabaseStructureTriggers(); 463 | $this->getDatabaseStructureProcedures(); 464 | $this->getDatabaseStructureFunctions(); 465 | $this->getDatabaseStructureEvents(); 466 | 467 | if ($this->dumpSettings['databases']) { 468 | $this->compressManager->write( 469 | $this->typeAdapter->databases($this->dbName) 470 | ); 471 | } 472 | 473 | // If there still are some tables/views in include-tables array, 474 | // that means that some tables or views weren't found. 475 | // Give proper error and exit. 476 | // This check will be removed once include-tables supports regexps. 477 | if (0 < count($this->dumpSettings['include-tables'])) { 478 | $name = implode(",", $this->dumpSettings['include-tables']); 479 | throw new Exception("Table (".$name.") not found in database"); 480 | } 481 | 482 | $this->exportTables(); 483 | $this->exportTriggers(); 484 | $this->exportFunctions(); 485 | $this->exportProcedures(); 486 | $this->exportViews(); 487 | $this->exportEvents(); 488 | 489 | // Restore saved parameters. 490 | $this->compressManager->write( 491 | $this->typeAdapter->restore_parameters() 492 | ); 493 | 494 | // end transaction 495 | if ($this->dumpSettings['single-transaction']) { 496 | $this->dbHandler->exec($this->typeAdapter->commit_transaction()); 497 | } 498 | 499 | // Write some stats to output file. 500 | $this->compressManager->write($this->getDumpFileFooter()); 501 | // Close output file. 502 | $this->compressManager->close(); 503 | 504 | return; 505 | } 506 | 507 | /** 508 | * Returns header for dump file. 509 | * 510 | * @return string 511 | */ 512 | private function getDumpFileHeader() 513 | { 514 | $header = ''; 515 | if (!$this->dumpSettings['skip-comments']) { 516 | // Some info about software, source and time 517 | $header = "-- mysqldump-php https://github.com/ifsnop/mysqldump-php".PHP_EOL. 518 | "--".PHP_EOL. 519 | "-- Host: {$this->host}\tDatabase: {$this->dbName}".PHP_EOL. 520 | "-- ------------------------------------------------------".PHP_EOL; 521 | 522 | if (!empty($this->version)) { 523 | $header .= "-- Server version \t".$this->version.PHP_EOL; 524 | } 525 | 526 | if (!$this->dumpSettings['skip-dump-date']) { 527 | $header .= "-- Date: ".date('r').PHP_EOL.PHP_EOL; 528 | } 529 | } 530 | return $header; 531 | } 532 | 533 | /** 534 | * Returns footer for dump file. 535 | * 536 | * @return string 537 | */ 538 | private function getDumpFileFooter() 539 | { 540 | $footer = ''; 541 | if (!$this->dumpSettings['skip-comments']) { 542 | $footer .= '-- Dump completed'; 543 | if (!$this->dumpSettings['skip-dump-date']) { 544 | $footer .= ' on: '.date('r'); 545 | } 546 | $footer .= PHP_EOL; 547 | } 548 | 549 | return $footer; 550 | } 551 | 552 | /** 553 | * Reads table names from database. 554 | * Fills $this->tables array so they will be dumped later. 555 | * 556 | * @return null 557 | */ 558 | private function getDatabaseStructureTables() 559 | { 560 | // Listing all tables from database 561 | if (empty($this->dumpSettings['include-tables'])) { 562 | // include all tables for now, blacklisting happens later 563 | foreach ($this->dbHandler->query($this->typeAdapter->show_tables($this->dbName)) as $row) { 564 | array_push($this->tables, current($row)); 565 | } 566 | } else { 567 | // include only the tables mentioned in include-tables 568 | foreach ($this->dbHandler->query($this->typeAdapter->show_tables($this->dbName)) as $row) { 569 | if (in_array(current($row), $this->dumpSettings['include-tables'], true)) { 570 | array_push($this->tables, current($row)); 571 | $elem = array_search( 572 | current($row), 573 | $this->dumpSettings['include-tables'] 574 | ); 575 | unset($this->dumpSettings['include-tables'][$elem]); 576 | } 577 | } 578 | } 579 | return; 580 | } 581 | 582 | /** 583 | * Reads view names from database. 584 | * Fills $this->tables array so they will be dumped later. 585 | * 586 | * @return null 587 | */ 588 | private function getDatabaseStructureViews() 589 | { 590 | // Listing all views from database 591 | if (empty($this->dumpSettings['include-views'])) { 592 | // include all views for now, blacklisting happens later 593 | foreach ($this->dbHandler->query($this->typeAdapter->show_views($this->dbName)) as $row) { 594 | array_push($this->views, current($row)); 595 | } 596 | } else { 597 | // include only the tables mentioned in include-tables 598 | foreach ($this->dbHandler->query($this->typeAdapter->show_views($this->dbName)) as $row) { 599 | if (in_array(current($row), $this->dumpSettings['include-views'], true)) { 600 | array_push($this->views, current($row)); 601 | $elem = array_search( 602 | current($row), 603 | $this->dumpSettings['include-views'] 604 | ); 605 | unset($this->dumpSettings['include-views'][$elem]); 606 | } 607 | } 608 | } 609 | return; 610 | } 611 | 612 | /** 613 | * Reads trigger names from database. 614 | * Fills $this->tables array so they will be dumped later. 615 | * 616 | * @return null 617 | */ 618 | private function getDatabaseStructureTriggers() 619 | { 620 | // Listing all triggers from database 621 | if (false === $this->dumpSettings['skip-triggers']) { 622 | foreach ($this->dbHandler->query($this->typeAdapter->show_triggers($this->dbName)) as $row) { 623 | array_push($this->triggers, $row['Trigger']); 624 | } 625 | } 626 | return; 627 | } 628 | 629 | /** 630 | * Reads procedure names from database. 631 | * Fills $this->tables array so they will be dumped later. 632 | * 633 | * @return null 634 | */ 635 | private function getDatabaseStructureProcedures() 636 | { 637 | // Listing all procedures from database 638 | if ($this->dumpSettings['routines']) { 639 | foreach ($this->dbHandler->query($this->typeAdapter->show_procedures($this->dbName)) as $row) { 640 | array_push($this->procedures, $row['procedure_name']); 641 | } 642 | } 643 | return; 644 | } 645 | 646 | /** 647 | * Reads functions names from database. 648 | * Fills $this->tables array so they will be dumped later. 649 | * 650 | * @return null 651 | */ 652 | private function getDatabaseStructureFunctions() 653 | { 654 | // Listing all functions from database 655 | if ($this->dumpSettings['routines']) { 656 | foreach ($this->dbHandler->query($this->typeAdapter->show_functions($this->dbName)) as $row) { 657 | array_push($this->functions, $row['function_name']); 658 | } 659 | } 660 | return; 661 | } 662 | 663 | /** 664 | * Reads event names from database. 665 | * Fills $this->tables array so they will be dumped later. 666 | * 667 | * @return null 668 | */ 669 | private function getDatabaseStructureEvents() 670 | { 671 | // Listing all events from database 672 | if ($this->dumpSettings['events']) { 673 | foreach ($this->dbHandler->query($this->typeAdapter->show_events($this->dbName)) as $row) { 674 | array_push($this->events, $row['event_name']); 675 | } 676 | } 677 | return; 678 | } 679 | 680 | /** 681 | * Compare if $table name matches with a definition inside $arr 682 | * @param $table string 683 | * @param $arr array with strings or patterns 684 | * @return boolean 685 | */ 686 | private function matches($table, $arr) 687 | { 688 | $match = false; 689 | 690 | foreach ($arr as $pattern) { 691 | if ('/' != $pattern[0]) { 692 | continue; 693 | } 694 | if (1 == preg_match($pattern, $table)) { 695 | $match = true; 696 | } 697 | } 698 | 699 | return in_array($table, $arr) || $match; 700 | } 701 | 702 | /** 703 | * Exports all the tables selected from database 704 | * 705 | * @return null 706 | */ 707 | private function exportTables() 708 | { 709 | 710 | 711 | // Exporting tables one by one 712 | foreach ($this->tables as $table) { 713 | if ($this->matches($table, $this->dumpSettings['exclude-tables'])) { 714 | continue; 715 | } 716 | $this->getTableStructure($table); 717 | if (false === $this->dumpSettings['no-data']) { // don't break compatibility with old trigger 718 | $this->listValues($table); 719 | } elseif (true === $this->dumpSettings['no-data'] 720 | || $this->matches($table, $this->dumpSettings['no-data'])) { 721 | continue; 722 | } else { 723 | $this->listValues($table); 724 | } 725 | } 726 | } 727 | 728 | /** 729 | * Exports all the views found in database 730 | * 731 | * @return null 732 | */ 733 | private function exportViews() 734 | { 735 | if (false === $this->dumpSettings['no-create-info']) { 736 | // Exporting views one by one 737 | foreach ($this->views as $view) { 738 | if ($this->matches($view, $this->dumpSettings['exclude-tables'])) { 739 | continue; 740 | } 741 | $this->tableColumnTypes[$view] = $this->getTableColumnTypes($view); 742 | $this->getViewStructureTable($view); 743 | } 744 | foreach ($this->views as $view) { 745 | if ($this->matches($view, $this->dumpSettings['exclude-tables'])) { 746 | continue; 747 | } 748 | $this->getViewStructureView($view); 749 | } 750 | } 751 | } 752 | 753 | /** 754 | * Exports all the triggers found in database 755 | * 756 | * @return null 757 | */ 758 | private function exportTriggers() 759 | { 760 | // Exporting triggers one by one 761 | foreach ($this->triggers as $trigger) { 762 | $this->getTriggerStructure($trigger); 763 | } 764 | 765 | } 766 | 767 | /** 768 | * Exports all the procedures found in database 769 | * 770 | * @return null 771 | */ 772 | private function exportProcedures() 773 | { 774 | // Exporting triggers one by one 775 | foreach ($this->procedures as $procedure) { 776 | $this->getProcedureStructure($procedure); 777 | } 778 | } 779 | 780 | /** 781 | * Exports all the functions found in database 782 | * 783 | * @return null 784 | */ 785 | private function exportFunctions() 786 | { 787 | // Exporting triggers one by one 788 | foreach ($this->functions as $function) { 789 | $this->getFunctionStructure($function); 790 | } 791 | } 792 | 793 | /** 794 | * Exports all the events found in database 795 | * 796 | * @return null 797 | */ 798 | private function exportEvents() 799 | { 800 | // Exporting triggers one by one 801 | foreach ($this->events as $event) { 802 | $this->getEventStructure($event); 803 | } 804 | } 805 | 806 | /** 807 | * Table structure extractor 808 | * 809 | * @todo move specific mysql code to typeAdapter 810 | * @param string $tableName Name of table to export 811 | * @return null 812 | */ 813 | private function getTableStructure($tableName) 814 | { 815 | if (!$this->dumpSettings['no-create-info']) { 816 | $ret = ''; 817 | if (!$this->dumpSettings['skip-comments']) { 818 | $ret = "--".PHP_EOL. 819 | "-- Table structure for table `$tableName`".PHP_EOL. 820 | "--".PHP_EOL.PHP_EOL; 821 | } 822 | $stmt = $this->typeAdapter->show_create_table($tableName); 823 | foreach ($this->dbHandler->query($stmt) as $r) { 824 | $this->compressManager->write($ret); 825 | if ($this->dumpSettings['add-drop-table']) { 826 | $this->compressManager->write( 827 | $this->typeAdapter->drop_table($tableName) 828 | ); 829 | } 830 | $this->compressManager->write( 831 | $this->typeAdapter->create_table($r) 832 | ); 833 | break; 834 | } 835 | } 836 | $this->tableColumnTypes[$tableName] = $this->getTableColumnTypes($tableName); 837 | return; 838 | } 839 | 840 | /** 841 | * Store column types to create data dumps and for Stand-In tables 842 | * 843 | * @param string $tableName Name of table to export 844 | * @return array type column types detailed 845 | */ 846 | 847 | private function getTableColumnTypes($tableName) 848 | { 849 | $columnTypes = array(); 850 | $columns = $this->dbHandler->query( 851 | $this->typeAdapter->show_columns($tableName) 852 | ); 853 | $columns->setFetchMode(PDO::FETCH_ASSOC); 854 | 855 | foreach ($columns as $key => $col) { 856 | $types = $this->typeAdapter->parseColumnType($col); 857 | $columnTypes[$col['Field']] = array( 858 | 'is_numeric'=> $types['is_numeric'], 859 | 'is_blob' => $types['is_blob'], 860 | 'type' => $types['type'], 861 | 'type_sql' => $col['Type'], 862 | 'is_virtual' => $types['is_virtual'] 863 | ); 864 | } 865 | 866 | return $columnTypes; 867 | } 868 | 869 | /** 870 | * View structure extractor, create table (avoids cyclic references) 871 | * 872 | * @todo move mysql specific code to typeAdapter 873 | * @param string $viewName Name of view to export 874 | * @return null 875 | */ 876 | private function getViewStructureTable($viewName) 877 | { 878 | if (!$this->dumpSettings['skip-comments']) { 879 | $ret = "--".PHP_EOL. 880 | "-- Stand-In structure for view `{$viewName}`".PHP_EOL. 881 | "--".PHP_EOL.PHP_EOL; 882 | $this->compressManager->write($ret); 883 | } 884 | $stmt = $this->typeAdapter->show_create_view($viewName); 885 | 886 | // create views as tables, to resolve dependencies 887 | foreach ($this->dbHandler->query($stmt) as $r) { 888 | if ($this->dumpSettings['add-drop-table']) { 889 | $this->compressManager->write( 890 | $this->typeAdapter->drop_view($viewName) 891 | ); 892 | } 893 | 894 | $this->compressManager->write( 895 | $this->createStandInTable($viewName) 896 | ); 897 | break; 898 | } 899 | } 900 | 901 | /** 902 | * Write a create table statement for the table Stand-In, show create 903 | * table would return a create algorithm when used on a view 904 | * 905 | * @param string $viewName Name of view to export 906 | * @return string create statement 907 | */ 908 | public function createStandInTable($viewName) 909 | { 910 | $ret = array(); 911 | foreach ($this->tableColumnTypes[$viewName] as $k => $v) { 912 | $ret[] = "`{$k}` {$v['type_sql']}"; 913 | } 914 | $ret = implode(PHP_EOL.",", $ret); 915 | 916 | $ret = "CREATE TABLE IF NOT EXISTS `$viewName` (". 917 | PHP_EOL.$ret.PHP_EOL.");".PHP_EOL; 918 | 919 | return $ret; 920 | } 921 | 922 | /** 923 | * View structure extractor, create view 924 | * 925 | * @todo move mysql specific code to typeAdapter 926 | * @param string $viewName Name of view to export 927 | * @return null 928 | */ 929 | private function getViewStructureView($viewName) 930 | { 931 | if (!$this->dumpSettings['skip-comments']) { 932 | $ret = "--".PHP_EOL. 933 | "-- View structure for view `{$viewName}`".PHP_EOL. 934 | "--".PHP_EOL.PHP_EOL; 935 | $this->compressManager->write($ret); 936 | } 937 | $stmt = $this->typeAdapter->show_create_view($viewName); 938 | 939 | // create views, to resolve dependencies 940 | // replacing tables with views 941 | foreach ($this->dbHandler->query($stmt) as $r) { 942 | // because we must replace table with view, we should delete it 943 | $this->compressManager->write( 944 | $this->typeAdapter->drop_view($viewName) 945 | ); 946 | $this->compressManager->write( 947 | $this->typeAdapter->create_view($r) 948 | ); 949 | break; 950 | } 951 | } 952 | 953 | /** 954 | * Trigger structure extractor 955 | * 956 | * @param string $triggerName Name of trigger to export 957 | * @return null 958 | */ 959 | private function getTriggerStructure($triggerName) 960 | { 961 | $stmt = $this->typeAdapter->show_create_trigger($triggerName); 962 | foreach ($this->dbHandler->query($stmt) as $r) { 963 | if ($this->dumpSettings['add-drop-trigger']) { 964 | $this->compressManager->write( 965 | $this->typeAdapter->add_drop_trigger($triggerName) 966 | ); 967 | } 968 | $this->compressManager->write( 969 | $this->typeAdapter->create_trigger($r) 970 | ); 971 | return; 972 | } 973 | } 974 | 975 | /** 976 | * Procedure structure extractor 977 | * 978 | * @param string $procedureName Name of procedure to export 979 | * @return null 980 | */ 981 | private function getProcedureStructure($procedureName) 982 | { 983 | if (!$this->dumpSettings['skip-comments']) { 984 | $ret = "--".PHP_EOL. 985 | "-- Dumping routines for database '".$this->dbName."'".PHP_EOL. 986 | "--".PHP_EOL.PHP_EOL; 987 | $this->compressManager->write($ret); 988 | } 989 | $stmt = $this->typeAdapter->show_create_procedure($procedureName); 990 | foreach ($this->dbHandler->query($stmt) as $r) { 991 | $this->compressManager->write( 992 | $this->typeAdapter->create_procedure($r) 993 | ); 994 | return; 995 | } 996 | } 997 | 998 | /** 999 | * Function structure extractor 1000 | * 1001 | * @param string $functionName Name of function to export 1002 | * @return null 1003 | */ 1004 | private function getFunctionStructure($functionName) 1005 | { 1006 | if (!$this->dumpSettings['skip-comments']) { 1007 | $ret = "--".PHP_EOL. 1008 | "-- Dumping routines for database '".$this->dbName."'".PHP_EOL. 1009 | "--".PHP_EOL.PHP_EOL; 1010 | $this->compressManager->write($ret); 1011 | } 1012 | $stmt = $this->typeAdapter->show_create_function($functionName); 1013 | foreach ($this->dbHandler->query($stmt) as $r) { 1014 | $this->compressManager->write( 1015 | $this->typeAdapter->create_function($r) 1016 | ); 1017 | return; 1018 | } 1019 | } 1020 | 1021 | /** 1022 | * Event structure extractor 1023 | * 1024 | * @param string $eventName Name of event to export 1025 | * @return null 1026 | */ 1027 | private function getEventStructure($eventName) 1028 | { 1029 | if (!$this->dumpSettings['skip-comments']) { 1030 | $ret = "--".PHP_EOL. 1031 | "-- Dumping events for database '".$this->dbName."'".PHP_EOL. 1032 | "--".PHP_EOL.PHP_EOL; 1033 | $this->compressManager->write($ret); 1034 | } 1035 | $stmt = $this->typeAdapter->show_create_event($eventName); 1036 | foreach ($this->dbHandler->query($stmt) as $r) { 1037 | $this->compressManager->write( 1038 | $this->typeAdapter->create_event($r) 1039 | ); 1040 | return; 1041 | } 1042 | } 1043 | 1044 | /** 1045 | * Prepare values for output 1046 | * 1047 | * @param string $tableName Name of table which contains rows 1048 | * @param array $row Associative array of column names and values to be 1049 | * quoted 1050 | * 1051 | * @return array 1052 | */ 1053 | private function prepareColumnValues($tableName, array $row) 1054 | { 1055 | $ret = array(); 1056 | $columnTypes = $this->tableColumnTypes[$tableName]; 1057 | 1058 | if ($this->transformTableRowCallable) { 1059 | $row = call_user_func($this->transformTableRowCallable, $tableName, $row); 1060 | } 1061 | 1062 | foreach ($row as $colName => $colValue) { 1063 | if ($this->transformColumnValueCallable) { 1064 | $colValue = call_user_func($this->transformColumnValueCallable, $tableName, $colName, $colValue, $row); 1065 | } 1066 | 1067 | $ret[] = $this->escape($colValue, $columnTypes[$colName]); 1068 | } 1069 | 1070 | return $ret; 1071 | } 1072 | 1073 | /** 1074 | * Escape values with quotes when needed 1075 | * 1076 | * @param string $tableName Name of table which contains rows 1077 | * @param array $row Associative array of column names and values to be quoted 1078 | * 1079 | * @return string 1080 | */ 1081 | private function escape($colValue, $colType) 1082 | { 1083 | if (is_null($colValue)) { 1084 | return "NULL"; 1085 | } elseif ($this->dumpSettings['hex-blob'] && $colType['is_blob']) { 1086 | if ($colType['type'] == 'bit' || !empty($colValue)) { 1087 | return "0x{$colValue}"; 1088 | } else { 1089 | return "''"; 1090 | } 1091 | } elseif ($colType['is_numeric']) { 1092 | return $colValue; 1093 | } 1094 | 1095 | return $this->dbHandler->quote($colValue); 1096 | } 1097 | 1098 | /** 1099 | * Set a callable that will be used to transform table rows 1100 | * 1101 | * @param callable $callable 1102 | * 1103 | * @return void 1104 | */ 1105 | public function setTransformTableRowHook($callable) 1106 | { 1107 | $this->transformTableRowCallable = $callable; 1108 | } 1109 | 1110 | /** 1111 | * Set a callable that will be used to transform column values 1112 | * 1113 | * @param callable $callable 1114 | * 1115 | * @return void 1116 | * 1117 | * @deprecated Use setTransformTableRowHook instead for better performance 1118 | */ 1119 | public function setTransformColumnValueHook($callable) 1120 | { 1121 | $this->transformColumnValueCallable = $callable; 1122 | } 1123 | 1124 | /** 1125 | * Set a callable that will be used to report dump information 1126 | * 1127 | * @param callable $callable 1128 | * 1129 | * @return void 1130 | */ 1131 | public function setInfoHook($callable) 1132 | { 1133 | $this->infoCallable = $callable; 1134 | } 1135 | 1136 | /** 1137 | * Table rows extractor 1138 | * 1139 | * @param string $tableName Name of table to export 1140 | * 1141 | * @return null 1142 | */ 1143 | private function listValues($tableName) 1144 | { 1145 | $this->prepareListValues($tableName); 1146 | 1147 | $onlyOnce = true; 1148 | 1149 | // colStmt is used to form a query to obtain row values 1150 | $colStmt = $this->getColumnStmt($tableName); 1151 | // colNames is used to get the name of the columns when using complete-insert 1152 | if ($this->dumpSettings['complete-insert']) { 1153 | $colNames = $this->getColumnNames($tableName); 1154 | } 1155 | 1156 | $stmt = "SELECT ".implode(",", $colStmt)." FROM `$tableName`"; 1157 | 1158 | // Table specific conditions override the default 'where' 1159 | $condition = $this->getTableWhere($tableName); 1160 | 1161 | if ($condition) { 1162 | $stmt .= " WHERE {$condition}"; 1163 | } 1164 | 1165 | $limit = $this->getTableLimit($tableName); 1166 | 1167 | if ($limit !== false) { 1168 | $stmt .= " LIMIT {$limit}"; 1169 | } 1170 | 1171 | $resultSet = $this->dbHandler->query($stmt); 1172 | $resultSet->setFetchMode(PDO::FETCH_ASSOC); 1173 | 1174 | $ignore = $this->dumpSettings['insert-ignore'] ? ' IGNORE' : ''; 1175 | 1176 | $count = 0; 1177 | $line = ''; 1178 | foreach ($resultSet as $row) { 1179 | $count++; 1180 | $vals = $this->prepareColumnValues($tableName, $row); 1181 | if ($onlyOnce || !$this->dumpSettings['extended-insert']) { 1182 | if ($this->dumpSettings['complete-insert']) { 1183 | $line .= "INSERT$ignore INTO `$tableName` (". 1184 | implode(", ", $colNames). 1185 | ") VALUES (".implode(",", $vals).")"; 1186 | } else { 1187 | $line .= "INSERT$ignore INTO `$tableName` VALUES (".implode(",", $vals).")"; 1188 | } 1189 | $onlyOnce = false; 1190 | } else { 1191 | $line .= ",(".implode(",", $vals).")"; 1192 | } 1193 | if ((strlen($line) > $this->dumpSettings['net_buffer_length']) || 1194 | !$this->dumpSettings['extended-insert']) { 1195 | $onlyOnce = true; 1196 | $this->compressManager->write($line . ";".PHP_EOL); 1197 | $line = ''; 1198 | } 1199 | } 1200 | $resultSet->closeCursor(); 1201 | 1202 | if ('' !== $line) { 1203 | $this->compressManager->write($line. ";".PHP_EOL); 1204 | } 1205 | 1206 | $this->endListValues($tableName, $count); 1207 | 1208 | if ($this->infoCallable) { 1209 | call_user_func($this->infoCallable, 'table', array('name' => $tableName, 'rowCount' => $count)); 1210 | } 1211 | } 1212 | 1213 | /** 1214 | * Table rows extractor, append information prior to dump 1215 | * 1216 | * @param string $tableName Name of table to export 1217 | * 1218 | * @return null 1219 | */ 1220 | public function prepareListValues($tableName) 1221 | { 1222 | if (!$this->dumpSettings['skip-comments']) { 1223 | $this->compressManager->write( 1224 | "--".PHP_EOL. 1225 | "-- Dumping data for table `$tableName`".PHP_EOL. 1226 | "--".PHP_EOL.PHP_EOL 1227 | ); 1228 | } 1229 | 1230 | if ($this->dumpSettings['lock-tables'] && !$this->dumpSettings['single-transaction']) { 1231 | $this->typeAdapter->lock_table($tableName); 1232 | } 1233 | 1234 | if ($this->dumpSettings['add-locks']) { 1235 | $this->compressManager->write( 1236 | $this->typeAdapter->start_add_lock_table($tableName) 1237 | ); 1238 | } 1239 | 1240 | if ($this->dumpSettings['disable-keys']) { 1241 | $this->compressManager->write( 1242 | $this->typeAdapter->start_add_disable_keys($tableName) 1243 | ); 1244 | } 1245 | 1246 | // Disable autocommit for faster reload 1247 | if ($this->dumpSettings['no-autocommit']) { 1248 | $this->compressManager->write( 1249 | $this->typeAdapter->start_disable_autocommit() 1250 | ); 1251 | } 1252 | 1253 | return; 1254 | } 1255 | 1256 | /** 1257 | * Table rows extractor, close locks and commits after dump 1258 | * 1259 | * @param string $tableName Name of table to export. 1260 | * @param integer $count Number of rows inserted. 1261 | * 1262 | * @return void 1263 | */ 1264 | public function endListValues($tableName, $count = 0) 1265 | { 1266 | if ($this->dumpSettings['disable-keys']) { 1267 | $this->compressManager->write( 1268 | $this->typeAdapter->end_add_disable_keys($tableName) 1269 | ); 1270 | } 1271 | 1272 | if ($this->dumpSettings['add-locks']) { 1273 | $this->compressManager->write( 1274 | $this->typeAdapter->end_add_lock_table($tableName) 1275 | ); 1276 | } 1277 | 1278 | if ($this->dumpSettings['lock-tables'] && !$this->dumpSettings['single-transaction']) { 1279 | $this->typeAdapter->unlock_table($tableName); 1280 | } 1281 | 1282 | // Commit to enable autocommit 1283 | if ($this->dumpSettings['no-autocommit']) { 1284 | $this->compressManager->write( 1285 | $this->typeAdapter->end_disable_autocommit() 1286 | ); 1287 | } 1288 | 1289 | $this->compressManager->write(PHP_EOL); 1290 | 1291 | if (!$this->dumpSettings['skip-comments']) { 1292 | $this->compressManager->write( 1293 | "-- Dumped table `".$tableName."` with $count row(s)".PHP_EOL. 1294 | '--'.PHP_EOL.PHP_EOL 1295 | ); 1296 | } 1297 | 1298 | return; 1299 | } 1300 | 1301 | /** 1302 | * Build SQL List of all columns on current table which will be used for selecting 1303 | * 1304 | * @param string $tableName Name of table to get columns 1305 | * 1306 | * @return array SQL sentence with columns for select 1307 | */ 1308 | public function getColumnStmt($tableName) 1309 | { 1310 | $colStmt = array(); 1311 | foreach ($this->tableColumnTypes[$tableName] as $colName => $colType) { 1312 | if ($colType['is_virtual']) { 1313 | $this->dumpSettings['complete-insert'] = true; 1314 | continue; 1315 | } elseif ($colType['type'] == 'bit' && $this->dumpSettings['hex-blob']) { 1316 | $colStmt[] = "LPAD(HEX(`{$colName}`),2,'0') AS `{$colName}`"; 1317 | } elseif ($colType['type'] == 'double' && PHP_VERSION_ID > 80100) { 1318 | $colStmt[] = sprintf("CONCAT(`%s`) AS `%s`", $colName, $colName); 1319 | } elseif ($colType['is_blob'] && $this->dumpSettings['hex-blob']) { 1320 | $colStmt[] = "HEX(`{$colName}`) AS `{$colName}`"; 1321 | } else { 1322 | $colStmt[] = "`{$colName}`"; 1323 | } 1324 | } 1325 | 1326 | return $colStmt; 1327 | } 1328 | 1329 | /** 1330 | * Build SQL List of all columns on current table which will be used for inserting 1331 | * 1332 | * @param string $tableName Name of table to get columns 1333 | * 1334 | * @return array columns for sql sentence for insert 1335 | */ 1336 | public function getColumnNames($tableName) 1337 | { 1338 | $colNames = array(); 1339 | foreach ($this->tableColumnTypes[$tableName] as $colName => $colType) { 1340 | if ($colType['is_virtual']) { 1341 | $this->dumpSettings['complete-insert'] = true; 1342 | continue; 1343 | } else { 1344 | $colNames[] = "`{$colName}`"; 1345 | } 1346 | } 1347 | return $colNames; 1348 | } 1349 | } 1350 | 1351 | /** 1352 | * Enum with all available compression methods 1353 | * 1354 | */ 1355 | abstract class CompressMethod 1356 | { 1357 | public static $enums = array( 1358 | Mysqldump::NONE, 1359 | Mysqldump::GZIP, 1360 | Mysqldump::BZIP2, 1361 | Mysqldump::GZIPSTREAM, 1362 | ); 1363 | 1364 | /** 1365 | * @param string $c 1366 | * @return boolean 1367 | */ 1368 | public static function isValid($c) 1369 | { 1370 | return in_array($c, self::$enums); 1371 | } 1372 | } 1373 | 1374 | abstract class CompressManagerFactory 1375 | { 1376 | /** 1377 | * @param string $c 1378 | * @return CompressBzip2|CompressGzip|CompressNone 1379 | */ 1380 | public static function create($c) 1381 | { 1382 | $c = ucfirst(strtolower($c)); 1383 | if (!CompressMethod::isValid($c)) { 1384 | throw new Exception("Compression method ($c) is not defined yet"); 1385 | } 1386 | 1387 | $method = __NAMESPACE__."\\"."Compress".$c; 1388 | 1389 | return new $method; 1390 | } 1391 | } 1392 | 1393 | class CompressBzip2 extends CompressManagerFactory 1394 | { 1395 | private $fileHandler = null; 1396 | 1397 | public function __construct() 1398 | { 1399 | if (!function_exists("bzopen")) { 1400 | throw new Exception("Compression is enabled, but bzip2 lib is not installed or configured properly"); 1401 | } 1402 | } 1403 | 1404 | /** 1405 | * @param string $filename 1406 | */ 1407 | public function open($filename) 1408 | { 1409 | $this->fileHandler = bzopen($filename, "w"); 1410 | if (false === $this->fileHandler) { 1411 | throw new Exception("Output file is not writable"); 1412 | } 1413 | 1414 | return true; 1415 | } 1416 | 1417 | public function write($str) 1418 | { 1419 | $bytesWritten = bzwrite($this->fileHandler, $str); 1420 | if (false === $bytesWritten) { 1421 | throw new Exception("Writting to file failed! Probably, there is no more free space left?"); 1422 | } 1423 | return $bytesWritten; 1424 | } 1425 | 1426 | public function close() 1427 | { 1428 | return bzclose($this->fileHandler); 1429 | } 1430 | } 1431 | 1432 | class CompressGzip extends CompressManagerFactory 1433 | { 1434 | private $fileHandler = null; 1435 | 1436 | public function __construct() 1437 | { 1438 | if (!function_exists("gzopen")) { 1439 | throw new Exception("Compression is enabled, but gzip lib is not installed or configured properly"); 1440 | } 1441 | } 1442 | 1443 | /** 1444 | * @param string $filename 1445 | */ 1446 | public function open($filename) 1447 | { 1448 | $this->fileHandler = gzopen($filename, "wb"); 1449 | if (false === $this->fileHandler) { 1450 | throw new Exception("Output file is not writable"); 1451 | } 1452 | 1453 | return true; 1454 | } 1455 | 1456 | public function write($str) 1457 | { 1458 | $bytesWritten = gzwrite($this->fileHandler, $str); 1459 | if (false === $bytesWritten) { 1460 | throw new Exception("Writting to file failed! Probably, there is no more free space left?"); 1461 | } 1462 | return $bytesWritten; 1463 | } 1464 | 1465 | public function close() 1466 | { 1467 | return gzclose($this->fileHandler); 1468 | } 1469 | } 1470 | 1471 | class CompressNone extends CompressManagerFactory 1472 | { 1473 | private $fileHandler = null; 1474 | 1475 | /** 1476 | * @param string $filename 1477 | */ 1478 | public function open($filename) 1479 | { 1480 | $this->fileHandler = fopen($filename, "wb"); 1481 | if (false === $this->fileHandler) { 1482 | throw new Exception("Output file is not writable"); 1483 | } 1484 | 1485 | return true; 1486 | } 1487 | 1488 | public function write($str) 1489 | { 1490 | $bytesWritten = fwrite($this->fileHandler, $str); 1491 | if (false === $bytesWritten) { 1492 | throw new Exception("Writting to file failed! Probably, there is no more free space left?"); 1493 | } 1494 | return $bytesWritten; 1495 | } 1496 | 1497 | public function close() 1498 | { 1499 | return fclose($this->fileHandler); 1500 | } 1501 | } 1502 | 1503 | class CompressGzipstream extends CompressManagerFactory 1504 | { 1505 | private $fileHandler = null; 1506 | 1507 | private $compressContext; 1508 | 1509 | /** 1510 | * @param string $filename 1511 | */ 1512 | public function open($filename) 1513 | { 1514 | $this->fileHandler = fopen($filename, "wb"); 1515 | if (false === $this->fileHandler) { 1516 | throw new Exception("Output file is not writable"); 1517 | } 1518 | 1519 | $this->compressContext = deflate_init(ZLIB_ENCODING_GZIP, array('level' => 9)); 1520 | return true; 1521 | } 1522 | 1523 | public function write($str) 1524 | { 1525 | 1526 | $bytesWritten = fwrite($this->fileHandler, deflate_add($this->compressContext, $str, ZLIB_NO_FLUSH)); 1527 | if (false === $bytesWritten) { 1528 | throw new Exception("Writting to file failed! Probably, there is no more free space left?"); 1529 | } 1530 | return $bytesWritten; 1531 | } 1532 | 1533 | public function close() 1534 | { 1535 | fwrite($this->fileHandler, deflate_add($this->compressContext, '', ZLIB_FINISH)); 1536 | return fclose($this->fileHandler); 1537 | } 1538 | } 1539 | 1540 | /** 1541 | * Enum with all available TypeAdapter implementations 1542 | * 1543 | */ 1544 | abstract class TypeAdapter 1545 | { 1546 | public static $enums = array( 1547 | "Sqlite", 1548 | "Mysql" 1549 | ); 1550 | 1551 | /** 1552 | * @param string $c 1553 | * @return boolean 1554 | */ 1555 | public static function isValid($c) 1556 | { 1557 | return in_array($c, self::$enums); 1558 | } 1559 | } 1560 | 1561 | /** 1562 | * TypeAdapter Factory 1563 | * 1564 | */ 1565 | abstract class TypeAdapterFactory 1566 | { 1567 | protected $dbHandler = null; 1568 | protected $dumpSettings = array(); 1569 | 1570 | /** 1571 | * @param string $c Type of database factory to create (Mysql, Sqlite,...) 1572 | * @param PDO $dbHandler 1573 | */ 1574 | public static function create($c, $dbHandler = null, $dumpSettings = array()) 1575 | { 1576 | $c = ucfirst(strtolower($c)); 1577 | if (!TypeAdapter::isValid($c)) { 1578 | throw new Exception("Database type support for ($c) not yet available"); 1579 | } 1580 | $method = __NAMESPACE__."\\"."TypeAdapter".$c; 1581 | return new $method($dbHandler, $dumpSettings); 1582 | } 1583 | 1584 | public function __construct($dbHandler = null, $dumpSettings = array()) 1585 | { 1586 | $this->dbHandler = $dbHandler; 1587 | $this->dumpSettings = $dumpSettings; 1588 | } 1589 | 1590 | /** 1591 | * function databases Add sql to create and use database 1592 | * @todo make it do something with sqlite 1593 | */ 1594 | public function databases() 1595 | { 1596 | return ""; 1597 | } 1598 | 1599 | public function show_create_table($tableName) 1600 | { 1601 | return "SELECT tbl_name as 'Table', sql as 'Create Table' ". 1602 | "FROM sqlite_master ". 1603 | "WHERE type='table' AND tbl_name='$tableName'"; 1604 | } 1605 | 1606 | /** 1607 | * function create_table Get table creation code from database 1608 | * @todo make it do something with sqlite 1609 | */ 1610 | public function create_table($row) 1611 | { 1612 | return ""; 1613 | } 1614 | 1615 | public function show_create_view($viewName) 1616 | { 1617 | return "SELECT tbl_name as 'View', sql as 'Create View' ". 1618 | "FROM sqlite_master ". 1619 | "WHERE type='view' AND tbl_name='$viewName'"; 1620 | } 1621 | 1622 | /** 1623 | * function create_view Get view creation code from database 1624 | * @todo make it do something with sqlite 1625 | */ 1626 | public function create_view($row) 1627 | { 1628 | return ""; 1629 | } 1630 | 1631 | /** 1632 | * function show_create_trigger Get trigger creation code from database 1633 | * @todo make it do something with sqlite 1634 | */ 1635 | public function show_create_trigger($triggerName) 1636 | { 1637 | return ""; 1638 | } 1639 | 1640 | /** 1641 | * function create_trigger Modify trigger code, add delimiters, etc 1642 | * @todo make it do something with sqlite 1643 | */ 1644 | public function create_trigger($triggerName) 1645 | { 1646 | return ""; 1647 | } 1648 | 1649 | /** 1650 | * function create_procedure Modify procedure code, add delimiters, etc 1651 | * @todo make it do something with sqlite 1652 | */ 1653 | public function create_procedure($procedureName) 1654 | { 1655 | return ""; 1656 | } 1657 | 1658 | /** 1659 | * function create_function Modify function code, add delimiters, etc 1660 | * @todo make it do something with sqlite 1661 | */ 1662 | public function create_function($functionName) 1663 | { 1664 | return ""; 1665 | } 1666 | 1667 | public function show_tables() 1668 | { 1669 | return "SELECT tbl_name FROM sqlite_master WHERE type='table'"; 1670 | } 1671 | 1672 | public function show_views() 1673 | { 1674 | return "SELECT tbl_name FROM sqlite_master WHERE type='view'"; 1675 | } 1676 | 1677 | public function show_triggers() 1678 | { 1679 | return "SELECT name FROM sqlite_master WHERE type='trigger'"; 1680 | } 1681 | 1682 | public function show_columns() 1683 | { 1684 | if (func_num_args() != 1) { 1685 | return ""; 1686 | } 1687 | 1688 | $args = func_get_args(); 1689 | 1690 | return "pragma table_info({$args[0]})"; 1691 | } 1692 | 1693 | public function show_procedures() 1694 | { 1695 | return ""; 1696 | } 1697 | 1698 | public function show_functions() 1699 | { 1700 | return ""; 1701 | } 1702 | 1703 | public function show_events() 1704 | { 1705 | return ""; 1706 | } 1707 | 1708 | public function setup_transaction() 1709 | { 1710 | return ""; 1711 | } 1712 | 1713 | public function start_transaction() 1714 | { 1715 | return "BEGIN EXCLUSIVE"; 1716 | } 1717 | 1718 | public function commit_transaction() 1719 | { 1720 | return "COMMIT"; 1721 | } 1722 | 1723 | public function lock_table() 1724 | { 1725 | return ""; 1726 | } 1727 | 1728 | public function unlock_table() 1729 | { 1730 | return ""; 1731 | } 1732 | 1733 | public function start_add_lock_table() 1734 | { 1735 | return PHP_EOL; 1736 | } 1737 | 1738 | public function end_add_lock_table() 1739 | { 1740 | return PHP_EOL; 1741 | } 1742 | 1743 | public function start_add_disable_keys() 1744 | { 1745 | return PHP_EOL; 1746 | } 1747 | 1748 | public function end_add_disable_keys() 1749 | { 1750 | return PHP_EOL; 1751 | } 1752 | 1753 | public function start_disable_foreign_keys_check() 1754 | { 1755 | return PHP_EOL; 1756 | } 1757 | 1758 | public function end_disable_foreign_keys_check() 1759 | { 1760 | return PHP_EOL; 1761 | } 1762 | 1763 | public function add_drop_database() 1764 | { 1765 | return PHP_EOL; 1766 | } 1767 | 1768 | public function add_drop_trigger() 1769 | { 1770 | return PHP_EOL; 1771 | } 1772 | 1773 | public function drop_table() 1774 | { 1775 | return PHP_EOL; 1776 | } 1777 | 1778 | public function drop_view() 1779 | { 1780 | return PHP_EOL; 1781 | } 1782 | 1783 | /** 1784 | * Decode column metadata and fill info structure. 1785 | * type, is_numeric and is_blob will always be available. 1786 | * 1787 | * @param array $colType Array returned from "SHOW COLUMNS FROM tableName" 1788 | * @return array 1789 | */ 1790 | public function parseColumnType($colType) 1791 | { 1792 | return array(); 1793 | } 1794 | 1795 | public function backup_parameters() 1796 | { 1797 | return PHP_EOL; 1798 | } 1799 | 1800 | public function restore_parameters() 1801 | { 1802 | return PHP_EOL; 1803 | } 1804 | } 1805 | 1806 | class TypeAdapterPgsql extends TypeAdapterFactory 1807 | { 1808 | } 1809 | 1810 | class TypeAdapterDblib extends TypeAdapterFactory 1811 | { 1812 | } 1813 | 1814 | class TypeAdapterSqlite extends TypeAdapterFactory 1815 | { 1816 | } 1817 | 1818 | class TypeAdapterMysql extends TypeAdapterFactory 1819 | { 1820 | const DEFINER_RE = 'DEFINER=`(?:[^`]|``)*`@`(?:[^`]|``)*`'; 1821 | 1822 | 1823 | // Numerical Mysql types 1824 | public $mysqlTypes = array( 1825 | 'numerical' => array( 1826 | 'bit', 1827 | 'tinyint', 1828 | 'smallint', 1829 | 'mediumint', 1830 | 'int', 1831 | 'integer', 1832 | 'bigint', 1833 | 'real', 1834 | 'double', 1835 | 'float', 1836 | 'decimal', 1837 | 'numeric' 1838 | ), 1839 | 'blob' => array( 1840 | 'tinyblob', 1841 | 'blob', 1842 | 'mediumblob', 1843 | 'longblob', 1844 | 'binary', 1845 | 'varbinary', 1846 | 'bit', 1847 | 'geometry', /* http://bugs.mysql.com/bug.php?id=43544 */ 1848 | 'point', 1849 | 'linestring', 1850 | 'polygon', 1851 | 'multipoint', 1852 | 'multilinestring', 1853 | 'multipolygon', 1854 | 'geometrycollection', 1855 | ) 1856 | ); 1857 | 1858 | public function databases() 1859 | { 1860 | if ($this->dumpSettings['no-create-db']) { 1861 | return ""; 1862 | } 1863 | 1864 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 1865 | $args = func_get_args(); 1866 | $databaseName = $args[0]; 1867 | 1868 | $resultSet = $this->dbHandler->query("SHOW VARIABLES LIKE 'character_set_database';"); 1869 | $characterSet = $resultSet->fetchColumn(1); 1870 | $resultSet->closeCursor(); 1871 | 1872 | $resultSet = $this->dbHandler->query("SHOW VARIABLES LIKE 'collation_database';"); 1873 | $collationDb = $resultSet->fetchColumn(1); 1874 | $resultSet->closeCursor(); 1875 | $ret = ""; 1876 | 1877 | $ret .= "CREATE DATABASE /*!32312 IF NOT EXISTS*/ `{$databaseName}`". 1878 | " /*!40100 DEFAULT CHARACTER SET {$characterSet} ". 1879 | " COLLATE {$collationDb} */;".PHP_EOL.PHP_EOL. 1880 | "USE `{$databaseName}`;".PHP_EOL.PHP_EOL; 1881 | 1882 | return $ret; 1883 | } 1884 | 1885 | public function show_create_table($tableName) 1886 | { 1887 | return "SHOW CREATE TABLE `$tableName`"; 1888 | } 1889 | 1890 | public function show_create_view($viewName) 1891 | { 1892 | return "SHOW CREATE VIEW `$viewName`"; 1893 | } 1894 | 1895 | public function show_create_trigger($triggerName) 1896 | { 1897 | return "SHOW CREATE TRIGGER `$triggerName`"; 1898 | } 1899 | 1900 | public function show_create_procedure($procedureName) 1901 | { 1902 | return "SHOW CREATE PROCEDURE `$procedureName`"; 1903 | } 1904 | 1905 | public function show_create_function($functionName) 1906 | { 1907 | return "SHOW CREATE FUNCTION `$functionName`"; 1908 | } 1909 | 1910 | public function show_create_event($eventName) 1911 | { 1912 | return "SHOW CREATE EVENT `$eventName`"; 1913 | } 1914 | 1915 | public function create_table($row) 1916 | { 1917 | if (!isset($row['Create Table'])) { 1918 | throw new Exception("Error getting table code, unknown output"); 1919 | } 1920 | 1921 | $createTable = $row['Create Table']; 1922 | if ($this->dumpSettings['reset-auto-increment']) { 1923 | $match = "/AUTO_INCREMENT=[0-9]+/s"; 1924 | $replace = ""; 1925 | $createTable = preg_replace($match, $replace, $createTable); 1926 | } 1927 | 1928 | if ($this->dumpSettings['if-not-exists'] ) { 1929 | $createTable = preg_replace('/^CREATE TABLE/', 'CREATE TABLE IF NOT EXISTS', $createTable); 1930 | } 1931 | 1932 | $ret = "/*!40101 SET @saved_cs_client = @@character_set_client */;".PHP_EOL. 1933 | "/*!40101 SET character_set_client = ".$this->dumpSettings['default-character-set']." */;".PHP_EOL. 1934 | $createTable.";".PHP_EOL. 1935 | "/*!40101 SET character_set_client = @saved_cs_client */;".PHP_EOL. 1936 | PHP_EOL; 1937 | return $ret; 1938 | } 1939 | 1940 | public function create_view($row) 1941 | { 1942 | $ret = ""; 1943 | if (!isset($row['Create View'])) { 1944 | throw new Exception("Error getting view structure, unknown output"); 1945 | } 1946 | 1947 | $viewStmt = $row['Create View']; 1948 | 1949 | $definerStr = $this->dumpSettings['skip-definer'] ? '' : '/*!50013 \2 */'.PHP_EOL; 1950 | 1951 | if ($viewStmtReplaced = preg_replace( 1952 | '/^(CREATE(?:\s+ALGORITHM=(?:UNDEFINED|MERGE|TEMPTABLE))?)\s+(' 1953 | .self::DEFINER_RE.'(?:\s+SQL SECURITY (?:DEFINER|INVOKER))?)?\s+(VIEW .+)$/', 1954 | '/*!50001 \1 */'.PHP_EOL.$definerStr.'/*!50001 \3 */', 1955 | $viewStmt, 1956 | 1 1957 | )) { 1958 | $viewStmt = $viewStmtReplaced; 1959 | }; 1960 | 1961 | $ret .= $viewStmt.';'.PHP_EOL.PHP_EOL; 1962 | return $ret; 1963 | } 1964 | 1965 | public function create_trigger($row) 1966 | { 1967 | $ret = ""; 1968 | if (!isset($row['SQL Original Statement'])) { 1969 | throw new Exception("Error getting trigger code, unknown output"); 1970 | } 1971 | 1972 | $triggerStmt = $row['SQL Original Statement']; 1973 | $definerStr = $this->dumpSettings['skip-definer'] ? '' : '/*!50017 \2*/ '; 1974 | if ($triggerStmtReplaced = preg_replace( 1975 | '/^(CREATE)\s+('.self::DEFINER_RE.')?\s+(TRIGGER\s.*)$/s', 1976 | '/*!50003 \1*/ '.$definerStr.'/*!50003 \3 */', 1977 | $triggerStmt, 1978 | 1 1979 | )) { 1980 | $triggerStmt = $triggerStmtReplaced; 1981 | } 1982 | 1983 | $ret .= "DELIMITER ;;".PHP_EOL. 1984 | $triggerStmt.";;".PHP_EOL. 1985 | "DELIMITER ;".PHP_EOL.PHP_EOL; 1986 | return $ret; 1987 | } 1988 | 1989 | public function create_procedure($row) 1990 | { 1991 | $ret = ""; 1992 | if (!isset($row['Create Procedure'])) { 1993 | throw new Exception("Error getting procedure code, unknown output. ". 1994 | "Please check 'https://bugs.mysql.com/bug.php?id=14564'"); 1995 | } 1996 | $procedureStmt = $row['Create Procedure']; 1997 | if ($this->dumpSettings['skip-definer']) { 1998 | if ($procedureStmtReplaced = preg_replace( 1999 | '/^(CREATE)\s+('.self::DEFINER_RE.')?\s+(PROCEDURE\s.*)$/s', 2000 | '\1 \3', 2001 | $procedureStmt, 2002 | 1 2003 | )) { 2004 | $procedureStmt = $procedureStmtReplaced; 2005 | } 2006 | } 2007 | 2008 | $ret .= "/*!50003 DROP PROCEDURE IF EXISTS `". 2009 | $row['Procedure']."` */;".PHP_EOL. 2010 | "/*!40101 SET @saved_cs_client = @@character_set_client */;".PHP_EOL. 2011 | "/*!40101 SET character_set_client = ".$this->dumpSettings['default-character-set']." */;".PHP_EOL. 2012 | "DELIMITER ;;".PHP_EOL. 2013 | $procedureStmt." ;;".PHP_EOL. 2014 | "DELIMITER ;".PHP_EOL. 2015 | "/*!40101 SET character_set_client = @saved_cs_client */;".PHP_EOL.PHP_EOL; 2016 | 2017 | return $ret; 2018 | } 2019 | 2020 | public function create_function($row) 2021 | { 2022 | $ret = ""; 2023 | if (!isset($row['Create Function'])) { 2024 | throw new Exception("Error getting function code, unknown output. ". 2025 | "Please check 'https://bugs.mysql.com/bug.php?id=14564'"); 2026 | } 2027 | $functionStmt = $row['Create Function']; 2028 | $characterSetClient = $row['character_set_client']; 2029 | $collationConnection = $row['collation_connection']; 2030 | $sqlMode = $row['sql_mode']; 2031 | if ( $this->dumpSettings['skip-definer'] ) { 2032 | if ($functionStmtReplaced = preg_replace( 2033 | '/^(CREATE)\s+('.self::DEFINER_RE.')?\s+(FUNCTION\s.*)$/s', 2034 | '\1 \3', 2035 | $functionStmt, 2036 | 1 2037 | )) { 2038 | $functionStmt = $functionStmtReplaced; 2039 | } 2040 | } 2041 | 2042 | $ret .= "/*!50003 DROP FUNCTION IF EXISTS `". 2043 | $row['Function']."` */;".PHP_EOL. 2044 | "/*!40101 SET @saved_cs_client = @@character_set_client */;".PHP_EOL. 2045 | "/*!50003 SET @saved_cs_results = @@character_set_results */ ;".PHP_EOL. 2046 | "/*!50003 SET @saved_col_connection = @@collation_connection */ ;".PHP_EOL. 2047 | "/*!40101 SET character_set_client = ".$characterSetClient." */;".PHP_EOL. 2048 | "/*!40101 SET character_set_results = ".$characterSetClient." */;".PHP_EOL. 2049 | "/*!50003 SET collation_connection = ".$collationConnection." */ ;".PHP_EOL. 2050 | "/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;".PHP_EOL. 2051 | "/*!50003 SET sql_mode = '".$sqlMode."' */ ;;".PHP_EOL. 2052 | "/*!50003 SET @saved_time_zone = @@time_zone */ ;;".PHP_EOL. 2053 | "/*!50003 SET time_zone = 'SYSTEM' */ ;;".PHP_EOL. 2054 | "DELIMITER ;;".PHP_EOL. 2055 | $functionStmt." ;;".PHP_EOL. 2056 | "DELIMITER ;".PHP_EOL. 2057 | "/*!50003 SET sql_mode = @saved_sql_mode */ ;".PHP_EOL. 2058 | "/*!50003 SET character_set_client = @saved_cs_client */ ;".PHP_EOL. 2059 | "/*!50003 SET character_set_results = @saved_cs_results */ ;".PHP_EOL. 2060 | "/*!50003 SET collation_connection = @saved_col_connection */ ;".PHP_EOL. 2061 | "/*!50106 SET TIME_ZONE= @saved_time_zone */ ;".PHP_EOL.PHP_EOL; 2062 | 2063 | 2064 | return $ret; 2065 | } 2066 | 2067 | public function create_event($row) 2068 | { 2069 | $ret = ""; 2070 | if (!isset($row['Create Event'])) { 2071 | throw new Exception("Error getting event code, unknown output. ". 2072 | "Please check 'http://stackoverflow.com/questions/10853826/mysql-5-5-create-event-gives-syntax-error'"); 2073 | } 2074 | $eventName = $row['Event']; 2075 | $eventStmt = $row['Create Event']; 2076 | $sqlMode = $row['sql_mode']; 2077 | $definerStr = $this->dumpSettings['skip-definer'] ? '' : '/*!50117 \2*/ '; 2078 | 2079 | if ($eventStmtReplaced = preg_replace( 2080 | '/^(CREATE)\s+('.self::DEFINER_RE.')?\s+(EVENT .*)$/', 2081 | '/*!50106 \1*/ '.$definerStr.'/*!50106 \3 */', 2082 | $eventStmt, 2083 | 1 2084 | )) { 2085 | $eventStmt = $eventStmtReplaced; 2086 | } 2087 | 2088 | $ret .= "/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;".PHP_EOL. 2089 | "/*!50106 DROP EVENT IF EXISTS `".$eventName."` */;".PHP_EOL. 2090 | "DELIMITER ;;".PHP_EOL. 2091 | "/*!50003 SET @saved_cs_client = @@character_set_client */ ;;".PHP_EOL. 2092 | "/*!50003 SET @saved_cs_results = @@character_set_results */ ;;".PHP_EOL. 2093 | "/*!50003 SET @saved_col_connection = @@collation_connection */ ;;".PHP_EOL. 2094 | "/*!50003 SET character_set_client = utf8 */ ;;".PHP_EOL. 2095 | "/*!50003 SET character_set_results = utf8 */ ;;".PHP_EOL. 2096 | "/*!50003 SET collation_connection = utf8_general_ci */ ;;".PHP_EOL. 2097 | "/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;".PHP_EOL. 2098 | "/*!50003 SET sql_mode = '".$sqlMode."' */ ;;".PHP_EOL. 2099 | "/*!50003 SET @saved_time_zone = @@time_zone */ ;;".PHP_EOL. 2100 | "/*!50003 SET time_zone = 'SYSTEM' */ ;;".PHP_EOL. 2101 | $eventStmt." ;;".PHP_EOL. 2102 | "/*!50003 SET time_zone = @saved_time_zone */ ;;".PHP_EOL. 2103 | "/*!50003 SET sql_mode = @saved_sql_mode */ ;;".PHP_EOL. 2104 | "/*!50003 SET character_set_client = @saved_cs_client */ ;;".PHP_EOL. 2105 | "/*!50003 SET character_set_results = @saved_cs_results */ ;;".PHP_EOL. 2106 | "/*!50003 SET collation_connection = @saved_col_connection */ ;;".PHP_EOL. 2107 | "DELIMITER ;".PHP_EOL. 2108 | "/*!50106 SET TIME_ZONE= @save_time_zone */ ;".PHP_EOL.PHP_EOL; 2109 | // Commented because we are doing this in restore_parameters() 2110 | // "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;" . PHP_EOL . PHP_EOL; 2111 | 2112 | return $ret; 2113 | } 2114 | 2115 | public function show_tables() 2116 | { 2117 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2118 | $args = func_get_args(); 2119 | return "SELECT TABLE_NAME AS tbl_name ". 2120 | "FROM INFORMATION_SCHEMA.TABLES ". 2121 | "WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='{$args[0]}' ". 2122 | "ORDER BY TABLE_NAME"; 2123 | } 2124 | 2125 | public function show_views() 2126 | { 2127 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2128 | $args = func_get_args(); 2129 | return "SELECT TABLE_NAME AS tbl_name ". 2130 | "FROM INFORMATION_SCHEMA.TABLES ". 2131 | "WHERE TABLE_TYPE='VIEW' AND TABLE_SCHEMA='{$args[0]}' ". 2132 | "ORDER BY TABLE_NAME"; 2133 | } 2134 | 2135 | public function show_triggers() 2136 | { 2137 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2138 | $args = func_get_args(); 2139 | return "SHOW TRIGGERS FROM `{$args[0]}`;"; 2140 | } 2141 | 2142 | public function show_columns() 2143 | { 2144 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2145 | $args = func_get_args(); 2146 | return "SHOW COLUMNS FROM `{$args[0]}`;"; 2147 | } 2148 | 2149 | public function show_procedures() 2150 | { 2151 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2152 | $args = func_get_args(); 2153 | return "SELECT SPECIFIC_NAME AS procedure_name ". 2154 | "FROM INFORMATION_SCHEMA.ROUTINES ". 2155 | "WHERE ROUTINE_TYPE='PROCEDURE' AND ROUTINE_SCHEMA='{$args[0]}'"; 2156 | } 2157 | 2158 | public function show_functions() 2159 | { 2160 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2161 | $args = func_get_args(); 2162 | return "SELECT SPECIFIC_NAME AS function_name ". 2163 | "FROM INFORMATION_SCHEMA.ROUTINES ". 2164 | "WHERE ROUTINE_TYPE='FUNCTION' AND ROUTINE_SCHEMA='{$args[0]}'"; 2165 | } 2166 | 2167 | /** 2168 | * Get query string to ask for names of events from current database. 2169 | * 2170 | * @param string Name of database 2171 | * @return string 2172 | */ 2173 | public function show_events() 2174 | { 2175 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2176 | $args = func_get_args(); 2177 | return "SELECT EVENT_NAME AS event_name ". 2178 | "FROM INFORMATION_SCHEMA.EVENTS ". 2179 | "WHERE EVENT_SCHEMA='{$args[0]}'"; 2180 | } 2181 | 2182 | public function setup_transaction() 2183 | { 2184 | return "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ"; 2185 | } 2186 | 2187 | public function start_transaction() 2188 | { 2189 | return "START TRANSACTION ". 2190 | "/*!40100 WITH CONSISTENT SNAPSHOT */"; 2191 | } 2192 | 2193 | 2194 | public function commit_transaction() 2195 | { 2196 | return "COMMIT"; 2197 | } 2198 | 2199 | public function lock_table() 2200 | { 2201 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2202 | $args = func_get_args(); 2203 | return $this->dbHandler->exec("LOCK TABLES `{$args[0]}` READ LOCAL"); 2204 | } 2205 | 2206 | public function unlock_table() 2207 | { 2208 | return $this->dbHandler->exec("UNLOCK TABLES"); 2209 | } 2210 | 2211 | public function start_add_lock_table() 2212 | { 2213 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2214 | $args = func_get_args(); 2215 | return "LOCK TABLES `{$args[0]}` WRITE;".PHP_EOL; 2216 | } 2217 | 2218 | public function end_add_lock_table() 2219 | { 2220 | return "UNLOCK TABLES;".PHP_EOL; 2221 | } 2222 | 2223 | public function start_add_disable_keys() 2224 | { 2225 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2226 | $args = func_get_args(); 2227 | return "/*!40000 ALTER TABLE `{$args[0]}` DISABLE KEYS */;". 2228 | PHP_EOL; 2229 | } 2230 | 2231 | public function end_add_disable_keys() 2232 | { 2233 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2234 | $args = func_get_args(); 2235 | return "/*!40000 ALTER TABLE `{$args[0]}` ENABLE KEYS */;". 2236 | PHP_EOL; 2237 | } 2238 | 2239 | public function start_disable_autocommit() 2240 | { 2241 | return "SET autocommit=0;".PHP_EOL; 2242 | } 2243 | 2244 | public function end_disable_autocommit() 2245 | { 2246 | return "COMMIT;".PHP_EOL; 2247 | } 2248 | 2249 | public function add_drop_database() 2250 | { 2251 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2252 | $args = func_get_args(); 2253 | return "/*!40000 DROP DATABASE IF EXISTS `{$args[0]}`*/;". 2254 | PHP_EOL.PHP_EOL; 2255 | } 2256 | 2257 | public function add_drop_trigger() 2258 | { 2259 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2260 | $args = func_get_args(); 2261 | return "DROP TRIGGER IF EXISTS `{$args[0]}`;".PHP_EOL; 2262 | } 2263 | 2264 | public function drop_table() 2265 | { 2266 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2267 | $args = func_get_args(); 2268 | return "DROP TABLE IF EXISTS `{$args[0]}`;".PHP_EOL; 2269 | } 2270 | 2271 | public function drop_view() 2272 | { 2273 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2274 | $args = func_get_args(); 2275 | return "DROP TABLE IF EXISTS `{$args[0]}`;".PHP_EOL. 2276 | "/*!50001 DROP VIEW IF EXISTS `{$args[0]}`*/;".PHP_EOL; 2277 | } 2278 | 2279 | public function getDatabaseHeader() 2280 | { 2281 | $this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__); 2282 | $args = func_get_args(); 2283 | return "--".PHP_EOL. 2284 | "-- Current Database: `{$args[0]}`".PHP_EOL. 2285 | "--".PHP_EOL.PHP_EOL; 2286 | } 2287 | 2288 | /** 2289 | * Decode column metadata and fill info structure. 2290 | * type, is_numeric and is_blob will always be available. 2291 | * 2292 | * @param array $colType Array returned from "SHOW COLUMNS FROM tableName" 2293 | * @return array 2294 | */ 2295 | public function parseColumnType($colType) 2296 | { 2297 | $colInfo = array(); 2298 | $colParts = explode(" ", $colType['Type']); 2299 | 2300 | if ($fparen = strpos($colParts[0], "(")) { 2301 | $colInfo['type'] = substr($colParts[0], 0, $fparen); 2302 | $colInfo['length'] = str_replace(")", "", substr($colParts[0], $fparen + 1)); 2303 | $colInfo['attributes'] = isset($colParts[1]) ? $colParts[1] : null; 2304 | } else { 2305 | $colInfo['type'] = $colParts[0]; 2306 | } 2307 | $colInfo['is_numeric'] = in_array($colInfo['type'], $this->mysqlTypes['numerical']); 2308 | $colInfo['is_blob'] = in_array($colInfo['type'], $this->mysqlTypes['blob']); 2309 | // for virtual columns that are of type 'Extra', column type 2310 | // could by "STORED GENERATED" or "VIRTUAL GENERATED" 2311 | // MySQL reference: https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html 2312 | $colInfo['is_virtual'] = strpos($colType['Extra'], "VIRTUAL GENERATED") !== false || strpos($colType['Extra'], "STORED GENERATED") !== false; 2313 | 2314 | return $colInfo; 2315 | } 2316 | 2317 | public function backup_parameters() 2318 | { 2319 | $ret = "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;".PHP_EOL. 2320 | "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;".PHP_EOL. 2321 | "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;".PHP_EOL. 2322 | "/*!40101 SET NAMES ".$this->dumpSettings['default-character-set']." */;".PHP_EOL; 2323 | 2324 | if (false === $this->dumpSettings['skip-tz-utc']) { 2325 | $ret .= "/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;".PHP_EOL. 2326 | "/*!40103 SET TIME_ZONE='+00:00' */;".PHP_EOL; 2327 | } 2328 | 2329 | if ($this->dumpSettings['no-autocommit']) { 2330 | $ret .= "/*!40101 SET @OLD_AUTOCOMMIT=@@AUTOCOMMIT */;".PHP_EOL; 2331 | } 2332 | 2333 | $ret .= "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;".PHP_EOL. 2334 | "/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;".PHP_EOL. 2335 | "/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;".PHP_EOL. 2336 | "/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;".PHP_EOL.PHP_EOL; 2337 | 2338 | return $ret; 2339 | } 2340 | 2341 | public function restore_parameters() 2342 | { 2343 | $ret = ""; 2344 | 2345 | if (false === $this->dumpSettings['skip-tz-utc']) { 2346 | $ret .= "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;".PHP_EOL; 2347 | } 2348 | 2349 | if ($this->dumpSettings['no-autocommit']) { 2350 | $ret .= "/*!40101 SET AUTOCOMMIT=@OLD_AUTOCOMMIT */;".PHP_EOL; 2351 | } 2352 | 2353 | $ret .= "/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;".PHP_EOL. 2354 | "/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;".PHP_EOL. 2355 | "/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;".PHP_EOL. 2356 | "/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;".PHP_EOL. 2357 | "/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;".PHP_EOL. 2358 | "/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;".PHP_EOL. 2359 | "/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;".PHP_EOL.PHP_EOL; 2360 | 2361 | return $ret; 2362 | } 2363 | 2364 | /** 2365 | * Check number of parameters passed to function, useful when inheriting. 2366 | * Raise exception if unexpected. 2367 | * 2368 | * @param integer $num_args 2369 | * @param integer $expected_num_args 2370 | * @param string $method_name 2371 | */ 2372 | private function check_parameters($num_args, $expected_num_args, $method_name) 2373 | { 2374 | if ($num_args != $expected_num_args) { 2375 | throw new Exception("Unexpected parameter passed to $method_name"); 2376 | } 2377 | return; 2378 | } 2379 | } 2380 | --------------------------------------------------------------------------------