ColumnSchemaBuilder.php 14 KB

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