ColumnSchemaBuilder.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\db;
  8. use Yii;
  9. use yii\base\Object;
  10. /**
  11. * ColumnSchemaBuilder helps to define database schema types using a PHP interface.
  12. *
  13. * See [[SchemaBuilderTrait]] for more detailed description and usage examples.
  14. *
  15. * @author Vasenin Matvey <vaseninm@gmail.com>
  16. * @since 2.0.6
  17. */
  18. class ColumnSchemaBuilder extends Object
  19. {
  20. // Internally used constants representing categories that abstract column types fall under.
  21. // See [[$categoryMap]] for mappings of abstract column types to category.
  22. // @since 2.0.8
  23. const CATEGORY_PK = 'pk';
  24. const CATEGORY_STRING = 'string';
  25. const CATEGORY_NUMERIC = 'numeric';
  26. const CATEGORY_TIME = 'time';
  27. const CATEGORY_OTHER = 'other';
  28. /**
  29. * @var string the column type definition such as INTEGER, VARCHAR, DATETIME, etc.
  30. */
  31. protected $type;
  32. /**
  33. * @var int|string|array column size or precision definition. This is what goes into the parenthesis after
  34. * the column type. This can be either a string, an integer or an array. If it is an array, the array values will
  35. * be joined into a string separated by comma.
  36. */
  37. protected $length;
  38. /**
  39. * @var bool|null whether the column is or not nullable. If this is `true`, a `NOT NULL` constraint will be added.
  40. * If this is `false`, a `NULL` constraint will be added.
  41. */
  42. protected $isNotNull;
  43. /**
  44. * @var bool whether the column values should be unique. If this is `true`, a `UNIQUE` constraint will be added.
  45. */
  46. protected $isUnique = false;
  47. /**
  48. * @var string the `CHECK` constraint for the column.
  49. */
  50. protected $check;
  51. /**
  52. * @var mixed default value of the column.
  53. */
  54. protected $default;
  55. /**
  56. * @var mixed SQL string to be appended to column schema definition.
  57. * @since 2.0.9
  58. */
  59. protected $append;
  60. /**
  61. * @var bool whether the column values should be unsigned. If this is `true`, an `UNSIGNED` keyword will be added.
  62. * @since 2.0.7
  63. */
  64. protected $isUnsigned = false;
  65. /**
  66. * @var string the column after which this column will be added.
  67. * @since 2.0.8
  68. */
  69. protected $after;
  70. /**
  71. * @var bool whether this column is to be inserted at the beginning of the table.
  72. * @since 2.0.8
  73. */
  74. protected $isFirst;
  75. /**
  76. * @var array mapping of abstract column types (keys) to type categories (values).
  77. * @since 2.0.8
  78. */
  79. public $categoryMap = [
  80. Schema::TYPE_PK => self::CATEGORY_PK,
  81. Schema::TYPE_UPK => self::CATEGORY_PK,
  82. Schema::TYPE_BIGPK => self::CATEGORY_PK,
  83. Schema::TYPE_UBIGPK => self::CATEGORY_PK,
  84. Schema::TYPE_CHAR => self::CATEGORY_STRING,
  85. Schema::TYPE_STRING => self::CATEGORY_STRING,
  86. Schema::TYPE_TEXT => self::CATEGORY_STRING,
  87. Schema::TYPE_SMALLINT => self::CATEGORY_NUMERIC,
  88. Schema::TYPE_INTEGER => self::CATEGORY_NUMERIC,
  89. Schema::TYPE_BIGINT => self::CATEGORY_NUMERIC,
  90. Schema::TYPE_FLOAT => self::CATEGORY_NUMERIC,
  91. Schema::TYPE_DOUBLE => self::CATEGORY_NUMERIC,
  92. Schema::TYPE_DECIMAL => self::CATEGORY_NUMERIC,
  93. Schema::TYPE_DATETIME => self::CATEGORY_TIME,
  94. Schema::TYPE_TIMESTAMP => self::CATEGORY_TIME,
  95. Schema::TYPE_TIME => self::CATEGORY_TIME,
  96. Schema::TYPE_DATE => self::CATEGORY_TIME,
  97. Schema::TYPE_BINARY => self::CATEGORY_OTHER,
  98. Schema::TYPE_BOOLEAN => self::CATEGORY_NUMERIC,
  99. Schema::TYPE_MONEY => self::CATEGORY_NUMERIC,
  100. ];
  101. /**
  102. * @var \yii\db\Connection the current database connection. It is used mainly to escape strings
  103. * safely when building the final column schema string.
  104. * @since 2.0.8
  105. */
  106. public $db;
  107. /**
  108. * @var string comment value of the column.
  109. * @since 2.0.8
  110. */
  111. public $comment;
  112. /**
  113. * Create a column schema builder instance giving the type and value precision.
  114. *
  115. * @param string $type type of the column. See [[$type]].
  116. * @param int|string|array $length length or precision of the column. See [[$length]].
  117. * @param \yii\db\Connection $db the current database connection. See [[$db]].
  118. * @param array $config name-value pairs that will be used to initialize the object properties
  119. */
  120. public function __construct($type, $length = null, $db = null, $config = [])
  121. {
  122. $this->type = $type;
  123. $this->length = $length;
  124. $this->db = $db;
  125. parent::__construct($config);
  126. }
  127. /**
  128. * Adds a `NOT NULL` constraint to the column.
  129. * @return $this
  130. */
  131. public function notNull()
  132. {
  133. $this->isNotNull = true;
  134. return $this;
  135. }
  136. /**
  137. * Adds a `NULL` constraint to the column
  138. * @return $this
  139. * @since 2.0.9
  140. */
  141. public function null()
  142. {
  143. $this->isNotNull = false;
  144. return $this;
  145. }
  146. /**
  147. * Adds a `UNIQUE` constraint to the column.
  148. * @return $this
  149. */
  150. public function unique()
  151. {
  152. $this->isUnique = true;
  153. return $this;
  154. }
  155. /**
  156. * Sets a `CHECK` constraint for the column.
  157. * @param string $check the SQL of the `CHECK` constraint to be added.
  158. * @return $this
  159. */
  160. public function check($check)
  161. {
  162. $this->check = $check;
  163. return $this;
  164. }
  165. /**
  166. * Specify the default value for the column.
  167. * @param mixed $default the default value.
  168. * @return $this
  169. */
  170. public function defaultValue($default)
  171. {
  172. if ($default === null) {
  173. $this->null();
  174. }
  175. $this->default = $default;
  176. return $this;
  177. }
  178. /**
  179. * Specifies the comment for column.
  180. * @param string $comment the comment
  181. * @return $this
  182. * @since 2.0.8
  183. */
  184. public function comment($comment)
  185. {
  186. $this->comment = $comment;
  187. return $this;
  188. }
  189. /**
  190. * Marks column as unsigned.
  191. * @return $this
  192. * @since 2.0.7
  193. */
  194. public function unsigned()
  195. {
  196. switch ($this->type) {
  197. case Schema::TYPE_PK:
  198. $this->type = Schema::TYPE_UPK;
  199. break;
  200. case Schema::TYPE_BIGPK:
  201. $this->type = Schema::TYPE_UBIGPK;
  202. break;
  203. }
  204. $this->isUnsigned = true;
  205. return $this;
  206. }
  207. /**
  208. * Adds an `AFTER` constraint to the column.
  209. * Note: MySQL, Oracle and Cubrid support only.
  210. * @param string $after the column after which $this column will be added.
  211. * @return $this
  212. * @since 2.0.8
  213. */
  214. public function after($after)
  215. {
  216. $this->after = $after;
  217. return $this;
  218. }
  219. /**
  220. * Adds an `FIRST` constraint to the column.
  221. * Note: MySQL, Oracle and Cubrid support only.
  222. * @return $this
  223. * @since 2.0.8
  224. */
  225. public function first()
  226. {
  227. $this->isFirst = true;
  228. return $this;
  229. }
  230. /**
  231. * Specify the default SQL expression for the column.
  232. * @param string $default the default value expression.
  233. * @return $this
  234. * @since 2.0.7
  235. */
  236. public function defaultExpression($default)
  237. {
  238. $this->default = new Expression($default);
  239. return $this;
  240. }
  241. /**
  242. * Specify additional SQL to be appended to column definition.
  243. * Position modifiers will be appended after column definition in databases that support them.
  244. * @param string $sql the SQL string to be appended.
  245. * @return $this
  246. * @since 2.0.9
  247. */
  248. public function append($sql)
  249. {
  250. $this->append = $sql;
  251. return $this;
  252. }
  253. /**
  254. * Builds the full string for the column's schema
  255. * @return string
  256. */
  257. public function __toString()
  258. {
  259. switch ($this->getTypeCategory()) {
  260. case self::CATEGORY_PK:
  261. $format = '{type}{check}{comment}{append}';
  262. break;
  263. default:
  264. $format = '{type}{length}{notnull}{unique}{default}{check}{comment}{append}';
  265. }
  266. return $this->buildCompleteString($format);
  267. }
  268. /**
  269. * Builds the length/precision part of the column.
  270. * @return string
  271. */
  272. protected function buildLengthString()
  273. {
  274. if ($this->length === null || $this->length === []) {
  275. return '';
  276. }
  277. if (is_array($this->length)) {
  278. $this->length = implode(',', $this->length);
  279. }
  280. return "({$this->length})";
  281. }
  282. /**
  283. * Builds the not null constraint for the column.
  284. * @return string returns 'NOT NULL' if [[isNotNull]] is true,
  285. * 'NULL' if [[isNotNull]] is false or an empty string otherwise.
  286. */
  287. protected function buildNotNullString()
  288. {
  289. if ($this->isNotNull === true) {
  290. return ' NOT NULL';
  291. } elseif ($this->isNotNull === false) {
  292. return ' NULL';
  293. } else {
  294. return '';
  295. }
  296. }
  297. /**
  298. * Builds the unique constraint for the column.
  299. * @return string returns string 'UNIQUE' if [[isUnique]] is true, otherwise it returns an empty string.
  300. */
  301. protected function buildUniqueString()
  302. {
  303. return $this->isUnique ? ' UNIQUE' : '';
  304. }
  305. /**
  306. * Builds the default value specification for the column.
  307. * @return string string with default value of column.
  308. */
  309. protected function buildDefaultString()
  310. {
  311. if ($this->default === null) {
  312. return $this->isNotNull === false ? ' DEFAULT NULL' : '';
  313. }
  314. $string = ' DEFAULT ';
  315. switch (gettype($this->default)) {
  316. case 'integer':
  317. $string .= (string) $this->default;
  318. break;
  319. case 'double':
  320. // ensure type cast always has . as decimal separator in all locales
  321. $string .= str_replace(',', '.', (string) $this->default);
  322. break;
  323. case 'boolean':
  324. $string .= $this->default ? 'TRUE' : 'FALSE';
  325. break;
  326. case 'object':
  327. $string .= (string) $this->default;
  328. break;
  329. default:
  330. $string .= "'{$this->default}'";
  331. }
  332. return $string;
  333. }
  334. /**
  335. * Builds the check constraint for the column.
  336. * @return string a string containing the CHECK constraint.
  337. */
  338. protected function buildCheckString()
  339. {
  340. return $this->check !== null ? " CHECK ({$this->check})" : '';
  341. }
  342. /**
  343. * Builds the unsigned string for column. Defaults to unsupported.
  344. * @return string a string containing UNSIGNED keyword.
  345. * @since 2.0.7
  346. */
  347. protected function buildUnsignedString()
  348. {
  349. return '';
  350. }
  351. /**
  352. * Builds the after constraint for the column. Defaults to unsupported.
  353. * @return string a string containing the AFTER constraint.
  354. * @since 2.0.8
  355. */
  356. protected function buildAfterString()
  357. {
  358. return '';
  359. }
  360. /**
  361. * Builds the first constraint for the column. Defaults to unsupported.
  362. * @return string a string containing the FIRST constraint.
  363. * @since 2.0.8
  364. */
  365. protected function buildFirstString()
  366. {
  367. return '';
  368. }
  369. /**
  370. * Builds the custom string that's appended to column definition.
  371. * @return string custom string to append.
  372. * @since 2.0.9
  373. */
  374. protected function buildAppendString()
  375. {
  376. return $this->append !== null ? ' ' . $this->append : '';
  377. }
  378. /**
  379. * Returns the category of the column type.
  380. * @return string a string containing the column type category name.
  381. * @since 2.0.8
  382. */
  383. protected function getTypeCategory()
  384. {
  385. return isset($this->categoryMap[$this->type]) ? $this->categoryMap[$this->type] : null;
  386. }
  387. /**
  388. * Builds the comment specification for the column.
  389. * @return string a string containing the COMMENT keyword and the comment itself
  390. * @since 2.0.8
  391. */
  392. protected function buildCommentString()
  393. {
  394. return '';
  395. }
  396. /**
  397. * Returns the complete column definition from input format
  398. * @param string $format the format of the definition.
  399. * @return string a string containing the complete column definition.
  400. * @since 2.0.8
  401. */
  402. protected function buildCompleteString($format)
  403. {
  404. $placeholderValues = [
  405. '{type}' => $this->type,
  406. '{length}' => $this->buildLengthString(),
  407. '{unsigned}' => $this->buildUnsignedString(),
  408. '{notnull}' => $this->buildNotNullString(),
  409. '{unique}' => $this->buildUniqueString(),
  410. '{default}' => $this->buildDefaultString(),
  411. '{check}' => $this->buildCheckString(),
  412. '{comment}' => $this->buildCommentString(),
  413. '{pos}' => $this->isFirst ? $this->buildFirstString() : $this->buildAfterString(),
  414. '{append}' => $this->buildAppendString(),
  415. ];
  416. return strtr($format, $placeholderValues);
  417. }
  418. }