Mysql.php 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\DB\Adapter\Pdo;
  7. use Magento\Framework\App\ObjectManager;
  8. use Magento\Framework\Cache\FrontendInterface;
  9. use Magento\Framework\DB\Adapter\AdapterInterface;
  10. use Magento\Framework\DB\Adapter\ConnectionException;
  11. use Magento\Framework\DB\Adapter\DeadlockException;
  12. use Magento\Framework\DB\Adapter\DuplicateException;
  13. use Magento\Framework\DB\Adapter\LockWaitException;
  14. use Magento\Framework\DB\Ddl\Table;
  15. use Magento\Framework\DB\ExpressionConverter;
  16. use Magento\Framework\DB\LoggerInterface;
  17. use Magento\Framework\DB\Profiler;
  18. use Magento\Framework\DB\Query\Generator as QueryGenerator;
  19. use Magento\Framework\DB\Select;
  20. use Magento\Framework\DB\SelectFactory;
  21. use Magento\Framework\DB\Statement\Parameter;
  22. use Magento\Framework\Exception\LocalizedException;
  23. use Magento\Framework\Phrase;
  24. use Magento\Framework\Serialize\SerializerInterface;
  25. use Magento\Framework\Stdlib\DateTime;
  26. use Magento\Framework\Stdlib\StringUtils;
  27. use Magento\Framework\Setup\SchemaListener;
  28. // @codingStandardsIgnoreStart
  29. /**
  30. * MySQL database adapter
  31. *
  32. * @api
  33. * @SuppressWarnings(PHPMD.ExcessivePublicCount)
  34. * @SuppressWarnings(PHPMD.TooManyFields)
  35. * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
  36. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  37. * @since 100.0.2
  38. */
  39. class Mysql extends \Zend_Db_Adapter_Pdo_Mysql implements AdapterInterface
  40. {
  41. // @codingStandardsIgnoreEnd
  42. const TIMESTAMP_FORMAT = 'Y-m-d H:i:s';
  43. const DATETIME_FORMAT = 'Y-m-d H:i:s';
  44. const DATE_FORMAT = 'Y-m-d';
  45. const DDL_DESCRIBE = 1;
  46. const DDL_CREATE = 2;
  47. const DDL_INDEX = 3;
  48. const DDL_FOREIGN_KEY = 4;
  49. const DDL_CACHE_PREFIX = 'DB_PDO_MYSQL_DDL';
  50. const DDL_CACHE_TAG = 'DB_PDO_MYSQL_DDL';
  51. const LENGTH_TABLE_NAME = 64;
  52. const LENGTH_INDEX_NAME = 64;
  53. const LENGTH_FOREIGN_NAME = 64;
  54. /**
  55. * MEMORY engine type for MySQL tables
  56. */
  57. const ENGINE_MEMORY = 'MEMORY';
  58. /**
  59. * Maximum number of connection retries
  60. */
  61. const MAX_CONNECTION_RETRIES = 10;
  62. /**
  63. * Default class name for a DB statement.
  64. *
  65. * @var string
  66. */
  67. protected $_defaultStmtClass = \Magento\Framework\DB\Statement\Pdo\Mysql::class;
  68. /**
  69. * Current Transaction Level
  70. *
  71. * @var int
  72. */
  73. protected $_transactionLevel = 0;
  74. /**
  75. * Whether transaction was rolled back or not
  76. *
  77. * @var bool
  78. */
  79. protected $_isRolledBack = false;
  80. /**
  81. * Set attribute to connection flag
  82. *
  83. * @var bool
  84. */
  85. protected $_connectionFlagsSet = false;
  86. /**
  87. * Tables DDL cache
  88. *
  89. * @var array
  90. */
  91. protected $_ddlCache = [];
  92. /**
  93. * SQL bind params. Used temporarily by regexp callback.
  94. *
  95. * @var array
  96. */
  97. protected $_bindParams = [];
  98. /**
  99. * Autoincrement for bind value. Used by regexp callback.
  100. *
  101. * @var int
  102. */
  103. protected $_bindIncrement = 0;
  104. /**
  105. * Cache frontend adapter instance
  106. *
  107. * @var FrontendInterface
  108. */
  109. protected $_cacheAdapter;
  110. /**
  111. * DDL cache allowing flag
  112. * @var bool
  113. */
  114. protected $_isDdlCacheAllowed = true;
  115. /**
  116. * MySQL column - Table DDL type pairs
  117. *
  118. * @var array
  119. */
  120. protected $_ddlColumnTypes = [
  121. Table::TYPE_BOOLEAN => 'bool',
  122. Table::TYPE_SMALLINT => 'smallint',
  123. Table::TYPE_INTEGER => 'int',
  124. Table::TYPE_BIGINT => 'bigint',
  125. Table::TYPE_FLOAT => 'float',
  126. Table::TYPE_DECIMAL => 'decimal',
  127. Table::TYPE_NUMERIC => 'decimal',
  128. Table::TYPE_DATE => 'date',
  129. Table::TYPE_TIMESTAMP => 'timestamp',
  130. Table::TYPE_DATETIME => 'datetime',
  131. Table::TYPE_TEXT => 'text',
  132. Table::TYPE_BLOB => 'blob',
  133. Table::TYPE_VARBINARY => 'blob',
  134. ];
  135. /**
  136. * All possible DDL statements
  137. * First 3 symbols for each statement
  138. *
  139. * @var string[]
  140. */
  141. protected $_ddlRoutines = ['alt', 'cre', 'ren', 'dro', 'tru'];
  142. /**
  143. * Allowed interval units array
  144. *
  145. * @var array
  146. */
  147. protected $_intervalUnits = [
  148. self::INTERVAL_YEAR => 'YEAR',
  149. self::INTERVAL_MONTH => 'MONTH',
  150. self::INTERVAL_DAY => 'DAY',
  151. self::INTERVAL_HOUR => 'HOUR',
  152. self::INTERVAL_MINUTE => 'MINUTE',
  153. self::INTERVAL_SECOND => 'SECOND',
  154. ];
  155. /**
  156. * Hook callback to modify queries. Mysql specific property, designed only for backwards compatibility.
  157. *
  158. * @var array|null
  159. */
  160. protected $_queryHook = null;
  161. /**
  162. * @var String
  163. */
  164. protected $string;
  165. /**
  166. * @var DateTime
  167. */
  168. protected $dateTime;
  169. /**
  170. * @var SelectFactory
  171. * @since 100.1.0
  172. */
  173. protected $selectFactory;
  174. /**
  175. * @var LoggerInterface
  176. */
  177. protected $logger;
  178. /**
  179. * Map that links database error code to corresponding Magento exception
  180. *
  181. * @var \Zend_Db_Adapter_Exception[]
  182. */
  183. private $exceptionMap;
  184. /**
  185. * @var QueryGenerator
  186. */
  187. private $queryGenerator;
  188. /**
  189. * @var SerializerInterface
  190. */
  191. private $serializer;
  192. /**
  193. * @var SchemaListener
  194. */
  195. private $schemaListener;
  196. /**
  197. * Constructor
  198. *
  199. * @param StringUtils $string
  200. * @param DateTime $dateTime
  201. * @param LoggerInterface $logger
  202. * @param SelectFactory $selectFactory
  203. * @param array $config
  204. * @param SerializerInterface|null $serializer
  205. */
  206. public function __construct(
  207. StringUtils $string,
  208. DateTime $dateTime,
  209. LoggerInterface $logger,
  210. SelectFactory $selectFactory,
  211. array $config = [],
  212. SerializerInterface $serializer = null
  213. ) {
  214. $this->string = $string;
  215. $this->dateTime = $dateTime;
  216. $this->logger = $logger;
  217. $this->selectFactory = $selectFactory;
  218. $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class);
  219. $this->exceptionMap = [
  220. // SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
  221. 2006 => ConnectionException::class,
  222. // SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query
  223. 2013 => ConnectionException::class,
  224. // SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded
  225. 1205 => LockWaitException::class,
  226. // SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock
  227. 1213 => DeadlockException::class,
  228. // SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  229. 1062 => DuplicateException::class,
  230. ];
  231. try {
  232. parent::__construct($config);
  233. } catch (\Zend_Db_Adapter_Exception $e) {
  234. throw new \InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
  235. }
  236. }
  237. /**
  238. * Begin new DB transaction for connection
  239. *
  240. * @return $this
  241. * @throws \Exception
  242. */
  243. public function beginTransaction()
  244. {
  245. if ($this->_isRolledBack) {
  246. throw new \Exception(AdapterInterface::ERROR_ROLLBACK_INCOMPLETE_MESSAGE);
  247. }
  248. if ($this->_transactionLevel === 0) {
  249. $this->logger->startTimer();
  250. parent::beginTransaction();
  251. $this->logger->logStats(LoggerInterface::TYPE_TRANSACTION, 'BEGIN');
  252. }
  253. ++$this->_transactionLevel;
  254. return $this;
  255. }
  256. /**
  257. * Commit DB transaction
  258. *
  259. * @return $this
  260. * @throws \Exception
  261. */
  262. public function commit()
  263. {
  264. if ($this->_transactionLevel === 1 && !$this->_isRolledBack) {
  265. $this->logger->startTimer();
  266. parent::commit();
  267. $this->logger->logStats(LoggerInterface::TYPE_TRANSACTION, 'COMMIT');
  268. } elseif ($this->_transactionLevel === 0) {
  269. throw new \Exception(AdapterInterface::ERROR_ASYMMETRIC_COMMIT_MESSAGE);
  270. } elseif ($this->_isRolledBack) {
  271. throw new \Exception(AdapterInterface::ERROR_ROLLBACK_INCOMPLETE_MESSAGE);
  272. }
  273. --$this->_transactionLevel;
  274. return $this;
  275. }
  276. /**
  277. * Rollback DB transaction
  278. *
  279. * @return $this
  280. * @throws \Exception
  281. */
  282. public function rollBack()
  283. {
  284. if ($this->_transactionLevel === 1) {
  285. $this->logger->startTimer();
  286. parent::rollBack();
  287. $this->_isRolledBack = false;
  288. $this->logger->logStats(LoggerInterface::TYPE_TRANSACTION, 'ROLLBACK');
  289. } elseif ($this->_transactionLevel === 0) {
  290. throw new \Exception(AdapterInterface::ERROR_ASYMMETRIC_ROLLBACK_MESSAGE);
  291. } else {
  292. $this->_isRolledBack = true;
  293. }
  294. --$this->_transactionLevel;
  295. return $this;
  296. }
  297. /**
  298. * Get adapter transaction level state. Return 0 if all transactions are complete
  299. *
  300. * @return int
  301. */
  302. public function getTransactionLevel()
  303. {
  304. return $this->_transactionLevel;
  305. }
  306. /**
  307. * Convert date to DB format
  308. *
  309. * @param int|string|\DateTimeInterface $date
  310. * @return \Zend_Db_Expr
  311. */
  312. public function convertDate($date)
  313. {
  314. return $this->formatDate($date, false);
  315. }
  316. /**
  317. * Convert date and time to DB format
  318. *
  319. * @param int|string|\DateTimeInterface $datetime
  320. * @return \Zend_Db_Expr
  321. */
  322. public function convertDateTime($datetime)
  323. {
  324. return $this->formatDate($datetime, true);
  325. }
  326. /**
  327. * Creates a PDO object and connects to the database.
  328. *
  329. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  330. * @SuppressWarnings(PHPMD.NPathComplexity)
  331. *
  332. * @return void
  333. * @throws \Zend_Db_Adapter_Exception
  334. * @throws \Zend_Db_Statement_Exception
  335. */
  336. protected function _connect()
  337. {
  338. if ($this->_connection) {
  339. return;
  340. }
  341. if (!extension_loaded('pdo_mysql')) {
  342. throw new \Zend_Db_Adapter_Exception('pdo_mysql extension is not installed');
  343. }
  344. if (!isset($this->_config['host'])) {
  345. throw new \Zend_Db_Adapter_Exception('No host configured to connect');
  346. }
  347. if (isset($this->_config['port'])) {
  348. throw new \Zend_Db_Adapter_Exception('Port must be configured within host parameter (like localhost:3306');
  349. }
  350. unset($this->_config['port']);
  351. if (strpos($this->_config['host'], '/') !== false) {
  352. $this->_config['unix_socket'] = $this->_config['host'];
  353. unset($this->_config['host']);
  354. } elseif (strpos($this->_config['host'], ':') !== false) {
  355. list($this->_config['host'], $this->_config['port']) = explode(':', $this->_config['host']);
  356. }
  357. if (!isset($this->_config['driver_options'][\PDO::MYSQL_ATTR_MULTI_STATEMENTS])) {
  358. $this->_config['driver_options'][\PDO::MYSQL_ATTR_MULTI_STATEMENTS] = false;
  359. }
  360. $this->logger->startTimer();
  361. parent::_connect();
  362. $this->logger->logStats(LoggerInterface::TYPE_CONNECT, '');
  363. /** @link http://bugs.mysql.com/bug.php?id=18551 */
  364. $this->_connection->query("SET SQL_MODE=''");
  365. // As we use default value CURRENT_TIMESTAMP for TIMESTAMP type columns we need to set GMT timezone
  366. $this->_connection->query("SET time_zone = '+00:00'");
  367. if (isset($this->_config['initStatements'])) {
  368. $statements = $this->_splitMultiQuery($this->_config['initStatements']);
  369. foreach ($statements as $statement) {
  370. $this->_query($statement);
  371. }
  372. }
  373. if (!$this->_connectionFlagsSet) {
  374. $this->_connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
  375. if (isset($this->_config['use_buffered_query']) && $this->_config['use_buffered_query'] === false) {
  376. $this->_connection->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
  377. } else {
  378. $this->_connection->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
  379. }
  380. $this->_connectionFlagsSet = true;
  381. }
  382. }
  383. /**
  384. * Create new database connection
  385. *
  386. * @return \PDO
  387. */
  388. private function createConnection()
  389. {
  390. $connection = new \PDO(
  391. $this->_dsn(),
  392. $this->_config['username'],
  393. $this->_config['password'],
  394. $this->_config['driver_options']
  395. );
  396. return $connection;
  397. }
  398. /**
  399. * Run RAW Query
  400. *
  401. * @param string $sql
  402. * @return \Zend_Db_Statement_Interface
  403. * @throws \PDOException
  404. */
  405. public function rawQuery($sql)
  406. {
  407. try {
  408. $result = $this->query($sql);
  409. } catch (\Zend_Db_Statement_Exception $e) {
  410. // Convert to \PDOException to maintain backwards compatibility with usage of MySQL adapter
  411. $e = $e->getPrevious();
  412. if (!($e instanceof \PDOException)) {
  413. $e = new \PDOException($e->getMessage(), $e->getCode());
  414. }
  415. throw $e;
  416. }
  417. return $result;
  418. }
  419. /**
  420. * Run RAW query and Fetch First row
  421. *
  422. * @param string $sql
  423. * @param string|int $field
  424. * @return mixed|null
  425. */
  426. public function rawFetchRow($sql, $field = null)
  427. {
  428. $result = $this->rawQuery($sql);
  429. if (!$result) {
  430. return false;
  431. }
  432. $row = $result->fetch(\PDO::FETCH_ASSOC);
  433. if (!$row) {
  434. return false;
  435. }
  436. if (empty($field)) {
  437. return $row;
  438. } else {
  439. return $row[$field] ?? false;
  440. }
  441. }
  442. /**
  443. * Check transaction level in case of DDL query
  444. *
  445. * @param string|\Magento\Framework\DB\Select $sql
  446. * @return void
  447. * @throws \Zend_Db_Adapter_Exception
  448. */
  449. protected function _checkDdlTransaction($sql)
  450. {
  451. if ($this->getTransactionLevel() > 0) {
  452. $sql = ltrim(preg_replace('/\s+/', ' ', $sql));
  453. $sqlMessage = explode(' ', $sql, 3);
  454. $startSql = strtolower(substr($sqlMessage[0], 0, 3));
  455. if (in_array($startSql, $this->_ddlRoutines) && strcasecmp($sqlMessage[1], 'temporary') !== 0) {
  456. throw new ConnectionException(AdapterInterface::ERROR_DDL_MESSAGE, E_USER_ERROR);
  457. }
  458. }
  459. }
  460. /**
  461. * Special handling for PDO query().
  462. *
  463. * All bind parameter names must begin with ':'.
  464. *
  465. * @param string|\Magento\Framework\DB\Select $sql The SQL statement with placeholders.
  466. * @param mixed $bind An array of data or data itself to bind to the placeholders.
  467. * @return \Zend_Db_Statement_Pdo|void
  468. * @throws \Zend_Db_Adapter_Exception To re-throw \PDOException.
  469. * @throws \Zend_Db_Statement_Exception
  470. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  471. */
  472. protected function _query($sql, $bind = [])
  473. {
  474. $connectionErrors = [
  475. 2006, // SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
  476. 2013, // SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query
  477. ];
  478. $triesCount = 0;
  479. do {
  480. $retry = false;
  481. $this->logger->startTimer();
  482. try {
  483. $this->_checkDdlTransaction($sql);
  484. $this->_prepareQuery($sql, $bind);
  485. $result = parent::query($sql, $bind);
  486. $this->logger->logStats(LoggerInterface::TYPE_QUERY, $sql, $bind, $result);
  487. return $result;
  488. } catch (\Exception $e) {
  489. // Finalize broken query
  490. $profiler = $this->getProfiler();
  491. if ($profiler instanceof Profiler) {
  492. /** @var Profiler $profiler */
  493. $profiler->queryEndLast();
  494. }
  495. /** @var $pdoException \PDOException */
  496. $pdoException = null;
  497. if ($e instanceof \PDOException) {
  498. $pdoException = $e;
  499. } elseif (($e instanceof \Zend_Db_Statement_Exception)
  500. && ($e->getPrevious() instanceof \PDOException)
  501. ) {
  502. $pdoException = $e->getPrevious();
  503. }
  504. // Check to reconnect
  505. if ($pdoException && $triesCount < self::MAX_CONNECTION_RETRIES
  506. && in_array($pdoException->errorInfo[1], $connectionErrors)
  507. ) {
  508. $retry = true;
  509. $triesCount++;
  510. $this->closeConnection();
  511. /**
  512. * _connect() function does not allow port parameter, so put the port back with the host
  513. */
  514. if (!empty($this->_config['port'])) {
  515. $this->_config['host'] = implode(':', [$this->_config['host'], $this->_config['port']]);
  516. unset($this->_config['port']);
  517. }
  518. $this->_connect();
  519. }
  520. if (!$retry) {
  521. $this->logger->logStats(LoggerInterface::TYPE_QUERY, $sql, $bind);
  522. $this->logger->critical($e);
  523. // rethrow custom exception if needed
  524. if ($pdoException && isset($this->exceptionMap[$pdoException->errorInfo[1]])) {
  525. $customExceptionClass = $this->exceptionMap[$pdoException->errorInfo[1]];
  526. /** @var \Zend_Db_Adapter_Exception $customException */
  527. $customException = new $customExceptionClass($e->getMessage(), $pdoException->errorInfo[1], $e);
  528. throw $customException;
  529. }
  530. throw $e;
  531. }
  532. }
  533. } while ($retry);
  534. }
  535. /**
  536. * Special handling for PDO query().
  537. *
  538. * All bind parameter names must begin with ':'.
  539. *
  540. * @param string|\Magento\Framework\DB\Select $sql The SQL statement with placeholders.
  541. * @param mixed $bind An array of data or data itself to bind to the placeholders.
  542. * @return \Zend_Db_Statement_Pdo|void
  543. * @throws \Zend_Db_Adapter_Exception To re-throw \PDOException.
  544. * @throws LocalizedException In case multiple queries are attempted at once, to protect from SQL injection
  545. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  546. */
  547. public function query($sql, $bind = [])
  548. {
  549. if (strpos(rtrim($sql, " \t\n\r\0;"), ';') !== false && count($this->_splitMultiQuery($sql)) > 1) {
  550. throw new \Magento\Framework\Exception\LocalizedException(
  551. new Phrase("Multiple queries can't be executed. Run a single query and try again.")
  552. );
  553. }
  554. return $this->_query($sql, $bind);
  555. }
  556. /**
  557. * Allows multiple queries
  558. *
  559. * Allows multiple queries -- to safeguard against SQL injection, USE CAUTION and verify that input
  560. * cannot be tampered with.
  561. * Special handling for PDO query().
  562. * All bind parameter names must begin with ':'.
  563. *
  564. * @param string|\Magento\Framework\DB\Select $sql The SQL statement with placeholders.
  565. * @param mixed $bind An array of data or data itself to bind to the placeholders.
  566. * @return \Zend_Db_Statement_Pdo|void
  567. * @throws \Zend_Db_Adapter_Exception To re-throw \PDOException.
  568. * @throws LocalizedException In case multiple queries are attempted at once, to protect from SQL injection
  569. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  570. * @deprecated 101.0.0
  571. */
  572. public function multiQuery($sql, $bind = [])
  573. {
  574. return $this->_query($sql, $bind);
  575. }
  576. /**
  577. * Prepares SQL query by moving to bind all special parameters that can be confused with bind placeholders
  578. * (e.g. "foo:bar"). And also changes named bind to positional one, because underlying library has problems
  579. * with named binds.
  580. *
  581. * @param \Magento\Framework\DB\Select|string $sql
  582. * @param mixed $bind
  583. * @return $this
  584. */
  585. protected function _prepareQuery(&$sql, &$bind = [])
  586. {
  587. $sql = (string) $sql;
  588. if (!is_array($bind)) {
  589. $bind = [$bind];
  590. }
  591. // Mixed bind is not supported - so remember whether it is named bind, to normalize later if required
  592. $isNamedBind = false;
  593. if ($bind) {
  594. foreach ($bind as $k => $v) {
  595. if (!is_int($k)) {
  596. $isNamedBind = true;
  597. if ($k[0] != ':') {
  598. $bind[":{$k}"] = $v;
  599. unset($bind[$k]);
  600. }
  601. }
  602. }
  603. }
  604. // Special query hook
  605. if ($this->_queryHook) {
  606. $object = $this->_queryHook['object'];
  607. $method = $this->_queryHook['method'];
  608. $object->$method($sql, $bind);
  609. }
  610. return $this;
  611. }
  612. /**
  613. * Callback function for preparation of query and bind by regexp.
  614. * Checks query parameters for special symbols and moves such parameters to bind array as named ones.
  615. * This method writes to $_bindParams, where query bind parameters are kept.
  616. * This method requires further normalizing, if bind array is positional.
  617. *
  618. * @param string[] $matches
  619. * @return string
  620. */
  621. public function proccessBindCallback($matches)
  622. {
  623. if (isset($matches[6]) && (
  624. strpos($matches[6], "'") !== false ||
  625. strpos($matches[6], ':') !== false ||
  626. strpos($matches[6], '?') !== false)
  627. ) {
  628. $bindName = ':_mage_bind_var_' . (++$this->_bindIncrement);
  629. $this->_bindParams[$bindName] = $this->_unQuote($matches[6]);
  630. return ' ' . $bindName;
  631. }
  632. return $matches[0];
  633. }
  634. /**
  635. * Unquote raw string (use for auto-bind)
  636. *
  637. * @param string $string
  638. * @return string
  639. */
  640. protected function _unQuote($string)
  641. {
  642. $translate = [
  643. "\\000" => "\000",
  644. "\\n" => "\n",
  645. "\\r" => "\r",
  646. "\\\\" => "\\",
  647. "\'" => "'",
  648. "\\\"" => "\"",
  649. "\\032" => "\032",
  650. ];
  651. return strtr($string, $translate);
  652. }
  653. /**
  654. * Normalizes mixed positional-named bind to positional bind, and replaces named placeholders in query to
  655. * '?' placeholders.
  656. *
  657. * @param string $sql
  658. * @param array $bind
  659. * @return $this
  660. */
  661. protected function _convertMixedBind(&$sql, &$bind)
  662. {
  663. $positions = [];
  664. $offset = 0;
  665. // get positions
  666. while (true) {
  667. $pos = strpos($sql, '?', $offset);
  668. if ($pos !== false) {
  669. $positions[] = $pos;
  670. $offset = ++$pos;
  671. } else {
  672. break;
  673. }
  674. }
  675. $bindResult = [];
  676. $map = [];
  677. foreach ($bind as $k => $v) {
  678. // positional
  679. if (is_int($k)) {
  680. if (!isset($positions[$k])) {
  681. continue;
  682. }
  683. $bindResult[$positions[$k]] = $v;
  684. } else {
  685. $offset = 0;
  686. while (true) {
  687. $pos = strpos($sql, $k, $offset);
  688. if ($pos === false) {
  689. break;
  690. } else {
  691. $offset = $pos + strlen($k);
  692. $bindResult[$pos] = $v;
  693. }
  694. }
  695. $map[$k] = '?';
  696. }
  697. }
  698. ksort($bindResult);
  699. $bind = array_values($bindResult);
  700. $sql = strtr($sql, $map);
  701. return $this;
  702. }
  703. /**
  704. * Sets (removes) query hook.
  705. *
  706. * $hook must be either array with 'object' and 'method' entries, or null to remove hook.
  707. * Previous hook is returned.
  708. *
  709. * @param array $hook
  710. * @return array|null
  711. */
  712. public function setQueryHook($hook)
  713. {
  714. $prev = $this->_queryHook;
  715. $this->_queryHook = $hook;
  716. return $prev;
  717. }
  718. /**
  719. * Split multi statement query
  720. *
  721. * @param string $sql
  722. * @return array
  723. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  724. * @SuppressWarnings(PHPMD.NPathComplexity)
  725. * @deprecated 100.1.2
  726. */
  727. protected function _splitMultiQuery($sql)
  728. {
  729. $parts = preg_split(
  730. '#(;|\'|"|\\\\|//|--|\n|/\*|\*/)#',
  731. $sql,
  732. null,
  733. PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
  734. );
  735. $q = false;
  736. $c = false;
  737. $stmts = [];
  738. $s = '';
  739. foreach ($parts as $i => $part) {
  740. // strings
  741. if (($part === "'" || $part === '"') && ($i === 0 || $parts[$i-1] !== '\\')) {
  742. if ($q === false) {
  743. $q = $part;
  744. } elseif ($q === $part) {
  745. $q = false;
  746. }
  747. }
  748. // single line comments
  749. if (($part === '//' || $part === '--') && ($i === 0 || $parts[$i-1] === "\n")) {
  750. $c = $part;
  751. } elseif ($part === "\n" && ($c === '//' || $c === '--')) {
  752. $c = false;
  753. }
  754. // multi line comments
  755. if ($part === '/*' && $c === false) {
  756. $c = '/*';
  757. } elseif ($part === '*/' && $c === '/*') {
  758. $c = false;
  759. }
  760. // statements
  761. if ($part === ';' && $q === false && $c === false) {
  762. if (trim($s) !== '') {
  763. $stmts[] = trim($s);
  764. $s = '';
  765. }
  766. } else {
  767. $s .= $part;
  768. }
  769. }
  770. if (trim($s) !== '') {
  771. $stmts[] = trim($s);
  772. }
  773. return $stmts;
  774. }
  775. /**
  776. * Drop the Foreign Key from table
  777. *
  778. * @param string $tableName
  779. * @param string $fkName
  780. * @param string $schemaName
  781. * @return $this
  782. */
  783. public function dropForeignKey($tableName, $fkName, $schemaName = null)
  784. {
  785. $foreignKeys = $this->getForeignKeys($tableName, $schemaName);
  786. $fkName = strtoupper($fkName);
  787. if (substr($fkName, 0, 3) == 'FK_') {
  788. $fkName = substr($fkName, 3);
  789. }
  790. foreach ([$fkName, 'FK_' . $fkName] as $key) {
  791. if (isset($foreignKeys[$key])) {
  792. $sql = sprintf(
  793. 'ALTER TABLE %s DROP FOREIGN KEY %s',
  794. $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
  795. $this->quoteIdentifier($foreignKeys[$key]['FK_NAME'])
  796. );
  797. $this->resetDdlCache($tableName, $schemaName);
  798. $this->rawQuery($sql);
  799. $this->getSchemaListener()->dropForeignKey($tableName, $fkName);
  800. }
  801. }
  802. return $this;
  803. }
  804. /**
  805. * Prepare table before add constraint foreign key
  806. *
  807. * @param string $tableName
  808. * @param string $columnName
  809. * @param string $refTableName
  810. * @param string $refColumnName
  811. * @param string $onDelete
  812. * @return $this
  813. */
  814. public function purgeOrphanRecords(
  815. $tableName,
  816. $columnName,
  817. $refTableName,
  818. $refColumnName,
  819. $onDelete = AdapterInterface::FK_ACTION_CASCADE
  820. ) {
  821. $onDelete = strtoupper($onDelete);
  822. if ($onDelete == AdapterInterface::FK_ACTION_CASCADE
  823. || $onDelete == AdapterInterface::FK_ACTION_RESTRICT
  824. ) {
  825. $sql = sprintf(
  826. "DELETE p.* FROM %s AS p LEFT JOIN %s AS r ON p.%s = r.%s WHERE r.%s IS NULL",
  827. $this->quoteIdentifier($tableName),
  828. $this->quoteIdentifier($refTableName),
  829. $this->quoteIdentifier($columnName),
  830. $this->quoteIdentifier($refColumnName),
  831. $this->quoteIdentifier($refColumnName)
  832. );
  833. $this->rawQuery($sql);
  834. } elseif ($onDelete == AdapterInterface::FK_ACTION_SET_NULL) {
  835. $sql = sprintf(
  836. "UPDATE %s AS p LEFT JOIN %s AS r ON p.%s = r.%s SET p.%s = NULL WHERE r.%s IS NULL",
  837. $this->quoteIdentifier($tableName),
  838. $this->quoteIdentifier($refTableName),
  839. $this->quoteIdentifier($columnName),
  840. $this->quoteIdentifier($refColumnName),
  841. $this->quoteIdentifier($columnName),
  842. $this->quoteIdentifier($refColumnName)
  843. );
  844. $this->rawQuery($sql);
  845. }
  846. return $this;
  847. }
  848. /**
  849. * Check does table column exist
  850. *
  851. * @param string $tableName
  852. * @param string $columnName
  853. * @param string $schemaName
  854. * @return bool
  855. */
  856. public function tableColumnExists($tableName, $columnName, $schemaName = null)
  857. {
  858. $describe = $this->describeTable($tableName, $schemaName);
  859. foreach ($describe as $column) {
  860. if ($column['COLUMN_NAME'] == $columnName) {
  861. return true;
  862. }
  863. }
  864. return false;
  865. }
  866. /**
  867. * Adds new column to table.
  868. *
  869. * Generally $defintion must be array with column data to keep this call cross-DB compatible.
  870. * Using string as $definition is allowed only for concrete DB adapter.
  871. * Adds primary key if needed
  872. *
  873. * @param string $tableName
  874. * @param string $columnName
  875. * @param array|string $definition string specific or universal array DB Server definition
  876. * @param string $schemaName
  877. * @return true|\Zend_Db_Statement_Pdo
  878. * @throws \Zend_Db_Exception
  879. */
  880. public function addColumn($tableName, $columnName, $definition, $schemaName = null)
  881. {
  882. $this->getSchemaListener()->addColumn($tableName, $columnName, $definition);
  883. if ($this->tableColumnExists($tableName, $columnName, $schemaName)) {
  884. return true;
  885. }
  886. $primaryKey = '';
  887. if (is_array($definition)) {
  888. $definition = array_change_key_case($definition, CASE_UPPER);
  889. if (empty($definition['COMMENT'])) {
  890. throw new \Zend_Db_Exception("Impossible to create a column without comment.");
  891. }
  892. if (!empty($definition['PRIMARY'])) {
  893. $primaryKey = sprintf(', ADD PRIMARY KEY (%s)', $this->quoteIdentifier($columnName));
  894. }
  895. $definition = $this->_getColumnDefinition($definition);
  896. }
  897. $sql = sprintf(
  898. 'ALTER TABLE %s ADD COLUMN %s %s %s',
  899. $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
  900. $this->quoteIdentifier($columnName),
  901. $definition,
  902. $primaryKey
  903. );
  904. $result = $this->rawQuery($sql);
  905. $this->resetDdlCache($tableName, $schemaName);
  906. return $result;
  907. }
  908. /**
  909. * Delete table column
  910. *
  911. * @param string $tableName
  912. * @param string $columnName
  913. * @param string $schemaName
  914. * @return true|\Zend_Db_Statement_Pdo
  915. */
  916. public function dropColumn($tableName, $columnName, $schemaName = null)
  917. {
  918. if (!$this->tableColumnExists($tableName, $columnName, $schemaName)) {
  919. return true;
  920. }
  921. $this->getSchemaListener()->dropColumn($tableName, $columnName);
  922. $alterDrop = [];
  923. $foreignKeys = $this->getForeignKeys($tableName, $schemaName);
  924. foreach ($foreignKeys as $fkProp) {
  925. if ($fkProp['COLUMN_NAME'] == $columnName) {
  926. $this->getSchemaListener()->dropForeignKey($tableName, $fkProp['FK_NAME']);
  927. $alterDrop[] = 'DROP FOREIGN KEY ' . $this->quoteIdentifier($fkProp['FK_NAME']);
  928. }
  929. }
  930. /* drop index that after column removal would coincide with the existing index by indexed columns */
  931. foreach ($this->getIndexList($tableName, $schemaName) as $idxData) {
  932. $idxColumns = $idxData['COLUMNS_LIST'];
  933. $idxColumnKey = array_search($columnName, $idxColumns);
  934. if ($idxColumnKey !== false) {
  935. unset($idxColumns[$idxColumnKey]);
  936. if (empty($idxColumns)) {
  937. $this->getSchemaListener()->dropIndex($tableName, $idxData['KEY_NAME'], 'index');
  938. }
  939. if ($idxColumns && $this->_getIndexByColumns($tableName, $idxColumns, $schemaName)) {
  940. $this->dropIndex($tableName, $idxData['KEY_NAME'], $schemaName);
  941. }
  942. }
  943. }
  944. $alterDrop[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
  945. $sql = sprintf(
  946. 'ALTER TABLE %s %s',
  947. $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
  948. implode(', ', $alterDrop)
  949. );
  950. $result = $this->rawQuery($sql);
  951. $this->resetDdlCache($tableName, $schemaName);
  952. return $result;
  953. }
  954. /**
  955. * Retrieve index information by indexed columns or return NULL, if there is no index for a column list
  956. *
  957. * @param string $tableName
  958. * @param array $columns
  959. * @param string|null $schemaName
  960. * @return array|null
  961. */
  962. protected function _getIndexByColumns($tableName, array $columns, $schemaName)
  963. {
  964. foreach ($this->getIndexList($tableName, $schemaName) as $idxData) {
  965. if ($idxData['COLUMNS_LIST'] === $columns) {
  966. return $idxData;
  967. }
  968. }
  969. return null;
  970. }
  971. /**
  972. * Change the column name and definition
  973. *
  974. * For change definition of column - use modifyColumn
  975. *
  976. * @param string $tableName
  977. * @param string $oldColumnName
  978. * @param string $newColumnName
  979. * @param array $definition
  980. * @param boolean $flushData flush table statistic
  981. * @param string $schemaName
  982. * @return \Zend_Db_Statement_Pdo
  983. * @throws \Zend_Db_Exception
  984. */
  985. public function changeColumn(
  986. $tableName,
  987. $oldColumnName,
  988. $newColumnName,
  989. $definition,
  990. $flushData = false,
  991. $schemaName = null
  992. ) {
  993. $this->getSchemaListener()->changeColumn(
  994. $tableName,
  995. $oldColumnName,
  996. $newColumnName,
  997. $definition
  998. );
  999. if (!$this->tableColumnExists($tableName, $oldColumnName, $schemaName)) {
  1000. throw new \Zend_Db_Exception(
  1001. sprintf(
  1002. 'Column "%s" does not exist in table "%s".',
  1003. $oldColumnName,
  1004. $tableName
  1005. )
  1006. );
  1007. }
  1008. if (is_array($definition)) {
  1009. $definition = $this->_getColumnDefinition($definition);
  1010. }
  1011. $sql = sprintf(
  1012. 'ALTER TABLE %s CHANGE COLUMN %s %s %s',
  1013. $this->quoteIdentifier($tableName),
  1014. $this->quoteIdentifier($oldColumnName),
  1015. $this->quoteIdentifier($newColumnName),
  1016. $definition
  1017. );
  1018. $result = $this->rawQuery($sql);
  1019. if ($flushData) {
  1020. $this->showTableStatus($tableName, $schemaName);
  1021. }
  1022. $this->resetDdlCache($tableName, $schemaName);
  1023. return $result;
  1024. }
  1025. /**
  1026. * Modify the column definition
  1027. *
  1028. * @param string $tableName
  1029. * @param string $columnName
  1030. * @param array|string $definition
  1031. * @param boolean $flushData
  1032. * @param string $schemaName
  1033. * @return $this
  1034. * @throws \Zend_Db_Exception
  1035. */
  1036. public function modifyColumn($tableName, $columnName, $definition, $flushData = false, $schemaName = null)
  1037. {
  1038. $this->getSchemaListener()->modifyColumn(
  1039. $tableName,
  1040. $columnName,
  1041. $definition
  1042. );
  1043. if (!$this->tableColumnExists($tableName, $columnName, $schemaName)) {
  1044. throw new \Zend_Db_Exception(sprintf('Column "%s" does not exist in table "%s".', $columnName, $tableName));
  1045. }
  1046. if (is_array($definition)) {
  1047. $definition = $this->_getColumnDefinition($definition);
  1048. }
  1049. $sql = sprintf(
  1050. 'ALTER TABLE %s MODIFY COLUMN %s %s',
  1051. $this->quoteIdentifier($tableName),
  1052. $this->quoteIdentifier($columnName),
  1053. $definition
  1054. );
  1055. $this->rawQuery($sql);
  1056. if ($flushData) {
  1057. $this->showTableStatus($tableName, $schemaName);
  1058. }
  1059. $this->resetDdlCache($tableName, $schemaName);
  1060. return $this;
  1061. }
  1062. /**
  1063. * Show table status
  1064. *
  1065. * @param string $tableName
  1066. * @param string $schemaName
  1067. * @return mixed
  1068. */
  1069. public function showTableStatus($tableName, $schemaName = null)
  1070. {
  1071. $fromDbName = null;
  1072. if ($schemaName !== null) {
  1073. $fromDbName = ' FROM ' . $this->quoteIdentifier($schemaName);
  1074. }
  1075. $query = sprintf('SHOW TABLE STATUS%s LIKE %s', $fromDbName, $this->quote($tableName));
  1076. return $this->rawFetchRow($query);
  1077. }
  1078. /**
  1079. * Retrieve Create Table SQL
  1080. *
  1081. * @param string $tableName
  1082. * @param string $schemaName
  1083. * @return string
  1084. */
  1085. public function getCreateTable($tableName, $schemaName = null)
  1086. {
  1087. $cacheKey = $this->_getTableName($tableName, $schemaName);
  1088. $ddl = $this->loadDdlCache($cacheKey, self::DDL_CREATE);
  1089. if ($ddl === false) {
  1090. $sql = 'SHOW CREATE TABLE ' . $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
  1091. $ddl = $this->rawFetchRow($sql, 'Create Table');
  1092. $this->saveDdlCache($cacheKey, self::DDL_CREATE, $ddl);
  1093. }
  1094. return $ddl;
  1095. }
  1096. /**
  1097. * Retrieve the foreign keys descriptions for a table.
  1098. *
  1099. * The return value is an associative array keyed by the UPPERCASE foreign key,
  1100. * as returned by the RDBMS.
  1101. *
  1102. * The value of each array element is an associative array
  1103. * with the following keys:
  1104. *
  1105. * FK_NAME => string; original foreign key name
  1106. * SCHEMA_NAME => string; name of database or schema
  1107. * TABLE_NAME => string;
  1108. * COLUMN_NAME => string; column name
  1109. * REF_SCHEMA_NAME => string; name of reference database or schema
  1110. * REF_TABLE_NAME => string; reference table name
  1111. * REF_COLUMN_NAME => string; reference column name
  1112. * ON_DELETE => string; action type on delete row
  1113. *
  1114. * @param string $tableName
  1115. * @param string $schemaName
  1116. * @return array
  1117. */
  1118. public function getForeignKeys($tableName, $schemaName = null)
  1119. {
  1120. $cacheKey = $this->_getTableName($tableName, $schemaName);
  1121. $ddl = $this->loadDdlCache($cacheKey, self::DDL_FOREIGN_KEY);
  1122. if ($ddl === false) {
  1123. $ddl = [];
  1124. $createSql = $this->getCreateTable($tableName, $schemaName);
  1125. // collect CONSTRAINT
  1126. $regExp = '#,\s+CONSTRAINT `([^`]*)` FOREIGN KEY ?\(`([^`]*)`\) '
  1127. . 'REFERENCES (`([^`]*)`\.)?`([^`]*)` \(`([^`]*)`\)'
  1128. . '( ON DELETE (RESTRICT|CASCADE|SET NULL|NO ACTION))?'
  1129. . '( ON UPDATE (RESTRICT|CASCADE|SET NULL|NO ACTION))?#';
  1130. $matches = [];
  1131. preg_match_all($regExp, $createSql, $matches, PREG_SET_ORDER);
  1132. foreach ($matches as $match) {
  1133. $ddl[strtoupper($match[1])] = [
  1134. 'FK_NAME' => $match[1],
  1135. 'SCHEMA_NAME' => $schemaName,
  1136. 'TABLE_NAME' => $tableName,
  1137. 'COLUMN_NAME' => $match[2],
  1138. 'REF_SHEMA_NAME' => isset($match[4]) ? $match[4] : $schemaName,
  1139. 'REF_TABLE_NAME' => $match[5],
  1140. 'REF_COLUMN_NAME' => $match[6],
  1141. 'ON_DELETE' => isset($match[7]) ? $match[8] : ''
  1142. ];
  1143. }
  1144. $this->saveDdlCache($cacheKey, self::DDL_FOREIGN_KEY, $ddl);
  1145. }
  1146. return $ddl;
  1147. }
  1148. /**
  1149. * Retrieve the foreign keys tree for all tables
  1150. *
  1151. * @return array
  1152. */
  1153. public function getForeignKeysTree()
  1154. {
  1155. $tree = [];
  1156. foreach ($this->listTables() as $table) {
  1157. foreach ($this->getForeignKeys($table) as $key) {
  1158. $tree[$table][$key['COLUMN_NAME']] = $key;
  1159. }
  1160. }
  1161. return $tree;
  1162. }
  1163. /**
  1164. * Modify tables, used for upgrade process
  1165. *
  1166. * Change columns definitions, reset foreign keys, change tables comments and engines.
  1167. *
  1168. * The value of each array element is an associative array
  1169. * with the following keys:
  1170. *
  1171. * columns => array; list of columns definitions
  1172. * comment => string; table comment
  1173. * engine => string; table engine
  1174. *
  1175. * @param array $tables
  1176. * @return $this
  1177. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  1178. * @SuppressWarnings(PHPMD.NPathComplexity)
  1179. * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  1180. */
  1181. public function modifyTables($tables)
  1182. {
  1183. $foreignKeys = $this->getForeignKeysTree();
  1184. foreach ($tables as $table => $tableData) {
  1185. if (!$this->isTableExists($table)) {
  1186. continue;
  1187. }
  1188. foreach ($tableData['columns'] as $column => $columnDefinition) {
  1189. if (!$this->tableColumnExists($table, $column)) {
  1190. continue;
  1191. }
  1192. $droppedKeys = [];
  1193. foreach ($foreignKeys as $keyTable => $columns) {
  1194. foreach ($columns as $columnName => $keyOptions) {
  1195. if ($table == $keyOptions['REF_TABLE_NAME'] && $column == $keyOptions['REF_COLUMN_NAME']) {
  1196. $this->dropForeignKey($keyTable, $keyOptions['FK_NAME']);
  1197. $droppedKeys[] = $keyOptions;
  1198. }
  1199. }
  1200. }
  1201. $this->modifyColumn($table, $column, $columnDefinition);
  1202. foreach ($droppedKeys as $options) {
  1203. unset($columnDefinition['identity'], $columnDefinition['primary'], $columnDefinition['comment']);
  1204. $onDelete = $options['ON_DELETE'];
  1205. if ($onDelete == AdapterInterface::FK_ACTION_SET_NULL) {
  1206. $columnDefinition['nullable'] = true;
  1207. }
  1208. $this->modifyColumn($options['TABLE_NAME'], $options['COLUMN_NAME'], $columnDefinition);
  1209. $this->addForeignKey(
  1210. $options['FK_NAME'],
  1211. $options['TABLE_NAME'],
  1212. $options['COLUMN_NAME'],
  1213. $options['REF_TABLE_NAME'],
  1214. $options['REF_COLUMN_NAME'],
  1215. ($onDelete) ? $onDelete : AdapterInterface::FK_ACTION_NO_ACTION
  1216. );
  1217. }
  1218. }
  1219. if (!empty($tableData['comment'])) {
  1220. $this->changeTableComment($table, $tableData['comment']);
  1221. }
  1222. if (!empty($tableData['engine'])) {
  1223. $this->changeTableEngine($table, $tableData['engine']);
  1224. }
  1225. }
  1226. return $this;
  1227. }
  1228. /**
  1229. * Retrieve table index information
  1230. *
  1231. * The return value is an associative array keyed by the UPPERCASE index key (except for primary key,
  1232. * that is always stored under 'PRIMARY' key) as returned by the RDBMS.
  1233. *
  1234. * The value of each array element is an associative array
  1235. * with the following keys:
  1236. *
  1237. * SCHEMA_NAME => string; name of database or schema
  1238. * TABLE_NAME => string; name of the table
  1239. * KEY_NAME => string; the original index name
  1240. * COLUMNS_LIST => array; array of index column names
  1241. * INDEX_TYPE => string; lowercase, create index type
  1242. * INDEX_METHOD => string; index method using
  1243. * type => string; see INDEX_TYPE
  1244. * fields => array; see COLUMNS_LIST
  1245. *
  1246. * @param string $tableName
  1247. * @param string $schemaName
  1248. * @return array|string|int
  1249. */
  1250. public function getIndexList($tableName, $schemaName = null)
  1251. {
  1252. $cacheKey = $this->_getTableName($tableName, $schemaName);
  1253. $ddl = $this->loadDdlCache($cacheKey, self::DDL_INDEX);
  1254. if ($ddl === false) {
  1255. $ddl = [];
  1256. $sql = sprintf(
  1257. 'SHOW INDEX FROM %s',
  1258. $this->quoteIdentifier($this->_getTableName($tableName, $schemaName))
  1259. );
  1260. foreach ($this->fetchAll($sql) as $row) {
  1261. $fieldKeyName = 'Key_name';
  1262. $fieldNonUnique = 'Non_unique';
  1263. $fieldColumn = 'Column_name';
  1264. $fieldIndexType = 'Index_type';
  1265. if (strtolower($row[$fieldKeyName]) == AdapterInterface::INDEX_TYPE_PRIMARY) {
  1266. $indexType = AdapterInterface::INDEX_TYPE_PRIMARY;
  1267. } elseif ($row[$fieldNonUnique] == 0) {
  1268. $indexType = AdapterInterface::INDEX_TYPE_UNIQUE;
  1269. } elseif (strtolower($row[$fieldIndexType]) == AdapterInterface::INDEX_TYPE_FULLTEXT) {
  1270. $indexType = AdapterInterface::INDEX_TYPE_FULLTEXT;
  1271. } else {
  1272. $indexType = AdapterInterface::INDEX_TYPE_INDEX;
  1273. }
  1274. $upperKeyName = strtoupper($row[$fieldKeyName]);
  1275. if (isset($ddl[$upperKeyName])) {
  1276. $ddl[$upperKeyName]['fields'][] = $row[$fieldColumn]; // for compatible
  1277. $ddl[$upperKeyName]['COLUMNS_LIST'][] = $row[$fieldColumn];
  1278. } else {
  1279. $ddl[$upperKeyName] = [
  1280. 'SCHEMA_NAME' => $schemaName,
  1281. 'TABLE_NAME' => $tableName,
  1282. 'KEY_NAME' => $row[$fieldKeyName],
  1283. 'COLUMNS_LIST' => [$row[$fieldColumn]],
  1284. 'INDEX_TYPE' => $indexType,
  1285. 'INDEX_METHOD' => $row[$fieldIndexType],
  1286. 'type' => strtolower($indexType), // for compatibility
  1287. 'fields' => [$row[$fieldColumn]], // for compatibility
  1288. ];
  1289. }
  1290. }
  1291. $this->saveDdlCache($cacheKey, self::DDL_INDEX, $ddl);
  1292. }
  1293. return $ddl;
  1294. }
  1295. /**
  1296. * Remove duplicate entry for create key
  1297. *
  1298. * @param string $table
  1299. * @param array $fields
  1300. * @param string[] $ids
  1301. * @return $this
  1302. */
  1303. protected function _removeDuplicateEntry($table, $fields, $ids)
  1304. {
  1305. $where = [];
  1306. $i = 0;
  1307. foreach ($fields as $field) {
  1308. $where[] = $this->quoteInto($field . '=?', $ids[$i++]);
  1309. }
  1310. if (!$where) {
  1311. return $this;
  1312. }
  1313. $whereCond = implode(' AND ', $where);
  1314. $sql = sprintf('SELECT COUNT(*) as `cnt` FROM `%s` WHERE %s', $table, $whereCond);
  1315. $cnt = $this->rawFetchRow($sql, 'cnt');
  1316. if ($cnt > 1) {
  1317. $sql = sprintf(
  1318. 'DELETE FROM `%s` WHERE %s LIMIT %d',
  1319. $table,
  1320. $whereCond,
  1321. $cnt - 1
  1322. );
  1323. $this->rawQuery($sql);
  1324. }
  1325. return $this;
  1326. }
  1327. /**
  1328. * Creates and returns a new \Magento\Framework\DB\Select object for this adapter.
  1329. *
  1330. * @return Select
  1331. */
  1332. public function select()
  1333. {
  1334. return $this->selectFactory->create($this);
  1335. }
  1336. /**
  1337. * Quotes a value and places into a piece of text at a placeholder.
  1338. *
  1339. * Method revrited for handle empty arrays in value param
  1340. *
  1341. * @param string $text The text with a placeholder.
  1342. * @param mixed $value The value to quote.
  1343. * @param string $type OPTIONAL SQL datatype
  1344. * @param integer $count OPTIONAL count of placeholders to replace
  1345. * @return string An SQL-safe quoted value placed into the orignal text.
  1346. */
  1347. public function quoteInto($text, $value, $type = null, $count = null)
  1348. {
  1349. if (is_array($value) && empty($value)) {
  1350. $value = new \Zend_Db_Expr('NULL');
  1351. }
  1352. if ($value instanceof \DateTimeInterface) {
  1353. $value = $value->format('Y-m-d H:i:s');
  1354. }
  1355. return parent::quoteInto($text, $value, $type, $count);
  1356. }
  1357. /**
  1358. * Retrieve ddl cache name
  1359. *
  1360. * @param string $tableName
  1361. * @param string $schemaName
  1362. * @return string
  1363. */
  1364. protected function _getTableName($tableName, $schemaName = null)
  1365. {
  1366. return ($schemaName ? $schemaName . '.' : '') . $tableName;
  1367. }
  1368. /**
  1369. * Retrieve Id for cache
  1370. *
  1371. * @param string $tableKey
  1372. * @param int $ddlType
  1373. * @return string
  1374. */
  1375. protected function _getCacheId($tableKey, $ddlType)
  1376. {
  1377. return sprintf('%s_%s_%s', self::DDL_CACHE_PREFIX, $tableKey, $ddlType);
  1378. }
  1379. /**
  1380. * Load DDL data from cache
  1381. *
  1382. * Return false if cache does not exists
  1383. *
  1384. * @param string $tableCacheKey the table cache key
  1385. * @param int $ddlType the DDL constant
  1386. * @return string|array|int|false
  1387. */
  1388. public function loadDdlCache($tableCacheKey, $ddlType)
  1389. {
  1390. if (!$this->_isDdlCacheAllowed) {
  1391. return false;
  1392. }
  1393. if (isset($this->_ddlCache[$ddlType][$tableCacheKey])) {
  1394. return $this->_ddlCache[$ddlType][$tableCacheKey];
  1395. }
  1396. if ($this->_cacheAdapter) {
  1397. $cacheId = $this->_getCacheId($tableCacheKey, $ddlType);
  1398. $data = $this->_cacheAdapter->load($cacheId);
  1399. if ($data !== false) {
  1400. $data = $this->serializer->unserialize($data);
  1401. $this->_ddlCache[$ddlType][$tableCacheKey] = $data;
  1402. }
  1403. return $data;
  1404. }
  1405. return false;
  1406. }
  1407. /**
  1408. * Save DDL data into cache
  1409. *
  1410. * @param string $tableCacheKey
  1411. * @param int $ddlType
  1412. * @param array $data
  1413. * @return $this
  1414. */
  1415. public function saveDdlCache($tableCacheKey, $ddlType, $data)
  1416. {
  1417. if (!$this->_isDdlCacheAllowed) {
  1418. return $this;
  1419. }
  1420. $this->_ddlCache[$ddlType][$tableCacheKey] = $data;
  1421. if ($this->_cacheAdapter) {
  1422. $cacheId = $this->_getCacheId($tableCacheKey, $ddlType);
  1423. $data = $this->serializer->serialize($data);
  1424. $this->_cacheAdapter->save($data, $cacheId, [self::DDL_CACHE_TAG]);
  1425. }
  1426. return $this;
  1427. }
  1428. /**
  1429. * Reset cached DDL data from cache
  1430. *
  1431. * If table name is null - reset all cached DDL data
  1432. *
  1433. * @param string $tableName
  1434. * @param string $schemaName OPTIONAL
  1435. * @return $this
  1436. */
  1437. public function resetDdlCache($tableName = null, $schemaName = null)
  1438. {
  1439. if (!$this->_isDdlCacheAllowed) {
  1440. return $this;
  1441. }
  1442. if ($tableName === null) {
  1443. $this->_ddlCache = [];
  1444. if ($this->_cacheAdapter) {
  1445. $this->_cacheAdapter->clean(\Zend_Cache::CLEANING_MODE_MATCHING_TAG, [self::DDL_CACHE_TAG]);
  1446. }
  1447. } else {
  1448. $cacheKey = $this->_getTableName($tableName, $schemaName);
  1449. $ddlTypes = [self::DDL_DESCRIBE, self::DDL_CREATE, self::DDL_INDEX, self::DDL_FOREIGN_KEY];
  1450. foreach ($ddlTypes as $ddlType) {
  1451. unset($this->_ddlCache[$ddlType][$cacheKey]);
  1452. }
  1453. if ($this->_cacheAdapter) {
  1454. foreach ($ddlTypes as $ddlType) {
  1455. $cacheId = $this->_getCacheId($cacheKey, $ddlType);
  1456. $this->_cacheAdapter->remove($cacheId);
  1457. }
  1458. }
  1459. }
  1460. return $this;
  1461. }
  1462. /**
  1463. * Disallow DDL caching
  1464. *
  1465. * @return $this
  1466. */
  1467. public function disallowDdlCache()
  1468. {
  1469. $this->_isDdlCacheAllowed = false;
  1470. return $this;
  1471. }
  1472. /**
  1473. * Allow DDL caching
  1474. *
  1475. * @return $this
  1476. */
  1477. public function allowDdlCache()
  1478. {
  1479. $this->_isDdlCacheAllowed = true;
  1480. return $this;
  1481. }
  1482. /**
  1483. * Returns the column descriptions for a table.
  1484. *
  1485. * The return value is an associative array keyed by the column name,
  1486. * as returned by the RDBMS.
  1487. *
  1488. * The value of each array element is an associative array
  1489. * with the following keys:
  1490. *
  1491. * SCHEMA_NAME => string; name of database or schema
  1492. * TABLE_NAME => string;
  1493. * COLUMN_NAME => string; column name
  1494. * COLUMN_POSITION => number; ordinal position of column in table
  1495. * DATA_TYPE => string; SQL datatype name of column
  1496. * DEFAULT => string; default expression of column, null if none
  1497. * NULLABLE => boolean; true if column can have nulls
  1498. * LENGTH => number; length of CHAR/VARCHAR
  1499. * SCALE => number; scale of NUMERIC/DECIMAL
  1500. * PRECISION => number; precision of NUMERIC/DECIMAL
  1501. * UNSIGNED => boolean; unsigned property of an integer type
  1502. * PRIMARY => boolean; true if column is part of the primary key
  1503. * PRIMARY_POSITION => integer; position of column in primary key
  1504. * IDENTITY => integer; true if column is auto-generated with unique values
  1505. *
  1506. * @param string $tableName
  1507. * @param string $schemaName OPTIONAL
  1508. * @return array
  1509. */
  1510. public function describeTable($tableName, $schemaName = null)
  1511. {
  1512. $cacheKey = $this->_getTableName($tableName, $schemaName);
  1513. $ddl = $this->loadDdlCache($cacheKey, self::DDL_DESCRIBE);
  1514. if ($ddl === false) {
  1515. $ddl = parent::describeTable($tableName, $schemaName);
  1516. /**
  1517. * Remove bug in some MySQL versions, when int-column without default value is described as:
  1518. * having default empty string value
  1519. */
  1520. $affected = ['tinyint', 'smallint', 'mediumint', 'int', 'bigint'];
  1521. foreach ($ddl as $key => $columnData) {
  1522. if (($columnData['DEFAULT'] === '') && (array_search($columnData['DATA_TYPE'], $affected) !== false)) {
  1523. $ddl[$key]['DEFAULT'] = null;
  1524. }
  1525. }
  1526. $this->saveDdlCache($cacheKey, self::DDL_DESCRIBE, $ddl);
  1527. }
  1528. return $ddl;
  1529. }
  1530. /**
  1531. * Format described column to definition, ready to be added to ddl table.
  1532. *
  1533. * Return array with keys: name, type, length, options, comment
  1534. *
  1535. * @param array $columnData
  1536. * @return array
  1537. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  1538. * @SuppressWarnings(PHPMD.NPathComplexity)
  1539. */
  1540. public function getColumnCreateByDescribe($columnData)
  1541. {
  1542. $type = $this->_getColumnTypeByDdl($columnData);
  1543. $options = [];
  1544. if ($columnData['IDENTITY'] === true) {
  1545. $options['identity'] = true;
  1546. }
  1547. if ($columnData['UNSIGNED'] === true) {
  1548. $options['unsigned'] = true;
  1549. }
  1550. if ($columnData['NULLABLE'] === false
  1551. && !($type == Table::TYPE_TEXT && strlen($columnData['DEFAULT']) != 0)
  1552. ) {
  1553. $options['nullable'] = false;
  1554. }
  1555. if ($columnData['PRIMARY'] === true) {
  1556. $options['primary'] = true;
  1557. }
  1558. if ($columnData['DEFAULT'] !== null && $type != Table::TYPE_TEXT) {
  1559. $options['default'] = $this->quote($columnData['DEFAULT']);
  1560. }
  1561. if (strlen($columnData['SCALE']) > 0) {
  1562. $options['scale'] = $columnData['SCALE'];
  1563. }
  1564. if (strlen($columnData['PRECISION']) > 0) {
  1565. $options['precision'] = $columnData['PRECISION'];
  1566. }
  1567. $comment = $this->string->upperCaseWords($columnData['COLUMN_NAME'], '_', ' ');
  1568. $result = [
  1569. 'name' => $columnData['COLUMN_NAME'],
  1570. 'type' => $type,
  1571. 'length' => $columnData['LENGTH'],
  1572. 'options' => $options,
  1573. 'comment' => $comment,
  1574. ];
  1575. return $result;
  1576. }
  1577. /**
  1578. * Create \Magento\Framework\DB\Ddl\Table object by data from describe table
  1579. *
  1580. * @param string $tableName
  1581. * @param string $newTableName
  1582. * @return Table
  1583. */
  1584. public function createTableByDdl($tableName, $newTableName)
  1585. {
  1586. $describe = $this->describeTable($tableName);
  1587. $table = $this->newTable($newTableName)
  1588. ->setComment($this->string->upperCaseWords($newTableName, '_', ' '));
  1589. foreach ($describe as $columnData) {
  1590. $columnInfo = $this->getColumnCreateByDescribe($columnData);
  1591. $table->addColumn(
  1592. $columnInfo['name'],
  1593. $columnInfo['type'],
  1594. $columnInfo['length'],
  1595. $columnInfo['options'],
  1596. $columnInfo['comment']
  1597. );
  1598. }
  1599. $indexes = $this->getIndexList($tableName);
  1600. foreach ($indexes as $indexData) {
  1601. /**
  1602. * Do not create primary index - it is created with identity column.
  1603. * For reliability check both name and type, because these values can start to differ in future.
  1604. */
  1605. if (($indexData['KEY_NAME'] == 'PRIMARY')
  1606. || ($indexData['INDEX_TYPE'] == AdapterInterface::INDEX_TYPE_PRIMARY)
  1607. ) {
  1608. continue;
  1609. }
  1610. $fields = $indexData['COLUMNS_LIST'];
  1611. $options = ['type' => $indexData['INDEX_TYPE']];
  1612. $table->addIndex($this->getIndexName($newTableName, $fields, $indexData['INDEX_TYPE']), $fields, $options);
  1613. }
  1614. $foreignKeys = $this->getForeignKeys($tableName);
  1615. foreach ($foreignKeys as $keyData) {
  1616. $fkName = $this->getForeignKeyName(
  1617. $newTableName,
  1618. $keyData['COLUMN_NAME'],
  1619. $keyData['REF_TABLE_NAME'],
  1620. $keyData['REF_COLUMN_NAME']
  1621. );
  1622. $onDelete = $this->_getDdlAction($keyData['ON_DELETE']);
  1623. $table->addForeignKey(
  1624. $fkName,
  1625. $keyData['COLUMN_NAME'],
  1626. $keyData['REF_TABLE_NAME'],
  1627. $keyData['REF_COLUMN_NAME'],
  1628. $onDelete
  1629. );
  1630. }
  1631. // Set additional options
  1632. $tableData = $this->showTableStatus($tableName);
  1633. $table->setOption('type', $tableData['Engine']);
  1634. return $table;
  1635. }
  1636. /**
  1637. * Modify the column definition by data from describe table
  1638. *
  1639. * @param string $tableName
  1640. * @param string $columnName
  1641. * @param array $definition
  1642. * @param boolean $flushData
  1643. * @param string $schemaName
  1644. * @return $this
  1645. */
  1646. public function modifyColumnByDdl($tableName, $columnName, $definition, $flushData = false, $schemaName = null)
  1647. {
  1648. $definition = array_change_key_case($definition, CASE_UPPER);
  1649. $definition['COLUMN_TYPE'] = $this->_getColumnTypeByDdl($definition);
  1650. if (array_key_exists('DEFAULT', $definition) && $definition['DEFAULT'] === null) {
  1651. unset($definition['DEFAULT']);
  1652. }
  1653. return $this->modifyColumn($tableName, $columnName, $definition, $flushData, $schemaName);
  1654. }
  1655. /**
  1656. * Retrieve column data type by data from describe table
  1657. *
  1658. * @param array $column
  1659. * @return string
  1660. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  1661. */
  1662. protected function _getColumnTypeByDdl($column)
  1663. {
  1664. switch ($column['DATA_TYPE']) {
  1665. case 'bool':
  1666. return Table::TYPE_BOOLEAN;
  1667. case 'tinytext':
  1668. case 'char':
  1669. case 'varchar':
  1670. case 'text':
  1671. case 'mediumtext':
  1672. case 'longtext':
  1673. return Table::TYPE_TEXT;
  1674. case 'blob':
  1675. case 'mediumblob':
  1676. case 'longblob':
  1677. return Table::TYPE_BLOB;
  1678. case 'tinyint':
  1679. case 'smallint':
  1680. return Table::TYPE_SMALLINT;
  1681. case 'mediumint':
  1682. case 'int':
  1683. return Table::TYPE_INTEGER;
  1684. case 'bigint':
  1685. return Table::TYPE_BIGINT;
  1686. case 'datetime':
  1687. return Table::TYPE_DATETIME;
  1688. case 'timestamp':
  1689. return Table::TYPE_TIMESTAMP;
  1690. case 'date':
  1691. return Table::TYPE_DATE;
  1692. case 'float':
  1693. return Table::TYPE_FLOAT;
  1694. case 'decimal':
  1695. case 'numeric':
  1696. return Table::TYPE_DECIMAL;
  1697. }
  1698. }
  1699. /**
  1700. * Change table storage engine
  1701. *
  1702. * @param string $tableName
  1703. * @param string $engine
  1704. * @param string $schemaName
  1705. * @return \Zend_Db_Statement_Pdo
  1706. */
  1707. public function changeTableEngine($tableName, $engine, $schemaName = null)
  1708. {
  1709. $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
  1710. $sql = sprintf('ALTER TABLE %s ENGINE=%s', $table, $engine);
  1711. return $this->rawQuery($sql);
  1712. }
  1713. /**
  1714. * Change table comment
  1715. *
  1716. * @param string $tableName
  1717. * @param string $comment
  1718. * @param string $schemaName
  1719. * @return \Zend_Db_Statement_Pdo
  1720. */
  1721. public function changeTableComment($tableName, $comment, $schemaName = null)
  1722. {
  1723. $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
  1724. $sql = sprintf("ALTER TABLE %s COMMENT='%s'", $table, $comment);
  1725. return $this->rawQuery($sql);
  1726. }
  1727. /**
  1728. * Inserts a table row with specified data
  1729. *
  1730. * Special for Zero values to identity column
  1731. *
  1732. * @param string $table
  1733. * @param array $bind
  1734. * @return int The number of affected rows.
  1735. */
  1736. public function insertForce($table, array $bind)
  1737. {
  1738. $this->rawQuery("SET @OLD_INSERT_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'");
  1739. $result = $this->insert($table, $bind);
  1740. $this->rawQuery("SET SQL_MODE=IFNULL(@OLD_INSERT_SQL_MODE,'')");
  1741. return $result;
  1742. }
  1743. /**
  1744. * Inserts a table row with specified data.
  1745. *
  1746. * @param string $table The table to insert data into.
  1747. * @param array $data Column-value pairs or array of column-value pairs.
  1748. * @param array $fields update fields pairs or values
  1749. * @return int The number of affected rows.
  1750. * @throws \Zend_Db_Exception
  1751. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  1752. * @SuppressWarnings(PHPMD.NPathComplexity)
  1753. */
  1754. public function insertOnDuplicate($table, array $data, array $fields = [])
  1755. {
  1756. // extract and quote col names from the array keys
  1757. $row = reset($data); // get first element from data array
  1758. $bind = []; // SQL bind array
  1759. $values = [];
  1760. if (is_array($row)) { // Array of column-value pairs
  1761. $cols = array_keys($row);
  1762. foreach ($data as $row) {
  1763. if (array_diff($cols, array_keys($row))) {
  1764. throw new \Zend_Db_Exception('Invalid data for insert');
  1765. }
  1766. $values[] = $this->_prepareInsertData($row, $bind);
  1767. }
  1768. unset($row);
  1769. } else { // Column-value pairs
  1770. $cols = array_keys($data);
  1771. $values[] = $this->_prepareInsertData($data, $bind);
  1772. }
  1773. $updateFields = [];
  1774. if (empty($fields)) {
  1775. $fields = $cols;
  1776. }
  1777. // prepare ON DUPLICATE KEY conditions
  1778. foreach ($fields as $k => $v) {
  1779. $field = $value = null;
  1780. if (!is_numeric($k)) {
  1781. $field = $this->quoteIdentifier($k);
  1782. if ($v instanceof \Zend_Db_Expr) {
  1783. $value = $v->__toString();
  1784. } elseif ($v instanceof \Zend\Db\Sql\Expression) {
  1785. $value = $v->getExpression();
  1786. } elseif (is_string($v)) {
  1787. $value = sprintf('VALUES(%s)', $this->quoteIdentifier($v));
  1788. } elseif (is_numeric($v)) {
  1789. $value = $this->quoteInto('?', $v);
  1790. }
  1791. } elseif (is_string($v)) {
  1792. $value = sprintf('VALUES(%s)', $this->quoteIdentifier($v));
  1793. $field = $this->quoteIdentifier($v);
  1794. }
  1795. if ($field && is_string($value) && $value !== '') {
  1796. $updateFields[] = sprintf('%s = %s', $field, $value);
  1797. }
  1798. }
  1799. $insertSql = $this->_getInsertSqlQuery($table, $cols, $values);
  1800. if ($updateFields) {
  1801. $insertSql .= ' ON DUPLICATE KEY UPDATE ' . implode(', ', $updateFields);
  1802. }
  1803. // execute the statement and return the number of affected rows
  1804. $stmt = $this->query($insertSql, array_values($bind));
  1805. $result = $stmt->rowCount();
  1806. return $result;
  1807. }
  1808. /**
  1809. * Inserts a table multiply rows with specified data.
  1810. *
  1811. * @param string|array|\Zend_Db_Expr $table The table to insert data into.
  1812. * @param array $data Column-value pairs or array of Column-value pairs.
  1813. * @return int The number of affected rows.
  1814. * @throws \Zend_Db_Exception
  1815. */
  1816. public function insertMultiple($table, array $data)
  1817. {
  1818. $row = reset($data);
  1819. // support insert syntaxes
  1820. if (!is_array($row)) {
  1821. return $this->insert($table, $data);
  1822. }
  1823. // validate data array
  1824. $cols = array_keys($row);
  1825. $insertArray = [];
  1826. foreach ($data as $row) {
  1827. $line = [];
  1828. if (array_diff($cols, array_keys($row))) {
  1829. throw new \Zend_Db_Exception('Invalid data for insert');
  1830. }
  1831. foreach ($cols as $field) {
  1832. $line[] = $row[$field];
  1833. }
  1834. $insertArray[] = $line;
  1835. }
  1836. unset($row);
  1837. return $this->insertArray($table, $cols, $insertArray);
  1838. }
  1839. /**
  1840. * Insert array into a table based on columns definition
  1841. *
  1842. * $data can be represented as:
  1843. * - arrays of values ordered according to columns in $columns array
  1844. * array(
  1845. * array('value1', 'value2'),
  1846. * array('value3', 'value4'),
  1847. * )
  1848. * - array of values, if $columns contains only one column
  1849. * array('value1', 'value2')
  1850. *
  1851. * @param string $table
  1852. * @param string[] $columns
  1853. * @param array $data
  1854. * @param int $strategy
  1855. * @return int
  1856. * @throws \Zend_Db_Exception
  1857. */
  1858. public function insertArray($table, array $columns, array $data, $strategy = 0)
  1859. {
  1860. $values = [];
  1861. $bind = [];
  1862. $columnsCount = count($columns);
  1863. foreach ($data as $row) {
  1864. if (is_array($row) && $columnsCount != count($row)) {
  1865. throw new \Zend_Db_Exception('Invalid data for insert');
  1866. }
  1867. $values[] = $this->_prepareInsertData($row, $bind);
  1868. }
  1869. switch ($strategy) {
  1870. case self::REPLACE:
  1871. $query = $this->_getReplaceSqlQuery($table, $columns, $values);
  1872. break;
  1873. default:
  1874. $query = $this->_getInsertSqlQuery($table, $columns, $values, $strategy);
  1875. }
  1876. // execute the statement and return the number of affected rows
  1877. $stmt = $this->query($query, $bind);
  1878. $result = $stmt->rowCount();
  1879. return $result;
  1880. }
  1881. /**
  1882. * Set cache adapter
  1883. *
  1884. * @param FrontendInterface $cacheAdapter
  1885. * @return $this
  1886. */
  1887. public function setCacheAdapter(FrontendInterface $cacheAdapter)
  1888. {
  1889. $this->_cacheAdapter = $cacheAdapter;
  1890. return $this;
  1891. }
  1892. /**
  1893. * Return new DDL Table object
  1894. *
  1895. * @param string $tableName the table name
  1896. * @param string $schemaName the database/schema name
  1897. * @return Table
  1898. */
  1899. public function newTable($tableName = null, $schemaName = null)
  1900. {
  1901. $table = new Table();
  1902. if ($tableName !== null) {
  1903. $table->setName($tableName);
  1904. }
  1905. if ($schemaName !== null) {
  1906. $table->setSchema($schemaName);
  1907. }
  1908. if (isset($this->_config['engine'])) {
  1909. $table->setOption('type', $this->_config['engine']);
  1910. }
  1911. return $table;
  1912. }
  1913. /**
  1914. * Create table
  1915. *
  1916. * @param Table $table
  1917. * @throws \Zend_Db_Exception
  1918. * @return \Zend_Db_Statement_Pdo
  1919. */
  1920. public function createTable(Table $table)
  1921. {
  1922. $this->getSchemaListener()->createTable($table);
  1923. $columns = $table->getColumns();
  1924. foreach ($columns as $columnEntry) {
  1925. if (empty($columnEntry['COMMENT'])) {
  1926. throw new \Zend_Db_Exception("Cannot create table without columns comments");
  1927. }
  1928. }
  1929. $sqlFragment = array_merge(
  1930. $this->_getColumnsDefinition($table),
  1931. $this->_getIndexesDefinition($table),
  1932. $this->_getForeignKeysDefinition($table)
  1933. );
  1934. $tableOptions = $this->_getOptionsDefinition($table);
  1935. $sql = sprintf(
  1936. "CREATE TABLE IF NOT EXISTS %s (\n%s\n) %s",
  1937. $this->quoteIdentifier($table->getName()),
  1938. implode(",\n", $sqlFragment),
  1939. implode(" ", $tableOptions)
  1940. );
  1941. if ($this->getTransactionLevel() > 0) {
  1942. $result = $this->createConnection()->query($sql);
  1943. } else {
  1944. $result = $this->query($sql);
  1945. }
  1946. $this->resetDdlCache($table->getName(), $table->getSchema());
  1947. return $result;
  1948. }
  1949. /**
  1950. * Create temporary table
  1951. *
  1952. * @param \Magento\Framework\DB\Ddl\Table $table
  1953. * @throws \Zend_Db_Exception
  1954. * @return \Zend_Db_Pdo_Statement
  1955. * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  1956. */
  1957. public function createTemporaryTable(\Magento\Framework\DB\Ddl\Table $table)
  1958. {
  1959. $columns = $table->getColumns();
  1960. $sqlFragment = array_merge(
  1961. $this->_getColumnsDefinition($table),
  1962. $this->_getIndexesDefinition($table),
  1963. $this->_getForeignKeysDefinition($table)
  1964. );
  1965. $tableOptions = $this->_getOptionsDefinition($table);
  1966. $sql = sprintf(
  1967. "CREATE TEMPORARY TABLE %s (\n%s\n) %s",
  1968. $this->quoteIdentifier($table->getName()),
  1969. implode(",\n", $sqlFragment),
  1970. implode(" ", $tableOptions)
  1971. );
  1972. return $this->query($sql);
  1973. }
  1974. /**
  1975. * Create temporary table like
  1976. *
  1977. * @param string $temporaryTableName
  1978. * @param string $originTableName
  1979. * @param bool $ifNotExists
  1980. * @return \Zend_Db_Statement_Pdo
  1981. */
  1982. public function createTemporaryTableLike($temporaryTableName, $originTableName, $ifNotExists = false)
  1983. {
  1984. $ifNotExistsSql = ($ifNotExists ? 'IF NOT EXISTS' : '');
  1985. $temporaryTable = $this->quoteIdentifier($this->_getTableName($temporaryTableName));
  1986. $originTable = $this->quoteIdentifier($this->_getTableName($originTableName));
  1987. $sql = sprintf('CREATE TEMPORARY TABLE %s %s LIKE %s', $ifNotExistsSql, $temporaryTable, $originTable);
  1988. return $this->query($sql);
  1989. }
  1990. /**
  1991. * Rename several tables
  1992. *
  1993. * @param array $tablePairs array('oldName' => 'Name1', 'newName' => 'Name2')
  1994. *
  1995. * @return boolean
  1996. * @throws \Zend_Db_Exception
  1997. */
  1998. public function renameTablesBatch(array $tablePairs)
  1999. {
  2000. if (count($tablePairs) == 0) {
  2001. throw new \Zend_Db_Exception('Please provide tables for rename');
  2002. }
  2003. $renamesList = [];
  2004. $tablesList = [];
  2005. foreach ($tablePairs as $pair) {
  2006. $oldTableName = $pair['oldName'];
  2007. $newTableName = $pair['newName'];
  2008. $renamesList[] = sprintf('%s TO %s', $oldTableName, $newTableName);
  2009. $tablesList[$oldTableName] = $oldTableName;
  2010. $tablesList[$newTableName] = $newTableName;
  2011. }
  2012. $query = sprintf('RENAME TABLE %s', implode(',', $renamesList));
  2013. $this->query($query);
  2014. foreach ($tablesList as $table) {
  2015. $this->resetDdlCache($table);
  2016. }
  2017. return true;
  2018. }
  2019. /**
  2020. * Retrieve columns and primary keys definition array for create table
  2021. *
  2022. * @param Table $table
  2023. * @return string[]
  2024. * @throws \Zend_Db_Exception
  2025. */
  2026. protected function _getColumnsDefinition(Table $table)
  2027. {
  2028. $definition = [];
  2029. $primary = [];
  2030. $columns = $table->getColumns();
  2031. if (empty($columns)) {
  2032. throw new \Zend_Db_Exception('Table columns are not defined');
  2033. }
  2034. foreach ($columns as $columnData) {
  2035. $columnDefinition = $this->_getColumnDefinition($columnData);
  2036. if ($columnData['PRIMARY']) {
  2037. $primary[$columnData['COLUMN_NAME']] = $columnData['PRIMARY_POSITION'];
  2038. }
  2039. $definition[] = sprintf(
  2040. ' %s %s',
  2041. $this->quoteIdentifier($columnData['COLUMN_NAME']),
  2042. $columnDefinition
  2043. );
  2044. }
  2045. // PRIMARY KEY
  2046. if (!empty($primary)) {
  2047. asort($primary, SORT_NUMERIC);
  2048. $primary = array_map([$this, 'quoteIdentifier'], array_keys($primary));
  2049. $definition[] = sprintf(' PRIMARY KEY (%s)', implode(', ', $primary));
  2050. }
  2051. return $definition;
  2052. }
  2053. /**
  2054. * Retrieve table indexes definition array for create table
  2055. *
  2056. * @param Table $table
  2057. * @return string[]
  2058. */
  2059. protected function _getIndexesDefinition(Table $table)
  2060. {
  2061. $definition = [];
  2062. $indexes = $table->getIndexes();
  2063. foreach ($indexes as $indexData) {
  2064. if (!empty($indexData['TYPE'])) {
  2065. //Skipping not supported fulltext indexes for NDB
  2066. if (($indexData['TYPE'] == AdapterInterface::INDEX_TYPE_FULLTEXT) && $this->isNdb($table)) {
  2067. continue;
  2068. }
  2069. switch ($indexData['TYPE']) {
  2070. case AdapterInterface::INDEX_TYPE_PRIMARY:
  2071. $indexType = 'PRIMARY KEY';
  2072. unset($indexData['INDEX_NAME']);
  2073. break;
  2074. default:
  2075. $indexType = strtoupper($indexData['TYPE']);
  2076. break;
  2077. }
  2078. } else {
  2079. $indexType = 'KEY';
  2080. }
  2081. $columns = [];
  2082. foreach ($indexData['COLUMNS'] as $columnData) {
  2083. $column = $this->quoteIdentifier($columnData['NAME']);
  2084. if (!empty($columnData['SIZE'])) {
  2085. $column .= sprintf('(%d)', $columnData['SIZE']);
  2086. }
  2087. $columns[] = $column;
  2088. }
  2089. $indexName = isset($indexData['INDEX_NAME']) ? $this->quoteIdentifier($indexData['INDEX_NAME']) : '';
  2090. $definition[] = sprintf(
  2091. ' %s %s (%s)',
  2092. $indexType,
  2093. $indexName,
  2094. implode(', ', $columns)
  2095. );
  2096. }
  2097. return $definition;
  2098. }
  2099. /**
  2100. * Check if NDB is used for table
  2101. *
  2102. * @param Table $table
  2103. * @return bool
  2104. */
  2105. protected function isNdb(Table $table)
  2106. {
  2107. $engineType = strtolower($table->getOption('type'));
  2108. return $engineType == 'ndb' || $engineType == 'ndbcluster';
  2109. }
  2110. /**
  2111. * Retrieve table foreign keys definition array for create table
  2112. *
  2113. * @param Table $table
  2114. * @return string[]
  2115. */
  2116. protected function _getForeignKeysDefinition(Table $table)
  2117. {
  2118. $definition = [];
  2119. $relations = $table->getForeignKeys();
  2120. if (!empty($relations)) {
  2121. foreach ($relations as $fkData) {
  2122. $onDelete = $this->_getDdlAction($fkData['ON_DELETE']);
  2123. $definition[] = sprintf(
  2124. ' CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s) ON DELETE %s',
  2125. $this->quoteIdentifier($fkData['FK_NAME']),
  2126. $this->quoteIdentifier($fkData['COLUMN_NAME']),
  2127. $this->quoteIdentifier($fkData['REF_TABLE_NAME']),
  2128. $this->quoteIdentifier($fkData['REF_COLUMN_NAME']),
  2129. $onDelete
  2130. );
  2131. }
  2132. }
  2133. return $definition;
  2134. }
  2135. /**
  2136. * Retrieve table options definition array for create table
  2137. *
  2138. * @param Table $table
  2139. * @return string[]
  2140. * @throws \Zend_Db_Exception
  2141. */
  2142. protected function _getOptionsDefinition(Table $table)
  2143. {
  2144. $definition = [];
  2145. $comment = $table->getComment();
  2146. if (empty($comment)) {
  2147. throw new \Zend_Db_Exception('Comment for table is required and must be defined');
  2148. }
  2149. $definition[] = $this->quoteInto('COMMENT=?', $comment);
  2150. $tableProps = [
  2151. 'type' => 'ENGINE=%s',
  2152. 'checksum' => 'CHECKSUM=%d',
  2153. 'auto_increment' => 'AUTO_INCREMENT=%d',
  2154. 'avg_row_length' => 'AVG_ROW_LENGTH=%d',
  2155. 'max_rows' => 'MAX_ROWS=%d',
  2156. 'min_rows' => 'MIN_ROWS=%d',
  2157. 'delay_key_write' => 'DELAY_KEY_WRITE=%d',
  2158. 'row_format' => 'row_format=%s',
  2159. 'charset' => 'charset=%s',
  2160. 'collate' => 'COLLATE=%s',
  2161. ];
  2162. foreach ($tableProps as $key => $mask) {
  2163. $v = $table->getOption($key);
  2164. if ($v !== null) {
  2165. $definition[] = sprintf($mask, $v);
  2166. }
  2167. }
  2168. return $definition;
  2169. }
  2170. /**
  2171. * Get column definition from description
  2172. *
  2173. * @param array $options
  2174. * @param null|string $ddlType
  2175. * @return string
  2176. */
  2177. public function getColumnDefinitionFromDescribe($options, $ddlType = null)
  2178. {
  2179. $columnInfo = $this->getColumnCreateByDescribe($options);
  2180. foreach ($columnInfo['options'] as $key => $value) {
  2181. $columnInfo[$key] = $value;
  2182. }
  2183. return $this->_getColumnDefinition($columnInfo, $ddlType);
  2184. }
  2185. /**
  2186. * Retrieve column definition fragment
  2187. *
  2188. * @param array $options
  2189. * @param string $ddlType Table DDL Column type constant
  2190. * @throws \Magento\Framework\Exception\LocalizedException
  2191. * @return string
  2192. * @throws \Zend_Db_Exception
  2193. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  2194. * @SuppressWarnings(PHPMD.NPathComplexity)
  2195. * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  2196. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  2197. */
  2198. protected function _getColumnDefinition($options, $ddlType = null)
  2199. {
  2200. // convert keys to uppercase
  2201. $options = array_change_key_case($options, CASE_UPPER);
  2202. $cType = null;
  2203. $cUnsigned = false;
  2204. $cNullable = true;
  2205. $cDefault = false;
  2206. $cIdentity = false;
  2207. // detect and validate column type
  2208. if ($ddlType === null) {
  2209. $ddlType = $this->_getDdlType($options);
  2210. }
  2211. if (empty($ddlType) || !isset($this->_ddlColumnTypes[$ddlType])) {
  2212. throw new \Zend_Db_Exception('Invalid column definition data');
  2213. }
  2214. // column size
  2215. $cType = $this->_ddlColumnTypes[$ddlType];
  2216. switch ($ddlType) {
  2217. case Table::TYPE_SMALLINT:
  2218. case Table::TYPE_INTEGER:
  2219. case Table::TYPE_BIGINT:
  2220. if (!empty($options['UNSIGNED'])) {
  2221. $cUnsigned = true;
  2222. }
  2223. break;
  2224. case Table::TYPE_DECIMAL:
  2225. case Table::TYPE_FLOAT:
  2226. case Table::TYPE_NUMERIC:
  2227. $precision = 10;
  2228. $scale = 0;
  2229. $match = [];
  2230. if (!empty($options['LENGTH']) && preg_match('#^\(?(\d+),(\d+)\)?$#', $options['LENGTH'], $match)) {
  2231. $precision = $match[1];
  2232. $scale = $match[2];
  2233. } else {
  2234. if (isset($options['SCALE']) && is_numeric($options['SCALE'])) {
  2235. $scale = $options['SCALE'];
  2236. }
  2237. if (isset($options['PRECISION']) && is_numeric($options['PRECISION'])) {
  2238. $precision = $options['PRECISION'];
  2239. }
  2240. }
  2241. $cType .= sprintf('(%d,%d)', $precision, $scale);
  2242. if (!empty($options['UNSIGNED'])) {
  2243. $cUnsigned = true;
  2244. }
  2245. break;
  2246. case Table::TYPE_TEXT:
  2247. case Table::TYPE_BLOB:
  2248. case Table::TYPE_VARBINARY:
  2249. if (empty($options['LENGTH'])) {
  2250. $length = Table::DEFAULT_TEXT_SIZE;
  2251. } else {
  2252. $length = $this->_parseTextSize($options['LENGTH']);
  2253. }
  2254. if ($length <= 255) {
  2255. $cType = $ddlType == Table::TYPE_TEXT ? 'varchar' : 'varbinary';
  2256. $cType = sprintf('%s(%d)', $cType, $length);
  2257. } elseif ($length > 255 && $length <= 65536) {
  2258. $cType = $ddlType == Table::TYPE_TEXT ? 'text' : 'blob';
  2259. } elseif ($length > 65536 && $length <= 16777216) {
  2260. $cType = $ddlType == Table::TYPE_TEXT ? 'mediumtext' : 'mediumblob';
  2261. } else {
  2262. $cType = $ddlType == Table::TYPE_TEXT ? 'longtext' : 'longblob';
  2263. }
  2264. break;
  2265. }
  2266. if (array_key_exists('DEFAULT', $options)) {
  2267. $cDefault = $options['DEFAULT'];
  2268. }
  2269. if (array_key_exists('NULLABLE', $options)) {
  2270. $cNullable = (bool)$options['NULLABLE'];
  2271. }
  2272. if (!empty($options['IDENTITY']) || !empty($options['AUTO_INCREMENT'])) {
  2273. $cIdentity = true;
  2274. }
  2275. /* For cases when tables created from createTableByDdl()
  2276. * where default value can be quoted already.
  2277. * We need to avoid "double-quoting" here
  2278. */
  2279. if ($cDefault !== null && is_string($cDefault) && strlen($cDefault)) {
  2280. $cDefault = str_replace("'", '', $cDefault);
  2281. }
  2282. // prepare default value string
  2283. if ($ddlType == Table::TYPE_TIMESTAMP) {
  2284. if ($cDefault === null) {
  2285. $cDefault = new \Zend_Db_Expr('NULL');
  2286. } elseif ($cDefault == Table::TIMESTAMP_INIT) {
  2287. $cDefault = new \Zend_Db_Expr('CURRENT_TIMESTAMP');
  2288. } elseif ($cDefault == Table::TIMESTAMP_UPDATE) {
  2289. $cDefault = new \Zend_Db_Expr('0 ON UPDATE CURRENT_TIMESTAMP');
  2290. } elseif ($cDefault == Table::TIMESTAMP_INIT_UPDATE) {
  2291. $cDefault = new \Zend_Db_Expr('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
  2292. } elseif ($cNullable && !$cDefault) {
  2293. $cDefault = new \Zend_Db_Expr('NULL');
  2294. } else {
  2295. $cDefault = false;
  2296. }
  2297. } elseif ($cDefault === null && $cNullable) {
  2298. $cDefault = new \Zend_Db_Expr('NULL');
  2299. }
  2300. if (empty($options['COMMENT'])) {
  2301. $comment = '';
  2302. } else {
  2303. $comment = $options['COMMENT'];
  2304. }
  2305. //set column position
  2306. $after = null;
  2307. if (!empty($options['AFTER'])) {
  2308. $after = $options['AFTER'];
  2309. }
  2310. return sprintf(
  2311. '%s%s%s%s%s COMMENT %s %s',
  2312. $cType,
  2313. $cUnsigned ? ' UNSIGNED' : '',
  2314. $cNullable ? ' NULL' : ' NOT NULL',
  2315. $cDefault !== false ? $this->quoteInto(' default ?', $cDefault) : '',
  2316. $cIdentity ? ' auto_increment' : '',
  2317. $this->quote($comment),
  2318. $after ? 'AFTER ' . $this->quoteIdentifier($after) : ''
  2319. );
  2320. }
  2321. /**
  2322. * Drop table from database
  2323. *
  2324. * @param string $tableName
  2325. * @param string $schemaName
  2326. * @return true
  2327. */
  2328. public function dropTable($tableName, $schemaName = null)
  2329. {
  2330. $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
  2331. $query = 'DROP TABLE IF EXISTS ' . $table;
  2332. if ($this->getTransactionLevel() > 0) {
  2333. $this->createConnection()->query($query);
  2334. } else {
  2335. $this->query($query);
  2336. }
  2337. $this->resetDdlCache($tableName, $schemaName);
  2338. $this->getSchemaListener()->dropTable($tableName);
  2339. return true;
  2340. }
  2341. /**
  2342. * Drop temporary table from database
  2343. *
  2344. * @param string $tableName
  2345. * @param string $schemaName
  2346. * @return boolean
  2347. */
  2348. public function dropTemporaryTable($tableName, $schemaName = null)
  2349. {
  2350. $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
  2351. $query = 'DROP TEMPORARY TABLE IF EXISTS ' . $table;
  2352. $this->query($query);
  2353. return true;
  2354. }
  2355. /**
  2356. * Truncate a table
  2357. *
  2358. * @param string $tableName
  2359. * @param string $schemaName
  2360. * @return $this
  2361. * @throws \Zend_Db_Exception
  2362. */
  2363. public function truncateTable($tableName, $schemaName = null)
  2364. {
  2365. if (!$this->isTableExists($tableName, $schemaName)) {
  2366. throw new \Zend_Db_Exception(sprintf('Table "%s" does not exist', $tableName));
  2367. }
  2368. $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
  2369. $query = 'TRUNCATE TABLE ' . $table;
  2370. $this->query($query);
  2371. return $this;
  2372. }
  2373. /**
  2374. * Check is a table exists
  2375. *
  2376. * @param string $tableName
  2377. * @param string $schemaName
  2378. * @return bool
  2379. */
  2380. public function isTableExists($tableName, $schemaName = null)
  2381. {
  2382. return $this->showTableStatus($tableName, $schemaName) !== false;
  2383. }
  2384. /**
  2385. * Rename table
  2386. *
  2387. * @param string $oldTableName
  2388. * @param string $newTableName
  2389. * @param string $schemaName
  2390. * @return true
  2391. * @throws \Zend_Db_Exception
  2392. */
  2393. public function renameTable($oldTableName, $newTableName, $schemaName = null)
  2394. {
  2395. if (!$this->isTableExists($oldTableName, $schemaName)) {
  2396. throw new \Zend_Db_Exception(sprintf('Table "%s" does not exist', $oldTableName));
  2397. }
  2398. if ($this->isTableExists($newTableName, $schemaName)) {
  2399. throw new \Zend_Db_Exception(sprintf('Table "%s" already exists', $newTableName));
  2400. }
  2401. $this->getSchemaListener()->renameTable($oldTableName, $newTableName);
  2402. $oldTable = $this->_getTableName($oldTableName, $schemaName);
  2403. $newTable = $this->_getTableName($newTableName, $schemaName);
  2404. $query = sprintf('ALTER TABLE %s RENAME TO %s', $oldTable, $newTable);
  2405. if ($this->getTransactionLevel() > 0) {
  2406. $this->createConnection()->query($query);
  2407. } else {
  2408. $this->query($query);
  2409. }
  2410. $this->resetDdlCache($oldTableName, $schemaName);
  2411. return true;
  2412. }
  2413. /**
  2414. * Add new index to table name
  2415. *
  2416. * @param string $tableName
  2417. * @param string $indexName
  2418. * @param string|array $fields the table column name or array of ones
  2419. * @param string $indexType the index type
  2420. * @param string $schemaName
  2421. * @return \Zend_Db_Statement_Interface
  2422. * @throws \Zend_Db_Exception
  2423. * @throws \Exception
  2424. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  2425. * @SuppressWarnings(PHPMD.NPathComplexity)
  2426. */
  2427. public function addIndex(
  2428. $tableName,
  2429. $indexName,
  2430. $fields,
  2431. $indexType = AdapterInterface::INDEX_TYPE_INDEX,
  2432. $schemaName = null
  2433. ) {
  2434. $this->getSchemaListener()->addIndex(
  2435. $tableName,
  2436. $indexName,
  2437. $fields,
  2438. $indexType
  2439. );
  2440. $columns = $this->describeTable($tableName, $schemaName);
  2441. $keyList = $this->getIndexList($tableName, $schemaName);
  2442. $query = sprintf('ALTER TABLE %s', $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)));
  2443. if (isset($keyList[strtoupper($indexName)])) {
  2444. if ($keyList[strtoupper($indexName)]['INDEX_TYPE'] == AdapterInterface::INDEX_TYPE_PRIMARY) {
  2445. $query .= ' DROP PRIMARY KEY,';
  2446. } else {
  2447. $query .= sprintf(' DROP INDEX %s,', $this->quoteIdentifier($indexName));
  2448. }
  2449. }
  2450. if (!is_array($fields)) {
  2451. $fields = [$fields];
  2452. }
  2453. $fieldSql = [];
  2454. foreach ($fields as $field) {
  2455. if (!isset($columns[$field])) {
  2456. $msg = sprintf(
  2457. 'There is no field "%s" that you are trying to create an index on "%s"',
  2458. $field,
  2459. $tableName
  2460. );
  2461. throw new \Zend_Db_Exception($msg);
  2462. }
  2463. $fieldSql[] = $this->quoteIdentifier($field);
  2464. }
  2465. $fieldSql = implode(',', $fieldSql);
  2466. switch (strtolower($indexType)) {
  2467. case AdapterInterface::INDEX_TYPE_PRIMARY:
  2468. $condition = 'PRIMARY KEY';
  2469. break;
  2470. case AdapterInterface::INDEX_TYPE_UNIQUE:
  2471. $condition = 'UNIQUE ' . $this->quoteIdentifier($indexName);
  2472. break;
  2473. case AdapterInterface::INDEX_TYPE_FULLTEXT:
  2474. $condition = 'FULLTEXT ' . $this->quoteIdentifier($indexName);
  2475. break;
  2476. default:
  2477. $condition = 'INDEX ' . $this->quoteIdentifier($indexName);
  2478. break;
  2479. }
  2480. $query .= sprintf(' ADD %s (%s)', $condition, $fieldSql);
  2481. $cycle = true;
  2482. while ($cycle === true) {
  2483. try {
  2484. $result = $this->rawQuery($query);
  2485. $cycle = false;
  2486. } catch (\Exception $e) {
  2487. if (in_array(strtolower($indexType), ['primary', 'unique'])) {
  2488. $match = [];
  2489. if (preg_match('#SQLSTATE\[23000\]: [^:]+: 1062[^\']+\'([\d-\.]+)\'#', $e->getMessage(), $match)) {
  2490. $ids = explode('-', $match[1]);
  2491. $this->_removeDuplicateEntry($tableName, $fields, $ids);
  2492. continue;
  2493. }
  2494. }
  2495. throw $e;
  2496. }
  2497. }
  2498. $this->resetDdlCache($tableName, $schemaName);
  2499. return $result;
  2500. }
  2501. /**
  2502. * Drop the index from table
  2503. *
  2504. * @param string $tableName
  2505. * @param string $keyName
  2506. * @param string $schemaName
  2507. * @return true|\Zend_Db_Statement_Interface
  2508. */
  2509. public function dropIndex($tableName, $keyName, $schemaName = null)
  2510. {
  2511. $indexList = $this->getIndexList($tableName, $schemaName);
  2512. $indexType = 'index';
  2513. $keyName = strtoupper($keyName);
  2514. if (!isset($indexList[$keyName])) {
  2515. return true;
  2516. }
  2517. if ($keyName == 'PRIMARY') {
  2518. $indexType = 'primary';
  2519. $cond = 'DROP PRIMARY KEY';
  2520. } else {
  2521. if (strpos($keyName, 'UNQ_') !== false) {
  2522. $indexType = 'unique';
  2523. }
  2524. $cond = 'DROP KEY ' . $this->quoteIdentifier($indexList[$keyName]['KEY_NAME']);
  2525. }
  2526. $sql = sprintf(
  2527. 'ALTER TABLE %s %s',
  2528. $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
  2529. $cond
  2530. );
  2531. $this->getSchemaListener()->dropIndex($tableName, $keyName, $indexType);
  2532. $this->resetDdlCache($tableName, $schemaName);
  2533. return $this->rawQuery($sql);
  2534. }
  2535. /**
  2536. * Add new Foreign Key to table
  2537. *
  2538. * If Foreign Key with same name is exist - it will be deleted
  2539. *
  2540. * @param string $fkName
  2541. * @param string $tableName
  2542. * @param string $columnName
  2543. * @param string $refTableName
  2544. * @param string $refColumnName
  2545. * @param string $onDelete
  2546. * @param bool $purge trying remove invalid data
  2547. * @param string $schemaName
  2548. * @param string $refSchemaName
  2549. * @return \Zend_Db_Statement_Interface
  2550. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  2551. */
  2552. public function addForeignKey(
  2553. $fkName,
  2554. $tableName,
  2555. $columnName,
  2556. $refTableName,
  2557. $refColumnName,
  2558. $onDelete = AdapterInterface::FK_ACTION_CASCADE,
  2559. $purge = false,
  2560. $schemaName = null,
  2561. $refSchemaName = null
  2562. ) {
  2563. $this->dropForeignKey($tableName, $fkName, $schemaName);
  2564. if ($purge) {
  2565. $this->purgeOrphanRecords($tableName, $columnName, $refTableName, $refColumnName, $onDelete);
  2566. }
  2567. $query = sprintf(
  2568. 'ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)',
  2569. $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
  2570. $this->quoteIdentifier($fkName),
  2571. $this->quoteIdentifier($columnName),
  2572. $this->quoteIdentifier($this->_getTableName($refTableName, $refSchemaName)),
  2573. $this->quoteIdentifier($refColumnName)
  2574. );
  2575. if ($onDelete !== null) {
  2576. $query .= ' ON DELETE ' . strtoupper($onDelete);
  2577. }
  2578. $this->getSchemaListener()->addForeignKey(
  2579. $fkName,
  2580. $tableName,
  2581. $columnName,
  2582. $refTableName,
  2583. $refColumnName,
  2584. $onDelete
  2585. );
  2586. $result = $this->rawQuery($query);
  2587. $this->resetDdlCache($tableName);
  2588. return $result;
  2589. }
  2590. /**
  2591. * Format Date to internal database date format
  2592. *
  2593. * @param int|string|\DateTimeInterface $date
  2594. * @param bool $includeTime
  2595. * @return \Zend_Db_Expr
  2596. */
  2597. public function formatDate($date, $includeTime = true)
  2598. {
  2599. $date = $this->dateTime->formatDate($date, $includeTime);
  2600. if ($date === null) {
  2601. return new \Zend_Db_Expr('NULL');
  2602. }
  2603. return new \Zend_Db_Expr($this->quote($date));
  2604. }
  2605. /**
  2606. * Run additional environment before setup
  2607. *
  2608. * @return $this
  2609. */
  2610. public function startSetup()
  2611. {
  2612. $this->rawQuery("SET SQL_MODE=''");
  2613. $this->rawQuery("SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0");
  2614. $this->rawQuery("SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'");
  2615. return $this;
  2616. }
  2617. /**
  2618. * Run additional environment after setup
  2619. *
  2620. * @return $this
  2621. */
  2622. public function endSetup()
  2623. {
  2624. $this->rawQuery("SET SQL_MODE=IFNULL(@OLD_SQL_MODE,'')");
  2625. $this->rawQuery("SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS=0, 0, 1)");
  2626. return $this;
  2627. }
  2628. /**
  2629. * Build SQL statement for condition
  2630. *
  2631. * If $condition integer or string - exact value will be filtered ('eq' condition)
  2632. *
  2633. * If $condition is array is - one of the following structures is expected:
  2634. * - array("from" => $fromValue, "to" => $toValue)
  2635. * - array("eq" => $equalValue)
  2636. * - array("neq" => $notEqualValue)
  2637. * - array("like" => $likeValue)
  2638. * - array("in" => array($inValues))
  2639. * - array("nin" => array($notInValues))
  2640. * - array("notnull" => $valueIsNotNull)
  2641. * - array("null" => $valueIsNull)
  2642. * - array("gt" => $greaterValue)
  2643. * - array("lt" => $lessValue)
  2644. * - array("gteq" => $greaterOrEqualValue)
  2645. * - array("lteq" => $lessOrEqualValue)
  2646. * - array("finset" => $valueInSet)
  2647. * - array("nfinset" => $valueNotInSet)
  2648. * - array("regexp" => $regularExpression)
  2649. * - array("seq" => $stringValue)
  2650. * - array("sneq" => $stringValue)
  2651. *
  2652. * If non matched - sequential array is expected and OR conditions
  2653. * will be built using above mentioned structure
  2654. *
  2655. * @param string $fieldName
  2656. * @param integer|string|array $condition
  2657. * @return string
  2658. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  2659. */
  2660. public function prepareSqlCondition($fieldName, $condition)
  2661. {
  2662. $conditionKeyMap = [
  2663. 'eq' => "{{fieldName}} = ?",
  2664. 'neq' => "{{fieldName}} != ?",
  2665. 'like' => "{{fieldName}} LIKE ?",
  2666. 'nlike' => "{{fieldName}} NOT LIKE ?",
  2667. 'in' => "{{fieldName}} IN(?)",
  2668. 'nin' => "{{fieldName}} NOT IN(?)",
  2669. 'is' => "{{fieldName}} IS ?",
  2670. 'notnull' => "{{fieldName}} IS NOT NULL",
  2671. 'null' => "{{fieldName}} IS NULL",
  2672. 'gt' => "{{fieldName}} > ?",
  2673. 'lt' => "{{fieldName}} < ?",
  2674. 'gteq' => "{{fieldName}} >= ?",
  2675. 'lteq' => "{{fieldName}} <= ?",
  2676. 'finset' => "FIND_IN_SET(?, {{fieldName}})",
  2677. 'nfinset' => "NOT FIND_IN_SET(?, {{fieldName}})",
  2678. 'regexp' => "{{fieldName}} REGEXP ?",
  2679. 'from' => "{{fieldName}} >= ?",
  2680. 'to' => "{{fieldName}} <= ?",
  2681. 'seq' => null,
  2682. 'sneq' => null,
  2683. 'ntoa' => "INET_NTOA({{fieldName}}) LIKE ?",
  2684. ];
  2685. $query = '';
  2686. if (is_array($condition)) {
  2687. $key = key(array_intersect_key($condition, $conditionKeyMap));
  2688. if (isset($condition['from']) || isset($condition['to'])) {
  2689. if (isset($condition['from'])) {
  2690. $from = $this->_prepareSqlDateCondition($condition, 'from');
  2691. $query = $this->_prepareQuotedSqlCondition($conditionKeyMap['from'], $from, $fieldName);
  2692. }
  2693. if (isset($condition['to'])) {
  2694. $query .= empty($query) ? '' : ' AND ';
  2695. $to = $this->_prepareSqlDateCondition($condition, 'to');
  2696. $query = $query . $this->_prepareQuotedSqlCondition($conditionKeyMap['to'], $to, $fieldName);
  2697. }
  2698. } elseif (array_key_exists($key, $conditionKeyMap)) {
  2699. $value = $condition[$key];
  2700. if (($key == 'seq') || ($key == 'sneq')) {
  2701. $key = $this->_transformStringSqlCondition($key, $value);
  2702. }
  2703. if (($key == 'in' || $key == 'nin') && is_string($value)) {
  2704. $value = explode(',', $value);
  2705. }
  2706. $query = $this->_prepareQuotedSqlCondition($conditionKeyMap[$key], $value, $fieldName);
  2707. } else {
  2708. $queries = [];
  2709. foreach ($condition as $orCondition) {
  2710. $queries[] = sprintf('(%s)', $this->prepareSqlCondition($fieldName, $orCondition));
  2711. }
  2712. $query = sprintf('(%s)', implode(' OR ', $queries));
  2713. }
  2714. } else {
  2715. $query = $this->_prepareQuotedSqlCondition($conditionKeyMap['eq'], (string)$condition, $fieldName);
  2716. }
  2717. return $query;
  2718. }
  2719. /**
  2720. * Prepare Sql condition
  2721. *
  2722. * @param string $text Condition value
  2723. * @param mixed $value
  2724. * @param string $fieldName
  2725. * @return string
  2726. */
  2727. protected function _prepareQuotedSqlCondition($text, $value, $fieldName)
  2728. {
  2729. $sql = $this->quoteInto($text, $value);
  2730. $sql = str_replace('{{fieldName}}', $fieldName, $sql);
  2731. return $sql;
  2732. }
  2733. /**
  2734. * Transforms sql condition key 'seq' / 'sneq' that is used for comparing string values to its analog:
  2735. * - 'null' / 'notnull' for empty strings
  2736. * - 'eq' / 'neq' for non-empty strings
  2737. *
  2738. * @param string $conditionKey
  2739. * @param mixed $value
  2740. * @return string
  2741. */
  2742. protected function _transformStringSqlCondition($conditionKey, $value)
  2743. {
  2744. $value = (string) $value;
  2745. if ($value == '') {
  2746. return ($conditionKey == 'seq') ? 'null' : 'notnull';
  2747. } else {
  2748. return ($conditionKey == 'seq') ? 'eq' : 'neq';
  2749. }
  2750. }
  2751. /**
  2752. * Prepare value for save in column
  2753. *
  2754. * Return converted to column data type value
  2755. *
  2756. * @param array $column the column describe array
  2757. * @param mixed $value
  2758. * @return mixed
  2759. *
  2760. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  2761. * @SuppressWarnings(PHPMD.NPathComplexity)
  2762. */
  2763. public function prepareColumnValue(array $column, $value)
  2764. {
  2765. if ($value instanceof \Zend_Db_Expr) {
  2766. return $value;
  2767. }
  2768. if ($value instanceof Parameter) {
  2769. return $value;
  2770. }
  2771. // return original value if invalid column describe data
  2772. if (!isset($column['DATA_TYPE'])) {
  2773. return $value;
  2774. }
  2775. // return null
  2776. if ($value === null && $column['NULLABLE']) {
  2777. return null;
  2778. }
  2779. switch ($column['DATA_TYPE']) {
  2780. case 'smallint':
  2781. case 'int':
  2782. $value = (int)$value;
  2783. break;
  2784. case 'bigint':
  2785. if (!is_integer($value)) {
  2786. $value = sprintf('%.0f', (float)$value);
  2787. }
  2788. break;
  2789. case 'decimal':
  2790. $precision = 10;
  2791. $scale = 0;
  2792. if (isset($column['SCALE'])) {
  2793. $scale = $column['SCALE'];
  2794. }
  2795. if (isset($column['PRECISION'])) {
  2796. $precision = $column['PRECISION'];
  2797. }
  2798. $format = sprintf('%%%d.%dF', $precision - $scale, $scale);
  2799. $value = (float)sprintf($format, $value);
  2800. break;
  2801. case 'float':
  2802. $value = (float)sprintf('%F', $value);
  2803. break;
  2804. case 'date':
  2805. $value = $this->formatDate($value, false);
  2806. break;
  2807. case 'datetime':
  2808. case 'timestamp':
  2809. $value = $this->formatDate($value);
  2810. break;
  2811. case 'varchar':
  2812. case 'mediumtext':
  2813. case 'text':
  2814. case 'longtext':
  2815. $value = (string)$value;
  2816. if ($column['NULLABLE'] && $value == '') {
  2817. $value = null;
  2818. }
  2819. break;
  2820. case 'varbinary':
  2821. case 'mediumblob':
  2822. case 'blob':
  2823. case 'longblob':
  2824. // No special processing for MySQL is needed
  2825. break;
  2826. }
  2827. return $value;
  2828. }
  2829. /**
  2830. * Generate fragment of SQL, that check condition and return true or false value
  2831. *
  2832. * @param \Zend_Db_Expr|\Magento\Framework\DB\Select|string $expression
  2833. * @param string $true true value
  2834. * @param string $false false value
  2835. * @return \Zend_Db_Expr
  2836. */
  2837. public function getCheckSql($expression, $true, $false)
  2838. {
  2839. if ($expression instanceof \Zend_Db_Expr || $expression instanceof \Zend_Db_Select) {
  2840. $expression = sprintf("IF((%s), %s, %s)", $expression, $true, $false);
  2841. } else {
  2842. $expression = sprintf("IF(%s, %s, %s)", $expression, $true, $false);
  2843. }
  2844. return new \Zend_Db_Expr($expression);
  2845. }
  2846. /**
  2847. * Returns valid IFNULL expression
  2848. *
  2849. * @param \Zend_Db_Expr|\Magento\Framework\DB\Select|string $expression
  2850. * @param string|int $value OPTIONAL. Applies when $expression is NULL
  2851. * @return \Zend_Db_Expr
  2852. */
  2853. public function getIfNullSql($expression, $value = 0)
  2854. {
  2855. if ($expression instanceof \Zend_Db_Expr || $expression instanceof \Zend_Db_Select) {
  2856. $expression = sprintf("IFNULL((%s), %s)", $expression, $value);
  2857. } else {
  2858. $expression = sprintf("IFNULL(%s, %s)", $expression, $value);
  2859. }
  2860. return new \Zend_Db_Expr($expression);
  2861. }
  2862. /**
  2863. * Generates case SQL fragment
  2864. *
  2865. * Generate fragment of SQL, that check value against multiple condition cases
  2866. * and return different result depends on them
  2867. *
  2868. * @param string $valueName Name of value to check
  2869. * @param array $casesResults Cases and results
  2870. * @param string $defaultValue value to use if value doesn't confirm to any cases
  2871. * @return \Zend_Db_Expr
  2872. */
  2873. public function getCaseSql($valueName, $casesResults, $defaultValue = null)
  2874. {
  2875. $expression = 'CASE ' . $valueName;
  2876. foreach ($casesResults as $case => $result) {
  2877. $expression .= ' WHEN ' . $case . ' THEN ' . $result;
  2878. }
  2879. if ($defaultValue !== null) {
  2880. $expression .= ' ELSE ' . $defaultValue;
  2881. }
  2882. $expression .= ' END';
  2883. return new \Zend_Db_Expr($expression);
  2884. }
  2885. /**
  2886. * Generate fragment of SQL, that combine together (concatenate) the results from data array
  2887. *
  2888. * All arguments in data must be quoted
  2889. *
  2890. * @param string[] $data
  2891. * @param string $separator concatenate with separator
  2892. * @return \Zend_Db_Expr
  2893. */
  2894. public function getConcatSql(array $data, $separator = null)
  2895. {
  2896. $format = empty($separator) ? 'CONCAT(%s)' : "CONCAT_WS('{$separator}', %s)";
  2897. return new \Zend_Db_Expr(sprintf($format, implode(', ', $data)));
  2898. }
  2899. /**
  2900. * Generate fragment of SQL that returns length of character string
  2901. *
  2902. * The string argument must be quoted
  2903. *
  2904. * @param string $string
  2905. * @return \Zend_Db_Expr
  2906. */
  2907. public function getLengthSql($string)
  2908. {
  2909. return new \Zend_Db_Expr(sprintf('LENGTH(%s)', $string));
  2910. }
  2911. /**
  2912. * Generate least SQL fragment
  2913. *
  2914. * Generate fragment of SQL, that compare with two or more arguments, and returns the smallest
  2915. * (minimum-valued) argument
  2916. * All arguments in data must be quoted
  2917. *
  2918. * @param string[] $data
  2919. * @return \Zend_Db_Expr
  2920. */
  2921. public function getLeastSql(array $data)
  2922. {
  2923. return new \Zend_Db_Expr(sprintf('LEAST(%s)', implode(', ', $data)));
  2924. }
  2925. /**
  2926. * Generate greatest SQL fragment
  2927. *
  2928. * Generate fragment of SQL, that compare with two or more arguments, and returns the largest
  2929. * (maximum-valued) argument
  2930. * All arguments in data must be quoted
  2931. *
  2932. * @param string[] $data
  2933. * @return \Zend_Db_Expr
  2934. */
  2935. public function getGreatestSql(array $data)
  2936. {
  2937. return new \Zend_Db_Expr(sprintf('GREATEST(%s)', implode(', ', $data)));
  2938. }
  2939. /**
  2940. * Get Interval Unit SQL fragment
  2941. *
  2942. * @param int $interval
  2943. * @param string $unit
  2944. * @return string
  2945. * @throws \Zend_Db_Exception
  2946. */
  2947. protected function _getIntervalUnitSql($interval, $unit)
  2948. {
  2949. if (!isset($this->_intervalUnits[$unit])) {
  2950. throw new \Zend_Db_Exception(sprintf('Undefined interval unit "%s" specified', $unit));
  2951. }
  2952. return sprintf('INTERVAL %d %s', $interval, $this->_intervalUnits[$unit]);
  2953. }
  2954. /**
  2955. * Add time values (intervals) to a date value
  2956. *
  2957. * @see INTERVAL_* constants for $unit
  2958. *
  2959. * @param \Zend_Db_Expr|string $date quoted field name or SQL statement
  2960. * @param int $interval
  2961. * @param string $unit
  2962. * @return \Zend_Db_Expr
  2963. */
  2964. public function getDateAddSql($date, $interval, $unit)
  2965. {
  2966. $expr = sprintf('DATE_ADD(%s, %s)', $date, $this->_getIntervalUnitSql($interval, $unit));
  2967. return new \Zend_Db_Expr($expr);
  2968. }
  2969. /**
  2970. * Subtract time values (intervals) to a date value
  2971. *
  2972. * @see INTERVAL_* constants for $expr
  2973. *
  2974. * @param \Zend_Db_Expr|string $date quoted field name or SQL statement
  2975. * @param int|string $interval
  2976. * @param string $unit
  2977. * @return \Zend_Db_Expr
  2978. */
  2979. public function getDateSubSql($date, $interval, $unit)
  2980. {
  2981. $expr = sprintf('DATE_SUB(%s, %s)', $date, $this->_getIntervalUnitSql($interval, $unit));
  2982. return new \Zend_Db_Expr($expr);
  2983. }
  2984. /**
  2985. * Format date as specified
  2986. *
  2987. * Supported format Specifier
  2988. *
  2989. * %H Hour (00..23)
  2990. * %i Minutes, numeric (00..59)
  2991. * %s Seconds (00..59)
  2992. * %d Day of the month, numeric (00..31)
  2993. * %m Month, numeric (00..12)
  2994. * %Y Year, numeric, four digits
  2995. *
  2996. * @param string $date quoted date value or non quoted SQL statement(field)
  2997. * @param string $format
  2998. * @return \Zend_Db_Expr
  2999. */
  3000. public function getDateFormatSql($date, $format)
  3001. {
  3002. $expr = sprintf("DATE_FORMAT(%s, '%s')", $date, $format);
  3003. return new \Zend_Db_Expr($expr);
  3004. }
  3005. /**
  3006. * Extract the date part of a date or datetime expression
  3007. *
  3008. * @param \Zend_Db_Expr|string $date quoted field name or SQL statement
  3009. * @return \Zend_Db_Expr
  3010. */
  3011. public function getDatePartSql($date)
  3012. {
  3013. return new \Zend_Db_Expr(sprintf('DATE(%s)', $date));
  3014. }
  3015. /**
  3016. * Prepare substring sql function
  3017. *
  3018. * @param \Zend_Db_Expr|string $stringExpression quoted field name or SQL statement
  3019. * @param int|string|\Zend_Db_Expr $pos
  3020. * @param int|string|\Zend_Db_Expr|null $len
  3021. * @return \Zend_Db_Expr
  3022. */
  3023. public function getSubstringSql($stringExpression, $pos, $len = null)
  3024. {
  3025. if ($len === null) {
  3026. return new \Zend_Db_Expr(sprintf('SUBSTRING(%s, %s)', $stringExpression, $pos));
  3027. }
  3028. return new \Zend_Db_Expr(sprintf('SUBSTRING(%s, %s, %s)', $stringExpression, $pos, $len));
  3029. }
  3030. /**
  3031. * Prepare standard deviation sql function
  3032. *
  3033. * @param \Zend_Db_Expr|string $expressionField quoted field name or SQL statement
  3034. * @return \Zend_Db_Expr
  3035. */
  3036. public function getStandardDeviationSql($expressionField)
  3037. {
  3038. return new \Zend_Db_Expr(sprintf('STDDEV_SAMP(%s)', $expressionField));
  3039. }
  3040. /**
  3041. * Extract part of a date
  3042. *
  3043. * @see INTERVAL_* constants for $unit
  3044. *
  3045. * @param \Zend_Db_Expr|string $date quoted field name or SQL statement
  3046. * @param string $unit
  3047. * @return \Zend_Db_Expr
  3048. * @throws \Zend_Db_Exception
  3049. */
  3050. public function getDateExtractSql($date, $unit)
  3051. {
  3052. if (!isset($this->_intervalUnits[$unit])) {
  3053. throw new \Zend_Db_Exception(sprintf('Undefined interval unit "%s" specified', $unit));
  3054. }
  3055. $expr = sprintf('EXTRACT(%s FROM %s)', $this->_intervalUnits[$unit], $date);
  3056. return new \Zend_Db_Expr($expr);
  3057. }
  3058. /**
  3059. * Returns a compressed version of the table name if it is too long
  3060. *
  3061. * @param string $tableName
  3062. * @return string
  3063. * @codeCoverageIgnore
  3064. */
  3065. public function getTableName($tableName)
  3066. {
  3067. return ExpressionConverter::shortenEntityName($tableName, 't_');
  3068. }
  3069. /**
  3070. * Build a trigger name based on table name and trigger details
  3071. *
  3072. * @param string $tableName The table which is the subject of the trigger
  3073. * @param string $time Either "before" or "after"
  3074. * @param string $event The DB level event which activates the trigger, i.e. "update" or "insert"
  3075. * @return string
  3076. * @codeCoverageIgnore
  3077. */
  3078. public function getTriggerName($tableName, $time, $event)
  3079. {
  3080. $triggerName = 'trg_' . $tableName . '_' . $time . '_' . $event;
  3081. return ExpressionConverter::shortenEntityName($triggerName, 'trg_');
  3082. }
  3083. /**
  3084. * Retrieve valid index name
  3085. *
  3086. * Check index name length and allowed symbols
  3087. *
  3088. * @param string $tableName
  3089. * @param string|string[] $fields the columns list
  3090. * @param string $indexType
  3091. * @return string
  3092. */
  3093. public function getIndexName($tableName, $fields, $indexType = '')
  3094. {
  3095. if (is_array($fields)) {
  3096. $fields = implode('_', $fields);
  3097. }
  3098. switch (strtolower($indexType)) {
  3099. case AdapterInterface::INDEX_TYPE_UNIQUE:
  3100. $prefix = 'unq_';
  3101. break;
  3102. case AdapterInterface::INDEX_TYPE_FULLTEXT:
  3103. $prefix = 'fti_';
  3104. break;
  3105. case AdapterInterface::INDEX_TYPE_INDEX:
  3106. default:
  3107. $prefix = 'idx_';
  3108. }
  3109. return strtoupper(ExpressionConverter::shortenEntityName($tableName . '_' . $fields, $prefix));
  3110. }
  3111. /**
  3112. * Retrieve valid foreign key name
  3113. *
  3114. * Check foreign key name length and allowed symbols
  3115. *
  3116. * @param string $priTableName
  3117. * @param string $priColumnName
  3118. * @param string $refTableName
  3119. * @param string $refColumnName
  3120. * @return string
  3121. * @codeCoverageIgnore
  3122. */
  3123. public function getForeignKeyName($priTableName, $priColumnName, $refTableName, $refColumnName)
  3124. {
  3125. $fkName = sprintf('%s_%s_%s_%s', $priTableName, $priColumnName, $refTableName, $refColumnName);
  3126. return strtoupper(ExpressionConverter::shortenEntityName($fkName, 'fk_'));
  3127. }
  3128. /**
  3129. * Stop updating indexes
  3130. *
  3131. * @param string $tableName
  3132. * @param string $schemaName
  3133. * @return $this
  3134. */
  3135. public function disableTableKeys($tableName, $schemaName = null)
  3136. {
  3137. $tableName = $this->_getTableName($tableName, $schemaName);
  3138. $query = sprintf('ALTER TABLE %s DISABLE KEYS', $this->quoteIdentifier($tableName));
  3139. $this->query($query);
  3140. return $this;
  3141. }
  3142. /**
  3143. * Re-create missing indexes
  3144. *
  3145. * @param string $tableName
  3146. * @param string $schemaName
  3147. * @return $this
  3148. */
  3149. public function enableTableKeys($tableName, $schemaName = null)
  3150. {
  3151. $tableName = $this->_getTableName($tableName, $schemaName);
  3152. $query = sprintf('ALTER TABLE %s ENABLE KEYS', $this->quoteIdentifier($tableName));
  3153. $this->query($query);
  3154. return $this;
  3155. }
  3156. /**
  3157. * Get insert from Select object query
  3158. *
  3159. * @param Select $select
  3160. * @param string $table insert into table
  3161. * @param array $fields
  3162. * @param int|false $mode
  3163. * @return string
  3164. */
  3165. public function insertFromSelect(Select $select, $table, array $fields = [], $mode = false)
  3166. {
  3167. $query = $mode === self::REPLACE ? 'REPLACE' : 'INSERT';
  3168. if ($mode === self::INSERT_IGNORE) {
  3169. $query .= ' IGNORE';
  3170. }
  3171. $query = sprintf('%s INTO %s', $query, $this->quoteIdentifier($table));
  3172. if ($fields) {
  3173. $columns = array_map([$this, 'quoteIdentifier'], $fields);
  3174. $query = sprintf('%s (%s)', $query, join(', ', $columns));
  3175. }
  3176. $query = sprintf('%s %s', $query, $select->assemble());
  3177. if ($mode === self::INSERT_ON_DUPLICATE) {
  3178. $query .= $this->renderOnDuplicate($table, $fields);
  3179. }
  3180. return $query;
  3181. }
  3182. /**
  3183. * Render On Duplicate query part
  3184. *
  3185. * @param string $table
  3186. * @param array $fields
  3187. * @return string
  3188. */
  3189. private function renderOnDuplicate($table, array $fields)
  3190. {
  3191. if (!$fields) {
  3192. $describe = $this->describeTable($table);
  3193. foreach ($describe as $column) {
  3194. if ($column['PRIMARY'] === false) {
  3195. $fields[] = $column['COLUMN_NAME'];
  3196. }
  3197. }
  3198. }
  3199. $update = [];
  3200. foreach ($fields as $field) {
  3201. $update[] = sprintf('%1$s = VALUES(%1$s)', $this->quoteIdentifier($field));
  3202. }
  3203. return count($update) ? ' ON DUPLICATE KEY UPDATE ' . join(', ', $update) : '';
  3204. }
  3205. /**
  3206. * Get insert queries in array for insert by range with step parameter
  3207. *
  3208. * @param string $rangeField
  3209. * @param \Magento\Framework\DB\Select $select
  3210. * @param int $stepCount
  3211. * @return \Magento\Framework\DB\Select[]
  3212. * @throws LocalizedException
  3213. * @deprecated 100.1.3
  3214. */
  3215. public function selectsByRange($rangeField, \Magento\Framework\DB\Select $select, $stepCount = 100)
  3216. {
  3217. $iterator = $this->getQueryGenerator()->generate($rangeField, $select, $stepCount);
  3218. $queries = [];
  3219. foreach ($iterator as $query) {
  3220. $queries[] = $query;
  3221. }
  3222. return $queries;
  3223. }
  3224. /**
  3225. * Get query generator
  3226. *
  3227. * @return QueryGenerator
  3228. * @deprecated 100.1.3
  3229. */
  3230. private function getQueryGenerator()
  3231. {
  3232. if ($this->queryGenerator === null) {
  3233. $this->queryGenerator = \Magento\Framework\App\ObjectManager::getInstance()->create(QueryGenerator::class);
  3234. }
  3235. return $this->queryGenerator;
  3236. }
  3237. /**
  3238. * Get update table query using select object for join and update
  3239. *
  3240. * @param Select $select
  3241. * @param string|array $table
  3242. * @return string
  3243. * @throws LocalizedException
  3244. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  3245. * @SuppressWarnings(PHPMD.NPathComplexity)
  3246. */
  3247. public function updateFromSelect(Select $select, $table)
  3248. {
  3249. if (!is_array($table)) {
  3250. $table = [$table => $table];
  3251. }
  3252. // get table name and alias
  3253. $keys = array_keys($table);
  3254. $tableAlias = $keys[0];
  3255. $tableName = $table[$keys[0]];
  3256. $query = sprintf('UPDATE %s', $this->quoteTableAs($tableName, $tableAlias));
  3257. // render JOIN conditions (FROM Part)
  3258. $joinConds = [];
  3259. foreach ($select->getPart(\Magento\Framework\DB\Select::FROM) as $correlationName => $joinProp) {
  3260. if ($joinProp['joinType'] == \Magento\Framework\DB\Select::FROM) {
  3261. $joinType = strtoupper(\Magento\Framework\DB\Select::INNER_JOIN);
  3262. } else {
  3263. $joinType = strtoupper($joinProp['joinType']);
  3264. }
  3265. $joinTable = '';
  3266. if ($joinProp['schema'] !== null) {
  3267. $joinTable = sprintf('%s.', $this->quoteIdentifier($joinProp['schema']));
  3268. }
  3269. $joinTable .= $this->quoteTableAs($joinProp['tableName'], $correlationName);
  3270. $join = sprintf(' %s %s', $joinType, $joinTable);
  3271. if (!empty($joinProp['joinCondition'])) {
  3272. $join = sprintf('%s ON %s', $join, $joinProp['joinCondition']);
  3273. }
  3274. $joinConds[] = $join;
  3275. }
  3276. if ($joinConds) {
  3277. $query = sprintf("%s\n%s", $query, implode("\n", $joinConds));
  3278. }
  3279. // render UPDATE SET
  3280. $columns = [];
  3281. foreach ($select->getPart(\Magento\Framework\DB\Select::COLUMNS) as $columnEntry) {
  3282. list($correlationName, $column, $alias) = $columnEntry;
  3283. if (empty($alias)) {
  3284. $alias = $column;
  3285. }
  3286. if (!$column instanceof \Zend_Db_Expr && !empty($correlationName)) {
  3287. $column = $this->quoteIdentifier([$correlationName, $column]);
  3288. }
  3289. $columns[] = sprintf('%s = %s', $this->quoteIdentifier([$tableAlias, $alias]), $column);
  3290. }
  3291. if (!$columns) {
  3292. throw new LocalizedException(
  3293. new \Magento\Framework\Phrase('The columns for UPDATE statement are not defined')
  3294. );
  3295. }
  3296. $query = sprintf("%s\nSET %s", $query, implode(', ', $columns));
  3297. // render WHERE
  3298. $wherePart = $select->getPart(\Magento\Framework\DB\Select::WHERE);
  3299. if ($wherePart) {
  3300. $query = sprintf("%s\nWHERE %s", $query, implode(' ', $wherePart));
  3301. }
  3302. return $query;
  3303. }
  3304. /**
  3305. * Get delete from select object query
  3306. *
  3307. * @param Select $select
  3308. * @param string $table the table name or alias used in select
  3309. * @return string
  3310. */
  3311. public function deleteFromSelect(Select $select, $table)
  3312. {
  3313. $select = clone $select;
  3314. $select->reset(\Magento\Framework\DB\Select::DISTINCT);
  3315. $select->reset(\Magento\Framework\DB\Select::COLUMNS);
  3316. $query = sprintf('DELETE %s %s', $this->quoteIdentifier($table), $select->assemble());
  3317. return $query;
  3318. }
  3319. /**
  3320. * Calculate checksum for table or for group of tables
  3321. *
  3322. * @param array|string $tableNames array of tables names | table name
  3323. * @param string $schemaName schema name
  3324. * @return array
  3325. */
  3326. public function getTablesChecksum($tableNames, $schemaName = null)
  3327. {
  3328. $result = [];
  3329. $tableNames = is_array($tableNames) ? $tableNames : [$tableNames];
  3330. foreach ($tableNames as $tableName) {
  3331. $query = 'CHECKSUM TABLE ' . $this->_getTableName($tableName, $schemaName);
  3332. $checkSumArray = $this->fetchRow($query);
  3333. $result[$tableName] = $checkSumArray['Checksum'];
  3334. }
  3335. return $result;
  3336. }
  3337. /**
  3338. * Check if the database support STRAIGHT JOIN
  3339. *
  3340. * @return true
  3341. */
  3342. public function supportStraightJoin()
  3343. {
  3344. return true;
  3345. }
  3346. /**
  3347. * Adds order by random to select object
  3348. *
  3349. * Possible using integer field for optimization
  3350. *
  3351. * @param Select $select
  3352. * @param string $field
  3353. * @return $this
  3354. */
  3355. public function orderRand(Select $select, $field = null)
  3356. {
  3357. if ($field !== null) {
  3358. $expression = new \Zend_Db_Expr(sprintf('RAND() * %s', $this->quoteIdentifier($field)));
  3359. $select->columns(['mage_rand' => $expression]);
  3360. $spec = new \Zend_Db_Expr('mage_rand');
  3361. } else {
  3362. $spec = new \Zend_Db_Expr('RAND()');
  3363. }
  3364. $select->order($spec);
  3365. return $this;
  3366. }
  3367. /**
  3368. * Render SQL FOR UPDATE clause
  3369. *
  3370. * @param string $sql
  3371. * @return string
  3372. */
  3373. public function forUpdate($sql)
  3374. {
  3375. return sprintf('%s FOR UPDATE', $sql);
  3376. }
  3377. /**
  3378. * Prepare insert data
  3379. *
  3380. * @param mixed $row
  3381. * @param array $bind
  3382. * @return string
  3383. */
  3384. protected function _prepareInsertData($row, &$bind)
  3385. {
  3386. $row = (array)$row;
  3387. $line = [];
  3388. foreach ($row as $value) {
  3389. if ($value instanceof \Zend_Db_Expr) {
  3390. $line[] = $value->__toString();
  3391. } else {
  3392. $line[] = '?';
  3393. $bind[] = $value;
  3394. }
  3395. }
  3396. $line = implode(', ', $line);
  3397. return sprintf('(%s)', $line);
  3398. }
  3399. /**
  3400. * Return insert sql query
  3401. *
  3402. * @param string $tableName
  3403. * @param array $columns
  3404. * @param array $values
  3405. * @param null|int $strategy
  3406. * @return string
  3407. */
  3408. protected function _getInsertSqlQuery($tableName, array $columns, array $values, $strategy = null)
  3409. {
  3410. $tableName = $this->quoteIdentifier($tableName, true);
  3411. $columns = array_map([$this, 'quoteIdentifier'], $columns);
  3412. $columns = implode(',', $columns);
  3413. $values = implode(', ', $values);
  3414. $strategy = $strategy === self::INSERT_IGNORE ? 'IGNORE' : '';
  3415. $insertSql = sprintf('INSERT %s INTO %s (%s) VALUES %s', $strategy, $tableName, $columns, $values);
  3416. return $insertSql;
  3417. }
  3418. /**
  3419. * Return replace sql query
  3420. *
  3421. * @param string $tableName
  3422. * @param array $columns
  3423. * @param array $values
  3424. * @return string
  3425. * @since 101.0.0
  3426. */
  3427. protected function _getReplaceSqlQuery($tableName, array $columns, array $values)
  3428. {
  3429. $tableName = $this->quoteIdentifier($tableName, true);
  3430. $columns = array_map([$this, 'quoteIdentifier'], $columns);
  3431. $columns = implode(',', $columns);
  3432. $values = implode(', ', $values);
  3433. $replaceSql = sprintf('REPLACE INTO %s (%s) VALUES %s', $tableName, $columns, $values);
  3434. return $replaceSql;
  3435. }
  3436. /**
  3437. * Return ddl type
  3438. *
  3439. * @param array $options
  3440. * @return string
  3441. */
  3442. protected function _getDdlType($options)
  3443. {
  3444. $ddlType = null;
  3445. if (isset($options['TYPE'])) {
  3446. $ddlType = $options['TYPE'];
  3447. } elseif (isset($options['COLUMN_TYPE'])) {
  3448. $ddlType = $options['COLUMN_TYPE'];
  3449. }
  3450. return $ddlType;
  3451. }
  3452. /**
  3453. * Return DDL action
  3454. *
  3455. * @param string $action
  3456. * @return string
  3457. */
  3458. protected function _getDdlAction($action)
  3459. {
  3460. switch ($action) {
  3461. case AdapterInterface::FK_ACTION_CASCADE:
  3462. return Table::ACTION_CASCADE;
  3463. case AdapterInterface::FK_ACTION_SET_NULL:
  3464. return Table::ACTION_SET_NULL;
  3465. case AdapterInterface::FK_ACTION_RESTRICT:
  3466. return Table::ACTION_RESTRICT;
  3467. default:
  3468. return Table::ACTION_NO_ACTION;
  3469. }
  3470. }
  3471. /**
  3472. * Prepare sql date condition
  3473. *
  3474. * @param array $condition
  3475. * @param string $key
  3476. * @return string
  3477. */
  3478. protected function _prepareSqlDateCondition($condition, $key)
  3479. {
  3480. if (empty($condition['date'])) {
  3481. if (empty($condition['datetime'])) {
  3482. $result = $condition[$key];
  3483. } else {
  3484. $result = $this->formatDate($condition[$key]);
  3485. }
  3486. } else {
  3487. $result = $this->formatDate($condition[$key]);
  3488. }
  3489. return $result;
  3490. }
  3491. /**
  3492. * Try to find installed primary key name, if not - formate new one.
  3493. *
  3494. * @param string $tableName Table name
  3495. * @param string $schemaName OPTIONAL
  3496. * @return string Primary Key name
  3497. */
  3498. public function getPrimaryKeyName($tableName, $schemaName = null)
  3499. {
  3500. $indexes = $this->getIndexList($tableName, $schemaName);
  3501. if (isset($indexes['PRIMARY'])) {
  3502. return $indexes['PRIMARY']['KEY_NAME'];
  3503. } else {
  3504. return 'PK_' . strtoupper($tableName);
  3505. }
  3506. }
  3507. /**
  3508. * Parse text size
  3509. *
  3510. * Returns max allowed size if value great it
  3511. *
  3512. * @param string|int $size
  3513. * @return int
  3514. */
  3515. protected function _parseTextSize($size)
  3516. {
  3517. $size = trim($size);
  3518. $last = strtolower(substr($size, -1));
  3519. switch ($last) {
  3520. case 'k':
  3521. $size = (int)$size * 1024;
  3522. break;
  3523. case 'm':
  3524. $size = (int)$size * 1024 * 1024;
  3525. break;
  3526. case 'g':
  3527. $size = (int)$size * 1024 * 1024 * 1024;
  3528. break;
  3529. }
  3530. if (empty($size)) {
  3531. return Table::DEFAULT_TEXT_SIZE;
  3532. }
  3533. if ($size >= Table::MAX_TEXT_SIZE) {
  3534. return Table::MAX_TEXT_SIZE;
  3535. }
  3536. return (int)$size;
  3537. }
  3538. /**
  3539. * Converts fetched blob into raw binary PHP data.
  3540. *
  3541. * The MySQL drivers do it nice, no processing required.
  3542. *
  3543. * @param mixed $value
  3544. * @return mixed
  3545. */
  3546. public function decodeVarbinary($value)
  3547. {
  3548. return $value;
  3549. }
  3550. /**
  3551. * Create trigger
  3552. *
  3553. * @param \Magento\Framework\DB\Ddl\Trigger $trigger
  3554. * @throws \Zend_Db_Exception
  3555. * @return \Zend_Db_Statement_Pdo
  3556. */
  3557. public function createTrigger(\Magento\Framework\DB\Ddl\Trigger $trigger)
  3558. {
  3559. if (!$trigger->getStatements()) {
  3560. throw new \Zend_Db_Exception(
  3561. (string)new \Magento\Framework\Phrase(
  3562. 'Trigger %1 has not statements available',
  3563. [$trigger->getName()]
  3564. )
  3565. );
  3566. }
  3567. $statements = implode("\n", $trigger->getStatements());
  3568. $sql = sprintf(
  3569. "CREATE TRIGGER %s %s %s ON %s FOR EACH ROW\nBEGIN\n%s\nEND",
  3570. $trigger->getName(),
  3571. $trigger->getTime(),
  3572. $trigger->getEvent(),
  3573. $trigger->getTable(),
  3574. $statements
  3575. );
  3576. return $this->multiQuery($sql);
  3577. }
  3578. /**
  3579. * Drop trigger from database
  3580. *
  3581. * @param string $triggerName
  3582. * @param string|null $schemaName
  3583. * @return bool
  3584. * @throws \InvalidArgumentException
  3585. */
  3586. public function dropTrigger($triggerName, $schemaName = null)
  3587. {
  3588. if (empty($triggerName)) {
  3589. throw new \InvalidArgumentException((string)new \Magento\Framework\Phrase('Trigger name is not defined'));
  3590. }
  3591. $triggerName = ($schemaName ? $schemaName . '.' : '') . $triggerName;
  3592. $sql = 'DROP TRIGGER IF EXISTS ' . $this->quoteIdentifier($triggerName);
  3593. $this->query($sql);
  3594. return true;
  3595. }
  3596. /**
  3597. * Check if all transactions have been committed
  3598. *
  3599. * @return void
  3600. */
  3601. public function __destruct()
  3602. {
  3603. if ($this->_transactionLevel > 0) {
  3604. trigger_error('Some transactions have not been committed or rolled back', E_USER_ERROR);
  3605. }
  3606. }
  3607. /**
  3608. * Retrieve tables list
  3609. *
  3610. * @param null|string $likeCondition
  3611. * @return array
  3612. */
  3613. public function getTables($likeCondition = null)
  3614. {
  3615. $sql = ($likeCondition === null) ? 'SHOW TABLES' : sprintf("SHOW TABLES LIKE '%s'", $likeCondition);
  3616. $result = $this->query($sql);
  3617. $tables = [];
  3618. while ($row = $result->fetchColumn()) {
  3619. $tables[] = $row;
  3620. }
  3621. return $tables;
  3622. }
  3623. /**
  3624. * Returns auto increment field if exists
  3625. *
  3626. * @param string $tableName
  3627. * @param string|null $schemaName
  3628. * @return string|bool
  3629. * @since 100.1.0
  3630. */
  3631. public function getAutoIncrementField($tableName, $schemaName = null)
  3632. {
  3633. $indexName = $this->getPrimaryKeyName($tableName, $schemaName);
  3634. $indexes = $this->getIndexList($tableName);
  3635. if ($indexName && count($indexes[$indexName]['COLUMNS_LIST']) == 1) {
  3636. return current($indexes[$indexName]['COLUMNS_LIST']);
  3637. }
  3638. return false;
  3639. }
  3640. /**
  3641. * Get schema Listener.
  3642. *
  3643. * Required to listen all DDL changes done by 3-rd party modules with old Install/UpgradeSchema scripts.
  3644. *
  3645. * @return SchemaListener
  3646. * @since 102.0.0
  3647. */
  3648. public function getSchemaListener()
  3649. {
  3650. if ($this->schemaListener === null) {
  3651. $this->schemaListener = \Magento\Framework\App\ObjectManager::getInstance()->create(SchemaListener::class);
  3652. }
  3653. return $this->schemaListener;
  3654. }
  3655. }