AbstractPlatform.php 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the LGPL. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\DBAL\Platforms;
  20. use Doctrine\DBAL\DBALException,
  21. Doctrine\DBAL\Connection,
  22. Doctrine\DBAL\Types,
  23. Doctrine\DBAL\Schema\Table,
  24. Doctrine\DBAL\Schema\Index,
  25. Doctrine\DBAL\Schema\ForeignKeyConstraint,
  26. Doctrine\DBAL\Schema\TableDiff,
  27. Doctrine\DBAL\Schema\Column,
  28. Doctrine\DBAL\Schema\ColumnDiff,
  29. Doctrine\DBAL\Types\Type,
  30. Doctrine\DBAL\Events,
  31. Doctrine\Common\EventManager,
  32. Doctrine\DBAL\Event\SchemaCreateTableEventArgs,
  33. Doctrine\DBAL\Event\SchemaCreateTableColumnEventArgs,
  34. Doctrine\DBAL\Event\SchemaDropTableEventArgs,
  35. Doctrine\DBAL\Event\SchemaAlterTableEventArgs,
  36. Doctrine\DBAL\Event\SchemaAlterTableAddColumnEventArgs,
  37. Doctrine\DBAL\Event\SchemaAlterTableRemoveColumnEventArgs,
  38. Doctrine\DBAL\Event\SchemaAlterTableChangeColumnEventArgs,
  39. Doctrine\DBAL\Event\SchemaAlterTableRenameColumnEventArgs;
  40. /**
  41. * Base class for all DatabasePlatforms. The DatabasePlatforms are the central
  42. * point of abstraction of platform-specific behaviors, features and SQL dialects.
  43. * They are a passive source of information.
  44. *
  45. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  46. * @link www.doctrine-project.org
  47. * @since 2.0
  48. * @version $Revision: 3938 $
  49. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  50. * @author Jonathan Wage <jonwage@gmail.com>
  51. * @author Roman Borschel <roman@code-factory.org>
  52. * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
  53. * @author Benjamin Eberlei <kontakt@beberlei.de>
  54. * @todo Remove any unnecessary methods.
  55. */
  56. abstract class AbstractPlatform
  57. {
  58. /**
  59. * @var int
  60. */
  61. const CREATE_INDEXES = 1;
  62. /**
  63. * @var int
  64. */
  65. const CREATE_FOREIGNKEYS = 2;
  66. /**
  67. * @var int
  68. */
  69. const TRIM_UNSPECIFIED = 0;
  70. /**
  71. * @var int
  72. */
  73. const TRIM_LEADING = 1;
  74. /**
  75. * @var int
  76. */
  77. const TRIM_TRAILING = 2;
  78. /**
  79. * @var int
  80. */
  81. const TRIM_BOTH = 3;
  82. /**
  83. * @var array
  84. */
  85. protected $doctrineTypeMapping = null;
  86. /**
  87. * Contains a list of all columns that should generate parseable column comments for type-detection
  88. * in reverse engineering scenarios.
  89. *
  90. * @var array
  91. */
  92. protected $doctrineTypeComments = null;
  93. /**
  94. * @var Doctrine\Common\EventManager
  95. */
  96. protected $_eventManager;
  97. /**
  98. * Constructor.
  99. */
  100. public function __construct() {}
  101. /**
  102. * Sets the EventManager used by the Platform.
  103. *
  104. * @param \Doctrine\Common\EventManager
  105. */
  106. public function setEventManager(EventManager $eventManager)
  107. {
  108. $this->_eventManager = $eventManager;
  109. }
  110. /**
  111. * Gets the EventManager used by the Platform.
  112. *
  113. * @return \Doctrine\Common\EventManager
  114. */
  115. public function getEventManager()
  116. {
  117. return $this->_eventManager;
  118. }
  119. /**
  120. * Gets the SQL snippet that declares a boolean column.
  121. *
  122. * @param array $columnDef
  123. * @return string
  124. */
  125. abstract public function getBooleanTypeDeclarationSQL(array $columnDef);
  126. /**
  127. * Gets the SQL snippet that declares a 4 byte integer column.
  128. *
  129. * @param array $columnDef
  130. * @return string
  131. */
  132. abstract public function getIntegerTypeDeclarationSQL(array $columnDef);
  133. /**
  134. * Gets the SQL snippet that declares an 8 byte integer column.
  135. *
  136. * @param array $columnDef
  137. * @return string
  138. */
  139. abstract public function getBigIntTypeDeclarationSQL(array $columnDef);
  140. /**
  141. * Gets the SQL snippet that declares a 2 byte integer column.
  142. *
  143. * @param array $columnDef
  144. * @return string
  145. */
  146. abstract public function getSmallIntTypeDeclarationSQL(array $columnDef);
  147. /**
  148. * Gets the SQL snippet that declares common properties of an integer column.
  149. *
  150. * @param array $columnDef
  151. * @return string
  152. */
  153. abstract protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef);
  154. /**
  155. * Lazy load Doctrine Type Mappings
  156. *
  157. * @return void
  158. */
  159. abstract protected function initializeDoctrineTypeMappings();
  160. /**
  161. * Gets the SQL snippet used to declare a VARCHAR column type.
  162. *
  163. * @param array $field
  164. */
  165. public function getVarcharTypeDeclarationSQL(array $field)
  166. {
  167. if ( !isset($field['length'])) {
  168. $field['length'] = $this->getVarcharDefaultLength();
  169. }
  170. $fixed = (isset($field['fixed'])) ? $field['fixed'] : false;
  171. if ($field['length'] > $this->getVarcharMaxLength()) {
  172. return $this->getClobTypeDeclarationSQL($field);
  173. } else {
  174. return $this->getVarcharTypeDeclarationSQLSnippet($field['length'], $fixed);
  175. }
  176. }
  177. protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
  178. {
  179. throw DBALException::notSupported('VARCHARs not supported by Platform.');
  180. }
  181. /**
  182. * Gets the SQL snippet used to declare a CLOB column type.
  183. *
  184. * @param array $field
  185. */
  186. abstract public function getClobTypeDeclarationSQL(array $field);
  187. /**
  188. * Gets the SQL Snippet used to declare a BLOB column type.
  189. */
  190. abstract public function getBlobTypeDeclarationSQL(array $field);
  191. /**
  192. * Gets the name of the platform.
  193. *
  194. * @return string
  195. */
  196. abstract public function getName();
  197. /**
  198. * Register a doctrine type to be used in conjunction with a column type of this platform.
  199. *
  200. * @param string $dbType
  201. * @param string $doctrineType
  202. */
  203. public function registerDoctrineTypeMapping($dbType, $doctrineType)
  204. {
  205. if ($this->doctrineTypeMapping === null) {
  206. $this->initializeDoctrineTypeMappings();
  207. }
  208. if (!Types\Type::hasType($doctrineType)) {
  209. throw DBALException::typeNotFound($doctrineType);
  210. }
  211. $dbType = strtolower($dbType);
  212. $this->doctrineTypeMapping[$dbType] = $doctrineType;
  213. }
  214. /**
  215. * Get the Doctrine type that is mapped for the given database column type.
  216. *
  217. * @param string $dbType
  218. * @return string
  219. */
  220. public function getDoctrineTypeMapping($dbType)
  221. {
  222. if ($this->doctrineTypeMapping === null) {
  223. $this->initializeDoctrineTypeMappings();
  224. }
  225. $dbType = strtolower($dbType);
  226. if (isset($this->doctrineTypeMapping[$dbType])) {
  227. return $this->doctrineTypeMapping[$dbType];
  228. } else {
  229. throw new \Doctrine\DBAL\DBALException("Unknown database type ".$dbType." requested, " . get_class($this) . " may not support it.");
  230. }
  231. }
  232. /**
  233. * Check if a database type is currently supported by this platform.
  234. *
  235. * @param string $dbType
  236. * @return bool
  237. */
  238. public function hasDoctrineTypeMappingFor($dbType)
  239. {
  240. if ($this->doctrineTypeMapping === null) {
  241. $this->initializeDoctrineTypeMappings();
  242. }
  243. $dbType = strtolower($dbType);
  244. return isset($this->doctrineTypeMapping[$dbType]);
  245. }
  246. /**
  247. * Initialize the Doctrine Type comments instance variable for in_array() checks.
  248. *
  249. * @return void
  250. */
  251. protected function initializeCommentedDoctrineTypes()
  252. {
  253. $this->doctrineTypeComments = array(Type::TARRAY, Type::OBJECT);
  254. }
  255. /**
  256. * Is it necessary for the platform to add a parsable type comment to allow reverse engineering the given type?
  257. *
  258. * @param Type $doctrineType
  259. * @return bool
  260. */
  261. public function isCommentedDoctrineType(Type $doctrineType)
  262. {
  263. if ($this->doctrineTypeComments === null) {
  264. $this->initializeCommentedDoctrineTypes();
  265. }
  266. return in_array($doctrineType->getName(), $this->doctrineTypeComments);
  267. }
  268. /**
  269. * Mark this type as to be commented in ALTER TABLE and CREATE TABLE statements.
  270. *
  271. * @param Type $doctrineType
  272. * @return void
  273. */
  274. public function markDoctrineTypeCommented(Type $doctrineType)
  275. {
  276. if ($this->doctrineTypeComments === null) {
  277. $this->initializeCommentedDoctrineTypes();
  278. }
  279. $this->doctrineTypeComments[] = $doctrineType->getName();
  280. }
  281. /**
  282. * Get the comment to append to a column comment that helps parsing this type in reverse engineering.
  283. *
  284. * @param Type $doctrineType
  285. * @return string
  286. */
  287. public function getDoctrineTypeComment(Type $doctrineType)
  288. {
  289. return '(DC2Type:' . $doctrineType->getName() . ')';
  290. }
  291. /**
  292. * Return the comment of a passed column modified by potential doctrine type comment hints.
  293. *
  294. * @param Column $column
  295. * @return string
  296. */
  297. protected function getColumnComment(Column $column)
  298. {
  299. $comment = $column->getComment();
  300. if ($this->isCommentedDoctrineType($column->getType())) {
  301. $comment .= $this->getDoctrineTypeComment($column->getType());
  302. }
  303. return $comment;
  304. }
  305. /**
  306. * Gets the character used for identifier quoting.
  307. *
  308. * @return string
  309. */
  310. public function getIdentifierQuoteCharacter()
  311. {
  312. return '"';
  313. }
  314. /**
  315. * Gets the string portion that starts an SQL comment.
  316. *
  317. * @return string
  318. */
  319. public function getSqlCommentStartString()
  320. {
  321. return "--";
  322. }
  323. /**
  324. * Gets the string portion that ends an SQL comment.
  325. *
  326. * @return string
  327. */
  328. public function getSqlCommentEndString()
  329. {
  330. return "\n";
  331. }
  332. /**
  333. * Gets the maximum length of a varchar field.
  334. *
  335. * @return integer
  336. */
  337. public function getVarcharMaxLength()
  338. {
  339. return 4000;
  340. }
  341. /**
  342. * Gets the default length of a varchar field.
  343. *
  344. * @return integer
  345. */
  346. public function getVarcharDefaultLength()
  347. {
  348. return 255;
  349. }
  350. /**
  351. * Gets all SQL wildcard characters of the platform.
  352. *
  353. * @return array
  354. */
  355. public function getWildcards()
  356. {
  357. return array('%', '_');
  358. }
  359. /**
  360. * Returns the regular expression operator.
  361. *
  362. * @return string
  363. */
  364. public function getRegexpExpression()
  365. {
  366. throw DBALException::notSupported(__METHOD__);
  367. }
  368. /**
  369. * Returns global unique identifier
  370. *
  371. * @return string to get global unique identifier
  372. */
  373. public function getGuidExpression()
  374. {
  375. throw DBALException::notSupported(__METHOD__);
  376. }
  377. /**
  378. * Returns the average value of a column
  379. *
  380. * @param string $column the column to use
  381. * @return string generated sql including an AVG aggregate function
  382. */
  383. public function getAvgExpression($column)
  384. {
  385. return 'AVG(' . $column . ')';
  386. }
  387. /**
  388. * Returns the number of rows (without a NULL value) of a column
  389. *
  390. * If a '*' is used instead of a column the number of selected rows
  391. * is returned.
  392. *
  393. * @param string|integer $column the column to use
  394. * @return string generated sql including a COUNT aggregate function
  395. */
  396. public function getCountExpression($column)
  397. {
  398. return 'COUNT(' . $column . ')';
  399. }
  400. /**
  401. * Returns the highest value of a column
  402. *
  403. * @param string $column the column to use
  404. * @return string generated sql including a MAX aggregate function
  405. */
  406. public function getMaxExpression($column)
  407. {
  408. return 'MAX(' . $column . ')';
  409. }
  410. /**
  411. * Returns the lowest value of a column
  412. *
  413. * @param string $column the column to use
  414. * @return string
  415. */
  416. public function getMinExpression($column)
  417. {
  418. return 'MIN(' . $column . ')';
  419. }
  420. /**
  421. * Returns the total sum of a column
  422. *
  423. * @param string $column the column to use
  424. * @return string
  425. */
  426. public function getSumExpression($column)
  427. {
  428. return 'SUM(' . $column . ')';
  429. }
  430. // scalar functions
  431. /**
  432. * Returns the md5 sum of a field.
  433. *
  434. * Note: Not SQL92, but common functionality
  435. *
  436. * @return string
  437. */
  438. public function getMd5Expression($column)
  439. {
  440. return 'MD5(' . $column . ')';
  441. }
  442. /**
  443. * Returns the length of a text field.
  444. *
  445. * @param string $expression1
  446. * @param string $expression2
  447. * @return string
  448. */
  449. public function getLengthExpression($column)
  450. {
  451. return 'LENGTH(' . $column . ')';
  452. }
  453. /**
  454. * Rounds a numeric field to the number of decimals specified.
  455. *
  456. * @param string $expression1
  457. * @param string $expression2
  458. * @return string
  459. */
  460. public function getRoundExpression($column, $decimals = 0)
  461. {
  462. return 'ROUND(' . $column . ', ' . $decimals . ')';
  463. }
  464. /**
  465. * Returns the remainder of the division operation
  466. * $expression1 / $expression2.
  467. *
  468. * @param string $expression1
  469. * @param string $expression2
  470. * @return string
  471. */
  472. public function getModExpression($expression1, $expression2)
  473. {
  474. return 'MOD(' . $expression1 . ', ' . $expression2 . ')';
  475. }
  476. /**
  477. * Trim a string, leading/trailing/both and with a given char which defaults to space.
  478. *
  479. * @param string $str
  480. * @param int $pos
  481. * @param string $char has to be quoted already
  482. * @return string
  483. */
  484. public function getTrimExpression($str, $pos = self::TRIM_UNSPECIFIED, $char = false)
  485. {
  486. $posStr = '';
  487. $trimChar = ($char != false) ? $char . ' FROM ' : '';
  488. if ($pos == self::TRIM_LEADING) {
  489. $posStr = 'LEADING '.$trimChar;
  490. } else if($pos == self::TRIM_TRAILING) {
  491. $posStr = 'TRAILING '.$trimChar;
  492. } else if($pos == self::TRIM_BOTH) {
  493. $posStr = 'BOTH '.$trimChar;
  494. }
  495. return 'TRIM(' . $posStr . $str . ')';
  496. }
  497. /**
  498. * rtrim
  499. * returns the string $str with proceeding space characters removed
  500. *
  501. * @param string $str literal string or column name
  502. * @return string
  503. */
  504. public function getRtrimExpression($str)
  505. {
  506. return 'RTRIM(' . $str . ')';
  507. }
  508. /**
  509. * ltrim
  510. * returns the string $str with leading space characters removed
  511. *
  512. * @param string $str literal string or column name
  513. * @return string
  514. */
  515. public function getLtrimExpression($str)
  516. {
  517. return 'LTRIM(' . $str . ')';
  518. }
  519. /**
  520. * upper
  521. * Returns the string $str with all characters changed to
  522. * uppercase according to the current character set mapping.
  523. *
  524. * @param string $str literal string or column name
  525. * @return string
  526. */
  527. public function getUpperExpression($str)
  528. {
  529. return 'UPPER(' . $str . ')';
  530. }
  531. /**
  532. * lower
  533. * Returns the string $str with all characters changed to
  534. * lowercase according to the current character set mapping.
  535. *
  536. * @param string $str literal string or column name
  537. * @return string
  538. */
  539. public function getLowerExpression($str)
  540. {
  541. return 'LOWER(' . $str . ')';
  542. }
  543. /**
  544. * returns the position of the first occurrence of substring $substr in string $str
  545. *
  546. * @param string $substr literal string to find
  547. * @param string $str literal string
  548. * @param int $pos position to start at, beginning of string by default
  549. * @return integer
  550. */
  551. public function getLocateExpression($str, $substr, $startPos = false)
  552. {
  553. throw DBALException::notSupported(__METHOD__);
  554. }
  555. /**
  556. * Returns the current system date.
  557. *
  558. * @return string
  559. */
  560. public function getNowExpression()
  561. {
  562. return 'NOW()';
  563. }
  564. /**
  565. * return string to call a function to get a substring inside an SQL statement
  566. *
  567. * Note: Not SQL92, but common functionality.
  568. *
  569. * SQLite only supports the 2 parameter variant of this function
  570. *
  571. * @param string $value an sql string literal or column name/alias
  572. * @param integer $from where to start the substring portion
  573. * @param integer $len the substring portion length
  574. * @return string
  575. */
  576. public function getSubstringExpression($value, $from, $len = null)
  577. {
  578. if ($len === null)
  579. return 'SUBSTRING(' . $value . ' FROM ' . $from . ')';
  580. else {
  581. return 'SUBSTRING(' . $value . ' FROM ' . $from . ' FOR ' . $len . ')';
  582. }
  583. }
  584. /**
  585. * Returns a series of strings concatinated
  586. *
  587. * concat() accepts an arbitrary number of parameters. Each parameter
  588. * must contain an expression
  589. *
  590. * @param string $arg1, $arg2 ... $argN strings that will be concatinated.
  591. * @return string
  592. */
  593. public function getConcatExpression()
  594. {
  595. return join(' || ' , func_get_args());
  596. }
  597. /**
  598. * Returns the SQL for a logical not.
  599. *
  600. * Example:
  601. * <code>
  602. * $q = new Doctrine_Query();
  603. * $e = $q->expr;
  604. * $q->select('*')->from('table')
  605. * ->where($e->eq('id', $e->not('null'));
  606. * </code>
  607. *
  608. * @return string a logical expression
  609. */
  610. public function getNotExpression($expression)
  611. {
  612. return 'NOT(' . $expression . ')';
  613. }
  614. /**
  615. * Returns the SQL to check if a value is one in a set of
  616. * given values.
  617. *
  618. * in() accepts an arbitrary number of parameters. The first parameter
  619. * must always specify the value that should be matched against. Successive
  620. * must contain a logical expression or an array with logical expressions.
  621. * These expressions will be matched against the first parameter.
  622. *
  623. * @param string $column the value that should be matched against
  624. * @param string|array(string) values that will be matched against $column
  625. * @return string logical expression
  626. */
  627. public function getInExpression($column, $values)
  628. {
  629. if ( ! is_array($values)) {
  630. $values = array($values);
  631. }
  632. $values = $this->getIdentifiers($values);
  633. if (count($values) == 0) {
  634. throw \InvalidArgumentException('Values must not be empty.');
  635. }
  636. return $column . ' IN (' . implode(', ', $values) . ')';
  637. }
  638. /**
  639. * Returns SQL that checks if a expression is null.
  640. *
  641. * @param string $expression the expression that should be compared to null
  642. * @return string logical expression
  643. */
  644. public function getIsNullExpression($expression)
  645. {
  646. return $expression . ' IS NULL';
  647. }
  648. /**
  649. * Returns SQL that checks if a expression is not null.
  650. *
  651. * @param string $expression the expression that should be compared to null
  652. * @return string logical expression
  653. */
  654. public function getIsNotNullExpression($expression)
  655. {
  656. return $expression . ' IS NOT NULL';
  657. }
  658. /**
  659. * Returns SQL that checks if an expression evaluates to a value between
  660. * two values.
  661. *
  662. * The parameter $expression is checked if it is between $value1 and $value2.
  663. *
  664. * Note: There is a slight difference in the way BETWEEN works on some databases.
  665. * http://www.w3schools.com/sql/sql_between.asp. If you want complete database
  666. * independence you should avoid using between().
  667. *
  668. * @param string $expression the value to compare to
  669. * @param string $value1 the lower value to compare with
  670. * @param string $value2 the higher value to compare with
  671. * @return string logical expression
  672. */
  673. public function getBetweenExpression($expression, $value1, $value2)
  674. {
  675. return $expression . ' BETWEEN ' .$value1 . ' AND ' . $value2;
  676. }
  677. public function getAcosExpression($value)
  678. {
  679. return 'ACOS(' . $value . ')';
  680. }
  681. public function getSinExpression($value)
  682. {
  683. return 'SIN(' . $value . ')';
  684. }
  685. public function getPiExpression()
  686. {
  687. return 'PI()';
  688. }
  689. public function getCosExpression($value)
  690. {
  691. return 'COS(' . $value . ')';
  692. }
  693. /**
  694. * Calculate the difference in days between the two passed dates.
  695. *
  696. * Computes diff = date1 - date2
  697. *
  698. * @param string $date1
  699. * @param string $date2
  700. * @return string
  701. */
  702. public function getDateDiffExpression($date1, $date2)
  703. {
  704. throw DBALException::notSupported(__METHOD__);
  705. }
  706. /**
  707. * Add the number of given days to a date.
  708. *
  709. * @param string $date
  710. * @param int $days
  711. * @return string
  712. */
  713. public function getDateAddDaysExpression($date, $days)
  714. {
  715. throw DBALException::notSupported(__METHOD__);
  716. }
  717. /**
  718. * Substract the number of given days to a date.
  719. *
  720. * @param string $date
  721. * @param int $days
  722. * @return string
  723. */
  724. public function getDateSubDaysExpression($date, $days)
  725. {
  726. throw DBALException::notSupported(__METHOD__);
  727. }
  728. /**
  729. * Add the number of given months to a date.
  730. *
  731. * @param string $date
  732. * @param int $months
  733. * @return string
  734. */
  735. public function getDateAddMonthExpression($date, $months)
  736. {
  737. throw DBALException::notSupported(__METHOD__);
  738. }
  739. /**
  740. * Substract the number of given months to a date.
  741. *
  742. * @param string $date
  743. * @param int $months
  744. * @return string
  745. */
  746. public function getDateSubMonthExpression($date, $months)
  747. {
  748. throw DBALException::notSupported(__METHOD__);
  749. }
  750. /**
  751. * Gets SQL bit AND comparison expression
  752. *
  753. * @param string $value1
  754. * @param string $value2
  755. * @return string
  756. */
  757. public function getBitAndComparisonExpression($value1, $value2)
  758. {
  759. return '(' . $value1 . ' & ' . $value2 . ')';
  760. }
  761. /**
  762. * Gets SQL bit OR comparison expression
  763. *
  764. * @param string $value1
  765. * @param string $value2
  766. * @return string
  767. */
  768. public function getBitOrComparisonExpression($value1, $value2)
  769. {
  770. return '(' . $value1 . ' | ' . $value2 . ')';
  771. }
  772. public function getForUpdateSQL()
  773. {
  774. return 'FOR UPDATE';
  775. }
  776. /**
  777. * Honors that some SQL vendors such as MsSql use table hints for locking instead of the ANSI SQL FOR UPDATE specification.
  778. *
  779. * @param string $fromClause
  780. * @param int $lockMode
  781. * @return string
  782. */
  783. public function appendLockHint($fromClause, $lockMode)
  784. {
  785. return $fromClause;
  786. }
  787. /**
  788. * Get the sql snippet to append to any SELECT statement which locks rows in shared read lock.
  789. *
  790. * This defaults to the ASNI SQL "FOR UPDATE", which is an exclusive lock (Write). Some database
  791. * vendors allow to lighten this constraint up to be a real read lock.
  792. *
  793. * @return string
  794. */
  795. public function getReadLockSQL()
  796. {
  797. return $this->getForUpdateSQL();
  798. }
  799. /**
  800. * Get the SQL snippet to append to any SELECT statement which obtains an exclusive lock on the rows.
  801. *
  802. * The semantics of this lock mode should equal the SELECT .. FOR UPDATE of the ASNI SQL standard.
  803. *
  804. * @return string
  805. */
  806. public function getWriteLockSQL()
  807. {
  808. return $this->getForUpdateSQL();
  809. }
  810. public function getDropDatabaseSQL($database)
  811. {
  812. return 'DROP DATABASE ' . $database;
  813. }
  814. /**
  815. * Drop a Table
  816. *
  817. * @throws \InvalidArgumentException
  818. * @param Table|string $table
  819. * @return string
  820. */
  821. public function getDropTableSQL($table)
  822. {
  823. $tableArg = $table;
  824. if ($table instanceof \Doctrine\DBAL\Schema\Table) {
  825. $table = $table->getQuotedName($this);
  826. } else if(!is_string($table)) {
  827. throw new \InvalidArgumentException('getDropTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
  828. }
  829. if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaDropTable)) {
  830. $eventArgs = new SchemaDropTableEventArgs($tableArg, $this);
  831. $this->_eventManager->dispatchEvent(Events::onSchemaDropTable, $eventArgs);
  832. if ($eventArgs->isDefaultPrevented()) {
  833. return $eventArgs->getSql();
  834. }
  835. }
  836. return 'DROP TABLE ' . $table;
  837. }
  838. /**
  839. * Get SQL to safely drop a temporary table WITHOUT implicitly committing an open transaction.
  840. *
  841. * @param Table|string $table
  842. * @return string
  843. */
  844. public function getDropTemporaryTableSQL($table)
  845. {
  846. return $this->getDropTableSQL($table);
  847. }
  848. /**
  849. * Drop index from a table
  850. *
  851. * @param Index|string $name
  852. * @param string|Table $table
  853. * @return string
  854. */
  855. public function getDropIndexSQL($index, $table=null)
  856. {
  857. if($index instanceof \Doctrine\DBAL\Schema\Index) {
  858. $index = $index->getQuotedName($this);
  859. } else if(!is_string($index)) {
  860. throw new \InvalidArgumentException('AbstractPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
  861. }
  862. return 'DROP INDEX ' . $index;
  863. }
  864. /**
  865. * Get drop constraint sql
  866. *
  867. * @param \Doctrine\DBAL\Schema\Constraint $constraint
  868. * @param string|Table $table
  869. * @return string
  870. */
  871. public function getDropConstraintSQL($constraint, $table)
  872. {
  873. if ($constraint instanceof \Doctrine\DBAL\Schema\Constraint) {
  874. $constraint = $constraint->getQuotedName($this);
  875. }
  876. if ($table instanceof \Doctrine\DBAL\Schema\Table) {
  877. $table = $table->getQuotedName($this);
  878. }
  879. return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $constraint;
  880. }
  881. /**
  882. * @param ForeignKeyConstraint|string $foreignKey
  883. * @param Table|string $table
  884. * @return string
  885. */
  886. public function getDropForeignKeySQL($foreignKey, $table)
  887. {
  888. if ($foreignKey instanceof \Doctrine\DBAL\Schema\ForeignKeyConstraint) {
  889. $foreignKey = $foreignKey->getQuotedName($this);
  890. }
  891. if ($table instanceof \Doctrine\DBAL\Schema\Table) {
  892. $table = $table->getQuotedName($this);
  893. }
  894. return 'ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $foreignKey;
  895. }
  896. /**
  897. * Gets the SQL statement(s) to create a table with the specified name, columns and constraints
  898. * on this platform.
  899. *
  900. * @param string $table The name of the table.
  901. * @param int $createFlags
  902. * @return array The sequence of SQL statements.
  903. */
  904. public function getCreateTableSQL(Table $table, $createFlags=self::CREATE_INDEXES)
  905. {
  906. if ( ! is_int($createFlags)) {
  907. throw new \InvalidArgumentException("Second argument of AbstractPlatform::getCreateTableSQL() has to be integer.");
  908. }
  909. if (count($table->getColumns()) == 0) {
  910. throw DBALException::noColumnsSpecifiedForTable($table->getName());
  911. }
  912. $tableName = $table->getQuotedName($this);
  913. $options = $table->getOptions();
  914. $options['uniqueConstraints'] = array();
  915. $options['indexes'] = array();
  916. $options['primary'] = array();
  917. if (($createFlags&self::CREATE_INDEXES) > 0) {
  918. foreach ($table->getIndexes() AS $index) {
  919. /* @var $index Index */
  920. if ($index->isPrimary()) {
  921. $options['primary'] = $index->getColumns();
  922. } else {
  923. $options['indexes'][$index->getName()] = $index;
  924. }
  925. }
  926. }
  927. $columnSql = array();
  928. $columns = array();
  929. foreach ($table->getColumns() AS $column) {
  930. /* @var \Doctrine\DBAL\Schema\Column $column */
  931. if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaCreateTableColumn)) {
  932. $eventArgs = new SchemaCreateTableColumnEventArgs($column, $table, $this);
  933. $this->_eventManager->dispatchEvent(Events::onSchemaCreateTableColumn, $eventArgs);
  934. $columnSql = array_merge($columnSql, $eventArgs->getSql());
  935. if ($eventArgs->isDefaultPrevented()) {
  936. continue;
  937. }
  938. }
  939. $columnData = array();
  940. $columnData['name'] = $column->getQuotedName($this);
  941. $columnData['type'] = $column->getType();
  942. $columnData['length'] = $column->getLength();
  943. $columnData['notnull'] = $column->getNotNull();
  944. $columnData['fixed'] = $column->getFixed();
  945. $columnData['unique'] = false; // TODO: what do we do about this?
  946. $columnData['version'] = ($column->hasPlatformOption("version"))?$column->getPlatformOption('version'):false;
  947. if(strtolower($columnData['type']) == "string" && $columnData['length'] === null) {
  948. $columnData['length'] = 255;
  949. }
  950. $columnData['unsigned'] = $column->getUnsigned();
  951. $columnData['precision'] = $column->getPrecision();
  952. $columnData['scale'] = $column->getScale();
  953. $columnData['default'] = $column->getDefault();
  954. $columnData['columnDefinition'] = $column->getColumnDefinition();
  955. $columnData['autoincrement'] = $column->getAutoincrement();
  956. $columnData['comment'] = $this->getColumnComment($column);
  957. if(in_array($column->getName(), $options['primary'])) {
  958. $columnData['primary'] = true;
  959. }
  960. $columns[$columnData['name']] = $columnData;
  961. }
  962. if (($createFlags&self::CREATE_FOREIGNKEYS) > 0) {
  963. $options['foreignKeys'] = array();
  964. foreach ($table->getForeignKeys() AS $fkConstraint) {
  965. $options['foreignKeys'][] = $fkConstraint;
  966. }
  967. }
  968. if (null !== $this->_eventManager && $this->_eventManager->hasListeners(Events::onSchemaCreateTable)) {
  969. $eventArgs = new SchemaCreateTableEventArgs($table, $columns, $options, $this);
  970. $this->_eventManager->dispatchEvent(Events::onSchemaCreateTable, $eventArgs);
  971. if ($eventArgs->isDefaultPrevented()) {
  972. return array_merge($eventArgs->getSql(), $columnSql);
  973. }
  974. }
  975. $sql = $this->_getCreateTableSQL($tableName, $columns, $options);
  976. if ($this->supportsCommentOnStatement()) {
  977. foreach ($table->getColumns() AS $column) {
  978. if ($this->getColumnComment($column)) {
  979. $sql[] = $this->getCommentOnColumnSQL($tableName, $column->getName(), $this->getColumnComment($column));
  980. }
  981. }
  982. }
  983. return array_merge($sql, $columnSql);
  984. }
  985. public function getCommentOnColumnSQL($tableName, $columnName, $comment)
  986. {
  987. return "COMMENT ON COLUMN " . $tableName . "." . $columnName . " IS '" . $comment . "'";
  988. }
  989. /**
  990. * @param string $tableName
  991. * @param array $columns
  992. * @param array $options
  993. * @return array
  994. */
  995. protected function _getCreateTableSQL($tableName, array $columns, array $options = array())
  996. {
  997. $columnListSql = $this->getColumnDeclarationListSQL($columns);
  998. if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
  999. foreach ($options['uniqueConstraints'] as $name => $definition) {
  1000. $columnListSql .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
  1001. }
  1002. }
  1003. if (isset($options['primary']) && ! empty($options['primary'])) {
  1004. $columnListSql .= ', PRIMARY KEY(' . implode(', ', array_unique(array_values($options['primary']))) . ')';
  1005. }
  1006. if (isset($options['indexes']) && ! empty($options['indexes'])) {
  1007. foreach($options['indexes'] as $index => $definition) {
  1008. $columnListSql .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
  1009. }
  1010. }
  1011. $query = 'CREATE TABLE ' . $tableName . ' (' . $columnListSql;
  1012. $check = $this->getCheckDeclarationSQL($columns);
  1013. if ( ! empty($check)) {
  1014. $query .= ', ' . $check;
  1015. }
  1016. $query .= ')';
  1017. $sql[] = $query;
  1018. if (isset($options['foreignKeys'])) {
  1019. foreach ((array) $options['foreignKeys'] AS $definition) {
  1020. $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
  1021. }
  1022. }
  1023. return $sql;
  1024. }
  1025. public function getCreateTemporaryTableSnippetSQL()
  1026. {
  1027. return "CREATE TEMPORARY TABLE";
  1028. }
  1029. /**
  1030. * Gets the SQL to create a sequence on this platform.
  1031. *
  1032. * @param \Doctrine\DBAL\Schema\Sequence $sequence
  1033. * @throws DBALException
  1034. */
  1035. public function getCreateSequenceSQL(\Doctrine\DBAL\Schema\Sequence $sequence)
  1036. {
  1037. throw DBALException::notSupported(__METHOD__);
  1038. }
  1039. /**
  1040. * Gets the SQL statement to change a sequence on this platform.
  1041. *
  1042. * @param \Doctrine\DBAL\Schema\Sequence $sequence
  1043. * @return string
  1044. */
  1045. public function getAlterSequenceSQL(\Doctrine\DBAL\Schema\Sequence $sequence)
  1046. {
  1047. throw DBALException::notSupported(__METHOD__);
  1048. }
  1049. /**
  1050. * Gets the SQL to create a constraint on a table on this platform.
  1051. *
  1052. * @param Constraint $constraint
  1053. * @param string|Table $table
  1054. * @return string
  1055. */
  1056. public function getCreateConstraintSQL(\Doctrine\DBAL\Schema\Constraint $constraint, $table)
  1057. {
  1058. if ($table instanceof \Doctrine\DBAL\Schema\Table) {
  1059. $table = $table->getQuotedName($this);
  1060. }
  1061. $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $constraint->getQuotedName($this);
  1062. $columns = array();
  1063. foreach ($constraint->getColumns() as $column) {
  1064. $columns[] = $column;
  1065. }
  1066. $columnList = '('. implode(', ', $columns) . ')';
  1067. $referencesClause = '';
  1068. if ($constraint instanceof \Doctrine\DBAL\Schema\Index) {
  1069. if($constraint->isPrimary()) {
  1070. $query .= ' PRIMARY KEY';
  1071. } elseif ($constraint->isUnique()) {
  1072. $query .= ' UNIQUE';
  1073. } else {
  1074. throw new \InvalidArgumentException(
  1075. 'Can only create primary or unique constraints, no common indexes with getCreateConstraintSQL().'
  1076. );
  1077. }
  1078. } else if ($constraint instanceof \Doctrine\DBAL\Schema\ForeignKeyConstraint) {
  1079. $query .= ' FOREIGN KEY';
  1080. $foreignColumns = array();
  1081. foreach ($constraint->getForeignColumns() AS $column) {
  1082. $foreignColumns[] = $column;
  1083. }
  1084. $referencesClause = ' REFERENCES '.$constraint->getForeignTableName(). ' ('.implode(', ', $foreignColumns).')';
  1085. }
  1086. $query .= ' '.$columnList.$referencesClause;
  1087. return $query;
  1088. }
  1089. /**
  1090. * Gets the SQL to create an index on a table on this platform.
  1091. *
  1092. * @param Index $index
  1093. * @param string|Table $table name of the table on which the index is to be created
  1094. * @return string
  1095. */
  1096. public function getCreateIndexSQL(Index $index, $table)
  1097. {
  1098. if ($table instanceof Table) {
  1099. $table = $table->getQuotedName($this);
  1100. }
  1101. $name = $index->getQuotedName($this);
  1102. $columns = $index->getColumns();
  1103. if (count($columns) == 0) {
  1104. throw new \InvalidArgumentException("Incomplete definition. 'columns' required.");
  1105. }
  1106. if ($index->isPrimary()) {
  1107. return $this->getCreatePrimaryKeySQL($index, $table);
  1108. } else {
  1109. $type = '';
  1110. if ($index->isUnique()) {
  1111. $type = 'UNIQUE ';
  1112. }
  1113. $query = 'CREATE ' . $type . 'INDEX ' . $name . ' ON ' . $table;
  1114. $query .= ' (' . $this->getIndexFieldDeclarationListSQL($columns) . ')';
  1115. }
  1116. return $query;
  1117. }
  1118. /**
  1119. * Get SQL to create an unnamed primary key constraint.
  1120. *
  1121. * @param Index $index
  1122. * @param string|Table $table
  1123. * @return string
  1124. */
  1125. public function getCreatePrimaryKeySQL(Index $index, $table)
  1126. {
  1127. return 'ALTER TABLE ' . $table . ' ADD PRIMARY KEY (' . $this->getIndexFieldDeclarationListSQL($index->getColumns()) . ')';
  1128. }
  1129. /**
  1130. * Quotes a string so that it can be safely used as a table or column name,
  1131. * even if it is a reserved word of the platform. This also detects identifier
  1132. * chains seperated by dot and quotes them independently.
  1133. *
  1134. * NOTE: Just because you CAN use quoted identifiers doesn't mean
  1135. * you SHOULD use them. In general, they end up causing way more
  1136. * problems than they solve.
  1137. *
  1138. * @param string $str identifier name to be quoted
  1139. * @return string quoted identifier string
  1140. */
  1141. public function quoteIdentifier($str)
  1142. {
  1143. if (strpos($str, ".") !== false) {
  1144. $parts = array_map(array($this, "quoteIdentifier"), explode(".", $str));
  1145. return implode(".", $parts);
  1146. }
  1147. return $this->quoteSingleIdentifier($str);
  1148. }
  1149. /**
  1150. * Quote a single identifier (no dot chain seperation)
  1151. *
  1152. * @param string $str
  1153. * @return string
  1154. */
  1155. public function quoteSingleIdentifier($str)
  1156. {
  1157. $c = $this->getIdentifierQuoteCharacter();
  1158. return $c . str_replace($c, $c.$c, $str) . $c;
  1159. }
  1160. /**
  1161. * Create a new foreign key
  1162. *
  1163. * @param ForeignKeyConstraint $foreignKey ForeignKey instance
  1164. * @param string|Table $table name of the table on which the foreign key is to be created
  1165. * @return string
  1166. */
  1167. public function getCreateForeignKeySQL(ForeignKeyConstraint $foreignKey, $table)
  1168. {
  1169. if ($table instanceof \Doctrine\DBAL\Schema\Table) {
  1170. $table = $table->getQuotedName($this);
  1171. }
  1172. $query = 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclarationSQL($foreignKey);
  1173. return $query;
  1174. }
  1175. /**
  1176. * Gets the sql statements for altering an existing table.
  1177. *
  1178. * The method returns an array of sql statements, since some platforms need several statements.
  1179. *
  1180. * @param TableDiff $diff
  1181. * @return array
  1182. */
  1183. public function getAlterTableSQL(TableDiff $diff)
  1184. {
  1185. throw DBALException::notSupported(__METHOD__);
  1186. }
  1187. /**
  1188. * @param Column $column
  1189. * @param TableDiff $diff
  1190. * @param array $columnSql
  1191. */
  1192. protected function onSchemaAlterTableAddColumn(Column $column, TableDiff $diff, &$columnSql)
  1193. {
  1194. if (null === $this->_eventManager) {
  1195. return false;
  1196. }
  1197. if (!$this->_eventManager->hasListeners(Events::onSchemaAlterTableAddColumn)) {
  1198. return false;
  1199. }
  1200. $eventArgs = new SchemaAlterTableAddColumnEventArgs($column, $diff, $this);
  1201. $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableAddColumn, $eventArgs);
  1202. $columnSql = array_merge($columnSql, $eventArgs->getSql());
  1203. return $eventArgs->isDefaultPrevented();
  1204. }
  1205. /**
  1206. * @param Column $column
  1207. * @param TableDiff $diff
  1208. * @param array $columnSql
  1209. */
  1210. protected function onSchemaAlterTableRemoveColumn(Column $column, TableDiff $diff, &$columnSql)
  1211. {
  1212. if (null === $this->_eventManager) {
  1213. return false;
  1214. }
  1215. if (!$this->_eventManager->hasListeners(Events::onSchemaAlterTableRemoveColumn)) {
  1216. return false;
  1217. }
  1218. $eventArgs = new SchemaAlterTableRemoveColumnEventArgs($column, $diff, $this);
  1219. $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRemoveColumn, $eventArgs);
  1220. $columnSql = array_merge($columnSql, $eventArgs->getSql());
  1221. return $eventArgs->isDefaultPrevented();
  1222. }
  1223. /**
  1224. * @param ColumnDiff $columnDiff
  1225. * @param TableDiff $diff
  1226. * @param array $columnSql
  1227. */
  1228. protected function onSchemaAlterTableChangeColumn(ColumnDiff $columnDiff, TableDiff $diff, &$columnSql)
  1229. {
  1230. if (null === $this->_eventManager) {
  1231. return false;
  1232. }
  1233. if (!$this->_eventManager->hasListeners(Events::onSchemaAlterTableChangeColumn)) {
  1234. return false;
  1235. }
  1236. $eventArgs = new SchemaAlterTableChangeColumnEventArgs($columnDiff, $diff, $this);
  1237. $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableChangeColumn, $eventArgs);
  1238. $columnSql = array_merge($columnSql, $eventArgs->getSql());
  1239. return $eventArgs->isDefaultPrevented();
  1240. }
  1241. /**
  1242. * @param string $oldColumnName
  1243. * @param Column $column
  1244. * @param TableDiff $diff
  1245. * @param array $columnSql
  1246. */
  1247. protected function onSchemaAlterTableRenameColumn($oldColumnName, Column $column, TableDiff $diff, &$columnSql)
  1248. {
  1249. if (null === $this->_eventManager) {
  1250. return false;
  1251. }
  1252. if (!$this->_eventManager->hasListeners(Events::onSchemaAlterTableRenameColumn)) {
  1253. return false;
  1254. }
  1255. $eventArgs = new SchemaAlterTableRenameColumnEventArgs($oldColumnName, $column, $diff, $this);
  1256. $this->_eventManager->dispatchEvent(Events::onSchemaAlterTableRenameColumn, $eventArgs);
  1257. $columnSql = array_merge($columnSql, $eventArgs->getSql());
  1258. return $eventArgs->isDefaultPrevented();
  1259. }
  1260. /**
  1261. * @param TableDiff $diff
  1262. * @param array $columnSql
  1263. */
  1264. protected function onSchemaAlterTable(TableDiff $diff, &$sql)
  1265. {
  1266. if (null === $this->_eventManager) {
  1267. return false;
  1268. }
  1269. if (!$this->_eventManager->hasListeners(Events::onSchemaAlterTable)) {
  1270. return false;
  1271. }
  1272. $eventArgs = new SchemaAlterTableEventArgs($diff, $this);
  1273. $this->_eventManager->dispatchEvent(Events::onSchemaAlterTable, $eventArgs);
  1274. $sql = array_merge($sql, $eventArgs->getSql());
  1275. return $eventArgs->isDefaultPrevented();
  1276. }
  1277. protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff)
  1278. {
  1279. $tableName = $diff->name;
  1280. $sql = array();
  1281. if ($this->supportsForeignKeyConstraints()) {
  1282. foreach ($diff->removedForeignKeys AS $foreignKey) {
  1283. $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
  1284. }
  1285. foreach ($diff->changedForeignKeys AS $foreignKey) {
  1286. $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
  1287. }
  1288. }
  1289. foreach ($diff->removedIndexes AS $index) {
  1290. $sql[] = $this->getDropIndexSQL($index, $tableName);
  1291. }
  1292. foreach ($diff->changedIndexes AS $index) {
  1293. $sql[] = $this->getDropIndexSQL($index, $tableName);
  1294. }
  1295. return $sql;
  1296. }
  1297. protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff)
  1298. {
  1299. if ($diff->newName !== false) {
  1300. $tableName = $diff->newName;
  1301. } else {
  1302. $tableName = $diff->name;
  1303. }
  1304. $sql = array();
  1305. if ($this->supportsForeignKeyConstraints()) {
  1306. foreach ($diff->addedForeignKeys AS $foreignKey) {
  1307. $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
  1308. }
  1309. foreach ($diff->changedForeignKeys AS $foreignKey) {
  1310. $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
  1311. }
  1312. }
  1313. foreach ($diff->addedIndexes AS $index) {
  1314. $sql[] = $this->getCreateIndexSQL($index, $tableName);
  1315. }
  1316. foreach ($diff->changedIndexes AS $index) {
  1317. $sql[] = $this->getCreateIndexSQL($index, $tableName);
  1318. }
  1319. return $sql;
  1320. }
  1321. /**
  1322. * Common code for alter table statement generation that updates the changed Index and Foreign Key definitions.
  1323. *
  1324. * @param TableDiff $diff
  1325. * @return array
  1326. */
  1327. protected function _getAlterTableIndexForeignKeySQL(TableDiff $diff)
  1328. {
  1329. return array_merge($this->getPreAlterTableIndexForeignKeySQL($diff), $this->getPostAlterTableIndexForeignKeySQL($diff));
  1330. }
  1331. /**
  1332. * Get declaration of a number of fields in bulk
  1333. *
  1334. * @param array $fields a multidimensional associative array.
  1335. * The first dimension determines the field name, while the second
  1336. * dimension is keyed with the name of the properties
  1337. * of the field being declared as array indexes. Currently, the types
  1338. * of supported field properties are as follows:
  1339. *
  1340. * length
  1341. * Integer value that determines the maximum length of the text
  1342. * field. If this argument is missing the field should be
  1343. * declared to have the longest length allowed by the DBMS.
  1344. *
  1345. * default
  1346. * Text value to be used as default for this field.
  1347. *
  1348. * notnull
  1349. * Boolean flag that indicates whether this field is constrained
  1350. * to not be set to null.
  1351. * charset
  1352. * Text value with the default CHARACTER SET for this field.
  1353. * collation
  1354. * Text value with the default COLLATION for this field.
  1355. * unique
  1356. * unique constraint
  1357. *
  1358. * @return string
  1359. */
  1360. public function getColumnDeclarationListSQL(array $fields)
  1361. {
  1362. $queryFields = array();
  1363. foreach ($fields as $fieldName => $field) {
  1364. $query = $this->getColumnDeclarationSQL($fieldName, $field);
  1365. $queryFields[] = $query;
  1366. }
  1367. return implode(', ', $queryFields);
  1368. }
  1369. /**
  1370. * Obtain DBMS specific SQL code portion needed to declare a generic type
  1371. * field to be used in statements like CREATE TABLE.
  1372. *
  1373. * @param string $name name the field to be declared.
  1374. * @param array $field associative array with the name of the properties
  1375. * of the field being declared as array indexes. Currently, the types
  1376. * of supported field properties are as follows:
  1377. *
  1378. * length
  1379. * Integer value that determines the maximum length of the text
  1380. * field. If this argument is missing the field should be
  1381. * declared to have the longest length allowed by the DBMS.
  1382. *
  1383. * default
  1384. * Text value to be used as default for this field.
  1385. *
  1386. * notnull
  1387. * Boolean flag that indicates whether this field is constrained
  1388. * to not be set to null.
  1389. * charset
  1390. * Text value with the default CHARACTER SET for this field.
  1391. * collation
  1392. * Text value with the default COLLATION for this field.
  1393. * unique
  1394. * unique constraint
  1395. * check
  1396. * column check constraint
  1397. * columnDefinition
  1398. * a string that defines the complete column
  1399. *
  1400. * @return string DBMS specific SQL code portion that should be used to declare the column.
  1401. */
  1402. public function getColumnDeclarationSQL($name, array $field)
  1403. {
  1404. if (isset($field['columnDefinition'])) {
  1405. $columnDef = $this->getCustomTypeDeclarationSQL($field);
  1406. } else {
  1407. $default = $this->getDefaultValueDeclarationSQL($field);
  1408. $charset = (isset($field['charset']) && $field['charset']) ?
  1409. ' ' . $this->getColumnCharsetDeclarationSQL($field['charset']) : '';
  1410. $collation = (isset($field['collation']) && $field['collation']) ?
  1411. ' ' . $this->getColumnCollationDeclarationSQL($field['collation']) : '';
  1412. $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : '';
  1413. $unique = (isset($field['unique']) && $field['unique']) ?
  1414. ' ' . $this->getUniqueFieldDeclarationSQL() : '';
  1415. $check = (isset($field['check']) && $field['check']) ?
  1416. ' ' . $field['check'] : '';
  1417. $typeDecl = $field['type']->getSqlDeclaration($field, $this);
  1418. $columnDef = $typeDecl . $charset . $default . $notnull . $unique . $check . $collation;
  1419. }
  1420. if ($this->supportsInlineColumnComments() && isset($field['comment']) && $field['comment']) {
  1421. $columnDef .= " COMMENT '" . $field['comment'] . "'";
  1422. }
  1423. return $name . ' ' . $columnDef;
  1424. }
  1425. /**
  1426. * Gets the SQL snippet that declares a floating point column of arbitrary precision.
  1427. *
  1428. * @param array $columnDef
  1429. * @return string
  1430. */
  1431. public function getDecimalTypeDeclarationSQL(array $columnDef)
  1432. {
  1433. $columnDef['precision'] = ( ! isset($columnDef['precision']) || empty($columnDef['precision']))
  1434. ? 10 : $columnDef['precision'];
  1435. $columnDef['scale'] = ( ! isset($columnDef['scale']) || empty($columnDef['scale']))
  1436. ? 0 : $columnDef['scale'];
  1437. return 'NUMERIC(' . $columnDef['precision'] . ', ' . $columnDef['scale'] . ')';
  1438. }
  1439. /**
  1440. * Obtain DBMS specific SQL code portion needed to set a default value
  1441. * declaration to be used in statements like CREATE TABLE.
  1442. *
  1443. * @param array $field field definition array
  1444. * @return string DBMS specific SQL code portion needed to set a default value
  1445. */
  1446. public function getDefaultValueDeclarationSQL($field)
  1447. {
  1448. $default = empty($field['notnull']) ? ' DEFAULT NULL' : '';
  1449. if (isset($field['default'])) {
  1450. $default = " DEFAULT '".$field['default']."'";
  1451. if (isset($field['type'])) {
  1452. if (in_array((string)$field['type'], array("Integer", "BigInteger", "SmallInteger"))) {
  1453. $default = " DEFAULT ".$field['default'];
  1454. } else if ((string)$field['type'] == 'DateTime' && $field['default'] == $this->getCurrentTimestampSQL()) {
  1455. $default = " DEFAULT ".$this->getCurrentTimestampSQL();
  1456. } else if ((string) $field['type'] == 'Boolean') {
  1457. $default = " DEFAULT '" . $this->convertBooleans($field['default']) . "'";
  1458. }
  1459. }
  1460. }
  1461. return $default;
  1462. }
  1463. /**
  1464. * Obtain DBMS specific SQL code portion needed to set a CHECK constraint
  1465. * declaration to be used in statements like CREATE TABLE.
  1466. *
  1467. * @param array $definition check definition
  1468. * @return string DBMS specific SQL code portion needed to set a CHECK constraint
  1469. */
  1470. public function getCheckDeclarationSQL(array $definition)
  1471. {
  1472. $constraints = array();
  1473. foreach ($definition as $field => $def) {
  1474. if (is_string($def)) {
  1475. $constraints[] = 'CHECK (' . $def . ')';
  1476. } else {
  1477. if (isset($def['min'])) {
  1478. $constraints[] = 'CHECK (' . $field . ' >= ' . $def['min'] . ')';
  1479. }
  1480. if (isset($def['max'])) {
  1481. $constraints[] = 'CHECK (' . $field . ' <= ' . $def['max'] . ')';
  1482. }
  1483. }
  1484. }
  1485. return implode(', ', $constraints);
  1486. }
  1487. /**
  1488. * Obtain DBMS specific SQL code portion needed to set a unique
  1489. * constraint declaration to be used in statements like CREATE TABLE.
  1490. *
  1491. * @param string $name name of the unique constraint
  1492. * @param Index $index index definition
  1493. * @return string DBMS specific SQL code portion needed
  1494. * to set a constraint
  1495. */
  1496. public function getUniqueConstraintDeclarationSQL($name, Index $index)
  1497. {
  1498. if (count($index->getColumns()) == 0) {
  1499. throw \InvalidArgumentException("Incomplete definition. 'columns' required.");
  1500. }
  1501. return 'CONSTRAINT ' . $name . ' UNIQUE ('
  1502. . $this->getIndexFieldDeclarationListSQL($index->getColumns())
  1503. . ')';
  1504. }
  1505. /**
  1506. * Obtain DBMS specific SQL code portion needed to set an index
  1507. * declaration to be used in statements like CREATE TABLE.
  1508. *
  1509. * @param string $name name of the index
  1510. * @param Index $index index definition
  1511. * @return string DBMS specific SQL code portion needed to set an index
  1512. */
  1513. public function getIndexDeclarationSQL($name, Index $index)
  1514. {
  1515. $type = '';
  1516. if($index->isUnique()) {
  1517. $type = 'UNIQUE ';
  1518. }
  1519. if (count($index->getColumns()) == 0) {
  1520. throw \InvalidArgumentException("Incomplete definition. 'columns' required.");
  1521. }
  1522. return $type . 'INDEX ' . $name . ' ('
  1523. . $this->getIndexFieldDeclarationListSQL($index->getColumns())
  1524. . ')';
  1525. }
  1526. /**
  1527. * getCustomTypeDeclarationSql
  1528. * Obtail SQL code portion needed to create a custom column,
  1529. * e.g. when a field has the "columnDefinition" keyword.
  1530. * Only "AUTOINCREMENT" and "PRIMARY KEY" are added if appropriate.
  1531. *
  1532. * @return string
  1533. */
  1534. public function getCustomTypeDeclarationSQL(array $columnDef)
  1535. {
  1536. return $columnDef['columnDefinition'];
  1537. }
  1538. /**
  1539. * getIndexFieldDeclarationList
  1540. * Obtain DBMS specific SQL code portion needed to set an index
  1541. * declaration to be used in statements like CREATE TABLE.
  1542. *
  1543. * @return string
  1544. */
  1545. public function getIndexFieldDeclarationListSQL(array $fields)
  1546. {
  1547. $ret = array();
  1548. foreach ($fields as $field => $definition) {
  1549. if (is_array($definition)) {
  1550. $ret[] = $field;
  1551. } else {
  1552. $ret[] = $definition;
  1553. }
  1554. }
  1555. return implode(', ', $ret);
  1556. }
  1557. /**
  1558. * A method to return the required SQL string that fits between CREATE ... TABLE
  1559. * to create the table as a temporary table.
  1560. *
  1561. * Should be overridden in driver classes to return the correct string for the
  1562. * specific database type.
  1563. *
  1564. * The default is to return the string "TEMPORARY" - this will result in a
  1565. * SQL error for any database that does not support temporary tables, or that
  1566. * requires a different SQL command from "CREATE TEMPORARY TABLE".
  1567. *
  1568. * @return string The string required to be placed between "CREATE" and "TABLE"
  1569. * to generate a temporary table, if possible.
  1570. */
  1571. public function getTemporaryTableSQL()
  1572. {
  1573. return 'TEMPORARY';
  1574. }
  1575. /**
  1576. * Some vendors require temporary table names to be qualified specially.
  1577. *
  1578. * @param string $tableName
  1579. * @return string
  1580. */
  1581. public function getTemporaryTableName($tableName)
  1582. {
  1583. return $tableName;
  1584. }
  1585. /**
  1586. * Get sql query to show a list of database.
  1587. *
  1588. * @return string
  1589. */
  1590. public function getShowDatabasesSQL()
  1591. {
  1592. throw DBALException::notSupported(__METHOD__);
  1593. }
  1594. /**
  1595. * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
  1596. * of a field declaration to be used in statements like CREATE TABLE.
  1597. *
  1598. * @param array $definition an associative array with the following structure:
  1599. * name optional constraint name
  1600. *
  1601. * local the local field(s)
  1602. *
  1603. * foreign the foreign reference field(s)
  1604. *
  1605. * foreignTable the name of the foreign table
  1606. *
  1607. * onDelete referential delete action
  1608. *
  1609. * onUpdate referential update action
  1610. *
  1611. * deferred deferred constraint checking
  1612. *
  1613. * The onDelete and onUpdate keys accept the following values:
  1614. *
  1615. * CASCADE: Delete or update the row from the parent table and automatically delete or
  1616. * update the matching rows in the child table. Both ON DELETE CASCADE and ON UPDATE CASCADE are supported.
  1617. * Between two tables, you should not define several ON UPDATE CASCADE clauses that act on the same column
  1618. * in the parent table or in the child table.
  1619. *
  1620. * SET NULL: Delete or update the row from the parent table and set the foreign key column or columns in the
  1621. * child table to NULL. This is valid only if the foreign key columns do not have the NOT NULL qualifier
  1622. * specified. Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are supported.
  1623. *
  1624. * NO ACTION: In standard SQL, NO ACTION means no action in the sense that an attempt to delete or update a primary
  1625. * key value is not allowed to proceed if there is a related foreign key value in the referenced table.
  1626. *
  1627. * RESTRICT: Rejects the delete or update operation for the parent table. NO ACTION and RESTRICT are the same as
  1628. * omitting the ON DELETE or ON UPDATE clause.
  1629. *
  1630. * SET DEFAULT
  1631. *
  1632. * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
  1633. * of a field declaration.
  1634. */
  1635. public function getForeignKeyDeclarationSQL(ForeignKeyConstraint $foreignKey)
  1636. {
  1637. $sql = $this->getForeignKeyBaseDeclarationSQL($foreignKey);
  1638. $sql .= $this->getAdvancedForeignKeyOptionsSQL($foreignKey);
  1639. return $sql;
  1640. }
  1641. /**
  1642. * Return the FOREIGN KEY query section dealing with non-standard options
  1643. * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
  1644. *
  1645. * @param ForeignKeyConstraint $foreignKey foreign key definition
  1646. * @return string
  1647. */
  1648. public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey)
  1649. {
  1650. $query = '';
  1651. if ($this->supportsForeignKeyOnUpdate() && $foreignKey->hasOption('onUpdate')) {
  1652. $query .= ' ON UPDATE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onUpdate'));
  1653. }
  1654. if ($foreignKey->hasOption('onDelete')) {
  1655. $query .= ' ON DELETE ' . $this->getForeignKeyReferentialActionSQL($foreignKey->getOption('onDelete'));
  1656. }
  1657. return $query;
  1658. }
  1659. /**
  1660. * returns given referential action in uppercase if valid, otherwise throws
  1661. * an exception
  1662. *
  1663. * @throws Doctrine_Exception_Exception if unknown referential action given
  1664. * @param string $action foreign key referential action
  1665. * @param string foreign key referential action in uppercase
  1666. */
  1667. public function getForeignKeyReferentialActionSQL($action)
  1668. {
  1669. $upper = strtoupper($action);
  1670. switch ($upper) {
  1671. case 'CASCADE':
  1672. case 'SET NULL':
  1673. case 'NO ACTION':
  1674. case 'RESTRICT':
  1675. case 'SET DEFAULT':
  1676. return $upper;
  1677. break;
  1678. default:
  1679. throw new \InvalidArgumentException('Invalid foreign key action: ' . $upper);
  1680. }
  1681. }
  1682. /**
  1683. * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint
  1684. * of a field declaration to be used in statements like CREATE TABLE.
  1685. *
  1686. * @param ForeignKeyConstraint $foreignKey
  1687. * @return string
  1688. */
  1689. public function getForeignKeyBaseDeclarationSQL(ForeignKeyConstraint $foreignKey)
  1690. {
  1691. $sql = '';
  1692. if (strlen($foreignKey->getName())) {
  1693. $sql .= 'CONSTRAINT ' . $foreignKey->getQuotedName($this) . ' ';
  1694. }
  1695. $sql .= 'FOREIGN KEY (';
  1696. if (count($foreignKey->getLocalColumns()) == 0) {
  1697. throw new \InvalidArgumentException("Incomplete definition. 'local' required.");
  1698. }
  1699. if (count($foreignKey->getForeignColumns()) == 0) {
  1700. throw new \InvalidArgumentException("Incomplete definition. 'foreign' required.");
  1701. }
  1702. if (strlen($foreignKey->getForeignTableName()) == 0) {
  1703. throw new \InvalidArgumentException("Incomplete definition. 'foreignTable' required.");
  1704. }
  1705. $sql .= implode(', ', $foreignKey->getLocalColumns())
  1706. . ') REFERENCES '
  1707. . $foreignKey->getForeignTableName() . ' ('
  1708. . implode(', ', $foreignKey->getForeignColumns()) . ')';
  1709. return $sql;
  1710. }
  1711. /**
  1712. * Obtain DBMS specific SQL code portion needed to set the UNIQUE constraint
  1713. * of a field declaration to be used in statements like CREATE TABLE.
  1714. *
  1715. * @return string DBMS specific SQL code portion needed to set the UNIQUE constraint
  1716. * of a field declaration.
  1717. */
  1718. public function getUniqueFieldDeclarationSQL()
  1719. {
  1720. return 'UNIQUE';
  1721. }
  1722. /**
  1723. * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET
  1724. * of a field declaration to be used in statements like CREATE TABLE.
  1725. *
  1726. * @param string $charset name of the charset
  1727. * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
  1728. * of a field declaration.
  1729. */
  1730. public function getColumnCharsetDeclarationSQL($charset)
  1731. {
  1732. return '';
  1733. }
  1734. /**
  1735. * Obtain DBMS specific SQL code portion needed to set the COLLATION
  1736. * of a field declaration to be used in statements like CREATE TABLE.
  1737. *
  1738. * @param string $collation name of the collation
  1739. * @return string DBMS specific SQL code portion needed to set the COLLATION
  1740. * of a field declaration.
  1741. */
  1742. public function getColumnCollationDeclarationSQL($collation)
  1743. {
  1744. return '';
  1745. }
  1746. /**
  1747. * Whether the platform prefers sequences for ID generation.
  1748. * Subclasses should override this method to return TRUE if they prefer sequences.
  1749. *
  1750. * @return boolean
  1751. */
  1752. public function prefersSequences()
  1753. {
  1754. return false;
  1755. }
  1756. /**
  1757. * Whether the platform prefers identity columns (eg. autoincrement) for ID generation.
  1758. * Subclasses should override this method to return TRUE if they prefer identity columns.
  1759. *
  1760. * @return boolean
  1761. */
  1762. public function prefersIdentityColumns()
  1763. {
  1764. return false;
  1765. }
  1766. /**
  1767. * Some platforms need the boolean values to be converted.
  1768. *
  1769. * The default conversion in this implementation converts to integers (false => 0, true => 1).
  1770. *
  1771. * @param mixed $item
  1772. */
  1773. public function convertBooleans($item)
  1774. {
  1775. if (is_array($item)) {
  1776. foreach ($item as $k => $value) {
  1777. if (is_bool($value)) {
  1778. $item[$k] = (int) $value;
  1779. }
  1780. }
  1781. } else if (is_bool($item)) {
  1782. $item = (int) $item;
  1783. }
  1784. return $item;
  1785. }
  1786. /**
  1787. * Gets the SQL statement specific for the platform to set the charset.
  1788. *
  1789. * This function is MySQL specific and required by
  1790. * {@see \Doctrine\DBAL\Connection::setCharset($charset)}
  1791. *
  1792. * @param string $charset
  1793. * @return string
  1794. */
  1795. public function getSetCharsetSQL($charset)
  1796. {
  1797. return "SET NAMES '".$charset."'";
  1798. }
  1799. /**
  1800. * Gets the SQL specific for the platform to get the current date.
  1801. *
  1802. * @return string
  1803. */
  1804. public function getCurrentDateSQL()
  1805. {
  1806. return 'CURRENT_DATE';
  1807. }
  1808. /**
  1809. * Gets the SQL specific for the platform to get the current time.
  1810. *
  1811. * @return string
  1812. */
  1813. public function getCurrentTimeSQL()
  1814. {
  1815. return 'CURRENT_TIME';
  1816. }
  1817. /**
  1818. * Gets the SQL specific for the platform to get the current timestamp
  1819. *
  1820. * @return string
  1821. */
  1822. public function getCurrentTimestampSQL()
  1823. {
  1824. return 'CURRENT_TIMESTAMP';
  1825. }
  1826. /**
  1827. * Get sql for transaction isolation level Connection constant
  1828. *
  1829. * @param integer $level
  1830. */
  1831. protected function _getTransactionIsolationLevelSQL($level)
  1832. {
  1833. switch ($level) {
  1834. case Connection::TRANSACTION_READ_UNCOMMITTED:
  1835. return 'READ UNCOMMITTED';
  1836. case Connection::TRANSACTION_READ_COMMITTED:
  1837. return 'READ COMMITTED';
  1838. case Connection::TRANSACTION_REPEATABLE_READ:
  1839. return 'REPEATABLE READ';
  1840. case Connection::TRANSACTION_SERIALIZABLE:
  1841. return 'SERIALIZABLE';
  1842. default:
  1843. throw new \InvalidArgumentException('Invalid isolation level:' . $level);
  1844. }
  1845. }
  1846. public function getListDatabasesSQL()
  1847. {
  1848. throw DBALException::notSupported(__METHOD__);
  1849. }
  1850. public function getListSequencesSQL($database)
  1851. {
  1852. throw DBALException::notSupported(__METHOD__);
  1853. }
  1854. public function getListTableConstraintsSQL($table)
  1855. {
  1856. throw DBALException::notSupported(__METHOD__);
  1857. }
  1858. public function getListTableColumnsSQL($table, $database = null)
  1859. {
  1860. throw DBALException::notSupported(__METHOD__);
  1861. }
  1862. public function getListTablesSQL()
  1863. {
  1864. throw DBALException::notSupported(__METHOD__);
  1865. }
  1866. public function getListUsersSQL()
  1867. {
  1868. throw DBALException::notSupported(__METHOD__);
  1869. }
  1870. /**
  1871. * Get the SQL to list all views of a database or user.
  1872. *
  1873. * @param string $database
  1874. * @return string
  1875. */
  1876. public function getListViewsSQL($database)
  1877. {
  1878. throw DBALException::notSupported(__METHOD__);
  1879. }
  1880. /**
  1881. * Get the list of indexes for the current database.
  1882. *
  1883. * The current database parameter is optional but will always be passed
  1884. * when using the SchemaManager API and is the database the given table is in.
  1885. *
  1886. * Attention: Some platforms only support currentDatabase when they
  1887. * are connected with that database. Cross-database information schema
  1888. * requests may be impossible.
  1889. *
  1890. * @param string $table
  1891. * @param string $currentDatabase
  1892. */
  1893. public function getListTableIndexesSQL($table, $currentDatabase = null)
  1894. {
  1895. throw DBALException::notSupported(__METHOD__);
  1896. }
  1897. public function getListTableForeignKeysSQL($table)
  1898. {
  1899. throw DBALException::notSupported(__METHOD__);
  1900. }
  1901. public function getCreateViewSQL($name, $sql)
  1902. {
  1903. throw DBALException::notSupported(__METHOD__);
  1904. }
  1905. public function getDropViewSQL($name)
  1906. {
  1907. throw DBALException::notSupported(__METHOD__);
  1908. }
  1909. public function getDropSequenceSQL($sequence)
  1910. {
  1911. throw DBALException::notSupported(__METHOD__);
  1912. }
  1913. public function getSequenceNextValSQL($sequenceName)
  1914. {
  1915. throw DBALException::notSupported(__METHOD__);
  1916. }
  1917. public function getCreateDatabaseSQL($database)
  1918. {
  1919. throw DBALException::notSupported(__METHOD__);
  1920. }
  1921. /**
  1922. * Get sql to set the transaction isolation level
  1923. *
  1924. * @param integer $level
  1925. */
  1926. public function getSetTransactionIsolationSQL($level)
  1927. {
  1928. throw DBALException::notSupported(__METHOD__);
  1929. }
  1930. /**
  1931. * Obtain DBMS specific SQL to be used to create datetime fields in
  1932. * statements like CREATE TABLE
  1933. *
  1934. * @param array $fieldDeclaration
  1935. * @return string
  1936. */
  1937. public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
  1938. {
  1939. throw DBALException::notSupported(__METHOD__);
  1940. }
  1941. /**
  1942. * Obtain DBMS specific SQL to be used to create datetime with timezone offset fields.
  1943. *
  1944. * @param array $fieldDeclaration
  1945. */
  1946. public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration)
  1947. {
  1948. return $this->getDateTimeTypeDeclarationSQL($fieldDeclaration);
  1949. }
  1950. /**
  1951. * Obtain DBMS specific SQL to be used to create date fields in statements
  1952. * like CREATE TABLE.
  1953. *
  1954. * @param array $fieldDeclaration
  1955. * @return string
  1956. */
  1957. public function getDateTypeDeclarationSQL(array $fieldDeclaration)
  1958. {
  1959. throw DBALException::notSupported(__METHOD__);
  1960. }
  1961. /**
  1962. * Obtain DBMS specific SQL to be used to create time fields in statements
  1963. * like CREATE TABLE.
  1964. *
  1965. * @param array $fieldDeclaration
  1966. * @return string
  1967. */
  1968. public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
  1969. {
  1970. throw DBALException::notSupported(__METHOD__);
  1971. }
  1972. public function getFloatDeclarationSQL(array $fieldDeclaration)
  1973. {
  1974. return 'DOUBLE PRECISION';
  1975. }
  1976. /**
  1977. * Gets the default transaction isolation level of the platform.
  1978. *
  1979. * @return integer The default isolation level.
  1980. * @see Doctrine\DBAL\Connection\TRANSACTION_* constants.
  1981. */
  1982. public function getDefaultTransactionIsolationLevel()
  1983. {
  1984. return Connection::TRANSACTION_READ_COMMITTED;
  1985. }
  1986. /* supports*() methods */
  1987. /**
  1988. * Whether the platform supports sequences.
  1989. *
  1990. * @return boolean
  1991. */
  1992. public function supportsSequences()
  1993. {
  1994. return false;
  1995. }
  1996. /**
  1997. * Whether the platform supports identity columns.
  1998. * Identity columns are columns that recieve an auto-generated value from the
  1999. * database on insert of a row.
  2000. *
  2001. * @return boolean
  2002. */
  2003. public function supportsIdentityColumns()
  2004. {
  2005. return false;
  2006. }
  2007. /**
  2008. * Whether the platform supports indexes.
  2009. *
  2010. * @return boolean
  2011. */
  2012. public function supportsIndexes()
  2013. {
  2014. return true;
  2015. }
  2016. public function supportsAlterTable()
  2017. {
  2018. return true;
  2019. }
  2020. /**
  2021. * Whether the platform supports transactions.
  2022. *
  2023. * @return boolean
  2024. */
  2025. public function supportsTransactions()
  2026. {
  2027. return true;
  2028. }
  2029. /**
  2030. * Whether the platform supports savepoints.
  2031. *
  2032. * @return boolean
  2033. */
  2034. public function supportsSavepoints()
  2035. {
  2036. return true;
  2037. }
  2038. /**
  2039. * Whether the platform supports releasing savepoints.
  2040. *
  2041. * @return boolean
  2042. */
  2043. public function supportsReleaseSavepoints()
  2044. {
  2045. return $this->supportsSavepoints();
  2046. }
  2047. /**
  2048. * Whether the platform supports primary key constraints.
  2049. *
  2050. * @return boolean
  2051. */
  2052. public function supportsPrimaryConstraints()
  2053. {
  2054. return true;
  2055. }
  2056. /**
  2057. * Does the platform supports foreign key constraints?
  2058. *
  2059. * @return boolean
  2060. */
  2061. public function supportsForeignKeyConstraints()
  2062. {
  2063. return true;
  2064. }
  2065. /**
  2066. * Does this platform supports onUpdate in foreign key constraints?
  2067. *
  2068. * @return bool
  2069. */
  2070. public function supportsForeignKeyOnUpdate()
  2071. {
  2072. return ($this->supportsForeignKeyConstraints() && true);
  2073. }
  2074. /**
  2075. * Whether the platform supports database schemas.
  2076. *
  2077. * @return boolean
  2078. */
  2079. public function supportsSchemas()
  2080. {
  2081. return false;
  2082. }
  2083. /**
  2084. * Can this platform emulate schemas?
  2085. *
  2086. * Platforms that either support or emulate schemas don't automatically
  2087. * filter a schema for the namespaced elements in {@link
  2088. * AbstractManager#createSchema}.
  2089. *
  2090. * @return bool
  2091. */
  2092. public function canEmulateSchemas()
  2093. {
  2094. return false;
  2095. }
  2096. /**
  2097. * Some databases don't allow to create and drop databases at all or only with certain tools.
  2098. *
  2099. * @return bool
  2100. */
  2101. public function supportsCreateDropDatabase()
  2102. {
  2103. return true;
  2104. }
  2105. /**
  2106. * Whether the platform supports getting the affected rows of a recent
  2107. * update/delete type query.
  2108. *
  2109. * @return boolean
  2110. */
  2111. public function supportsGettingAffectedRows()
  2112. {
  2113. return true;
  2114. }
  2115. /**
  2116. * Does this plaform support to add inline column comments as postfix.
  2117. *
  2118. * @return bool
  2119. */
  2120. public function supportsInlineColumnComments()
  2121. {
  2122. return false;
  2123. }
  2124. /**
  2125. * Does this platform support the propriortary synatx "COMMENT ON asset"
  2126. *
  2127. * @return bool
  2128. */
  2129. public function supportsCommentOnStatement()
  2130. {
  2131. return false;
  2132. }
  2133. public function getIdentityColumnNullInsertSQL()
  2134. {
  2135. return "";
  2136. }
  2137. /**
  2138. * Gets the format string, as accepted by the date() function, that describes
  2139. * the format of a stored datetime value of this platform.
  2140. *
  2141. * @return string The format string.
  2142. */
  2143. public function getDateTimeFormatString()
  2144. {
  2145. return 'Y-m-d H:i:s';
  2146. }
  2147. /**
  2148. * Gets the format string, as accepted by the date() function, that describes
  2149. * the format of a stored datetime with timezone value of this platform.
  2150. *
  2151. * @return string The format string.
  2152. */
  2153. public function getDateTimeTzFormatString()
  2154. {
  2155. return 'Y-m-d H:i:s';
  2156. }
  2157. /**
  2158. * Gets the format string, as accepted by the date() function, that describes
  2159. * the format of a stored date value of this platform.
  2160. *
  2161. * @return string The format string.
  2162. */
  2163. public function getDateFormatString()
  2164. {
  2165. return 'Y-m-d';
  2166. }
  2167. /**
  2168. * Gets the format string, as accepted by the date() function, that describes
  2169. * the format of a stored time value of this platform.
  2170. *
  2171. * @return string The format string.
  2172. */
  2173. public function getTimeFormatString()
  2174. {
  2175. return 'H:i:s';
  2176. }
  2177. /**
  2178. * Modify limit query
  2179. *
  2180. * @param string $query
  2181. * @param int $limit
  2182. * @param int $offset
  2183. * @return string
  2184. */
  2185. final public function modifyLimitQuery($query, $limit, $offset = null)
  2186. {
  2187. if ( $limit !== null) {
  2188. $limit = (int)$limit;
  2189. }
  2190. if ( $offset !== null) {
  2191. $offset = (int)$offset;
  2192. if ($offset < 0) {
  2193. throw new DBALException("LIMIT argument offset=$offset is not valid");
  2194. }
  2195. if ( $offset > 0 && ! $this->supportsLimitOffset()) {
  2196. throw new DBALException(sprintf("Platform %s does not support offset values in limit queries.", $this->getName()));
  2197. }
  2198. }
  2199. return $this->doModifyLimitQuery($query, $limit, $offset);
  2200. }
  2201. /**
  2202. * @param string $query
  2203. * @param int $limit
  2204. * @param int $offset
  2205. * @return string
  2206. */
  2207. protected function doModifyLimitQuery($query, $limit, $offset)
  2208. {
  2209. if ( $limit !== null) {
  2210. $query .= ' LIMIT ' . $limit;
  2211. }
  2212. if ( $offset !== null) {
  2213. $query .= ' OFFSET ' . $offset;
  2214. }
  2215. return $query;
  2216. }
  2217. /**
  2218. * Does the database platform support offsets in modify limit clauses?
  2219. *
  2220. * @return bool
  2221. */
  2222. public function supportsLimitOffset()
  2223. {
  2224. return true;
  2225. }
  2226. /**
  2227. * Gets the character casing of a column in an SQL result set of this platform.
  2228. *
  2229. * @param string $column The column name for which to get the correct character casing.
  2230. * @return string The column name in the character casing used in SQL result sets.
  2231. */
  2232. public function getSQLResultCasing($column)
  2233. {
  2234. return $column;
  2235. }
  2236. /**
  2237. * Makes any fixes to a name of a schema element (table, sequence, ...) that are required
  2238. * by restrictions of the platform, like a maximum length.
  2239. *
  2240. * @param string $schemaName
  2241. * @return string
  2242. */
  2243. public function fixSchemaElementName($schemaElementName)
  2244. {
  2245. return $schemaElementName;
  2246. }
  2247. /**
  2248. * Maximum length of any given databse identifier, like tables or column names.
  2249. *
  2250. * @return int
  2251. */
  2252. public function getMaxIdentifierLength()
  2253. {
  2254. return 63;
  2255. }
  2256. /**
  2257. * Get the insert sql for an empty insert statement
  2258. *
  2259. * @param string $tableName
  2260. * @param string $identifierColumnName
  2261. * @return string $sql
  2262. */
  2263. public function getEmptyIdentityInsertSQL($tableName, $identifierColumnName)
  2264. {
  2265. return 'INSERT INTO ' . $tableName . ' (' . $identifierColumnName . ') VALUES (null)';
  2266. }
  2267. /**
  2268. * Generate a Truncate Table SQL statement for a given table.
  2269. *
  2270. * Cascade is not supported on many platforms but would optionally cascade the truncate by
  2271. * following the foreign keys.
  2272. *
  2273. * @param string $tableName
  2274. * @param bool $cascade
  2275. * @return string
  2276. */
  2277. public function getTruncateTableSQL($tableName, $cascade = false)
  2278. {
  2279. return 'TRUNCATE '.$tableName;
  2280. }
  2281. /**
  2282. * This is for test reasons, many vendors have special requirements for dummy statements.
  2283. *
  2284. * @return string
  2285. */
  2286. public function getDummySelectSQL()
  2287. {
  2288. return 'SELECT 1';
  2289. }
  2290. /**
  2291. * Generate SQL to create a new savepoint
  2292. *
  2293. * @param string $savepoint
  2294. * @return string
  2295. */
  2296. public function createSavePoint($savepoint)
  2297. {
  2298. return 'SAVEPOINT ' . $savepoint;
  2299. }
  2300. /**
  2301. * Generate SQL to release a savepoint
  2302. *
  2303. * @param string $savepoint
  2304. * @return string
  2305. */
  2306. public function releaseSavePoint($savepoint)
  2307. {
  2308. return 'RELEASE SAVEPOINT ' . $savepoint;
  2309. }
  2310. /**
  2311. * Generate SQL to rollback a savepoint
  2312. *
  2313. * @param string $savepoint
  2314. * @return string
  2315. */
  2316. public function rollbackSavePoint($savepoint)
  2317. {
  2318. return 'ROLLBACK TO SAVEPOINT ' . $savepoint;
  2319. }
  2320. /**
  2321. * Return the keyword list instance of this platform.
  2322. *
  2323. * Throws exception if no keyword list is specified.
  2324. *
  2325. * @throws DBALException
  2326. * @return KeywordList
  2327. */
  2328. final public function getReservedKeywordsList()
  2329. {
  2330. $class = $this->getReservedKeywordsClass();
  2331. $keywords = new $class;
  2332. if (!$keywords instanceof \Doctrine\DBAL\Platforms\Keywords\KeywordList) {
  2333. throw DBALException::notSupported(__METHOD__);
  2334. }
  2335. return $keywords;
  2336. }
  2337. /**
  2338. * The class name of the reserved keywords list.
  2339. *
  2340. * @return string
  2341. */
  2342. protected function getReservedKeywordsClass()
  2343. {
  2344. throw DBALException::notSupported(__METHOD__);
  2345. }
  2346. }