ColumnSchemaBuilder.php 13 KB

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