Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ColumnSchemaBuilder.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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 integer|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 boolean|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 = null;
  43. /**
  44. * @var boolean 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 boolean 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 boolean 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 integer|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 schema string.
  243. * @param string $sql the SQL string to be appended.
  244. * @return $this
  245. * @since 2.0.9
  246. */
  247. public function append($sql)
  248. {
  249. $this->append = $sql;
  250. return $this;
  251. }
  252. /**
  253. * Builds the full string for the column's schema
  254. * @return string
  255. */
  256. public function __toString()
  257. {
  258. switch ($this->getTypeCategory()) {
  259. case self::CATEGORY_PK:
  260. $format = '{type}{check}{comment}{append}';
  261. break;
  262. default:
  263. $format = '{type}{length}{notnull}{unique}{default}{check}{comment}{append}';
  264. }
  265. return $this->buildCompleteString($format);
  266. }
  267. /**
  268. * Builds the length/precision part of the column.
  269. * @return string
  270. */
  271. protected function buildLengthString()
  272. {
  273. if ($this->length === null || $this->length === []) {
  274. return '';
  275. }
  276. if (is_array($this->length)) {
  277. $this->length = implode(',', $this->length);
  278. }
  279. return "({$this->length})";
  280. }
  281. /**
  282. * Builds the not null constraint for the column.
  283. * @return string returns 'NOT NULL' if [[isNotNull]] is true,
  284. * 'NULL' if [[isNotNull]] is false or an empty string otherwise.
  285. */
  286. protected function buildNotNullString()
  287. {
  288. if ($this->isNotNull === true) {
  289. return ' NOT NULL';
  290. } elseif ($this->isNotNull === false) {
  291. return ' NULL';
  292. } else {
  293. return '';
  294. }
  295. }
  296. /**
  297. * Builds the unique constraint for the column.
  298. * @return string returns string 'UNIQUE' if [[isUnique]] is true, otherwise it returns an empty string.
  299. */
  300. protected function buildUniqueString()
  301. {
  302. return $this->isUnique ? ' UNIQUE' : '';
  303. }
  304. /**
  305. * Builds the default value specification for the column.
  306. * @return string string with default value of column.
  307. */
  308. protected function buildDefaultString()
  309. {
  310. if ($this->default === null) {
  311. return $this->isNotNull === false ? ' DEFAULT NULL' : '';
  312. }
  313. $string = ' DEFAULT ';
  314. switch (gettype($this->default)) {
  315. case 'integer':
  316. $string .= (string) $this->default;
  317. break;
  318. case 'double':
  319. // ensure type cast always has . as decimal separator in all locales
  320. $string .= str_replace(',', '.', (string) $this->default);
  321. break;
  322. case 'boolean':
  323. $string .= $this->default ? 'TRUE' : 'FALSE';
  324. break;
  325. case 'object':
  326. $string .= (string) $this->default;
  327. break;
  328. default:
  329. $string .= "'{$this->default}'";
  330. }
  331. return $string;
  332. }
  333. /**
  334. * Builds the check constraint for the column.
  335. * @return string a string containing the CHECK constraint.
  336. */
  337. protected function buildCheckString()
  338. {
  339. return $this->check !== null ? " CHECK ({$this->check})" : '';
  340. }
  341. /**
  342. * Builds the unsigned string for column. Defaults to unsupported.
  343. * @return string a string containing UNSIGNED keyword.
  344. * @since 2.0.7
  345. */
  346. protected function buildUnsignedString()
  347. {
  348. return '';
  349. }
  350. /**
  351. * Builds the after constraint for the column. Defaults to unsupported.
  352. * @return string a string containing the AFTER constraint.
  353. * @since 2.0.8
  354. */
  355. protected function buildAfterString()
  356. {
  357. return '';
  358. }
  359. /**
  360. * Builds the first constraint for the column. Defaults to unsupported.
  361. * @return string a string containing the FIRST constraint.
  362. * @since 2.0.8
  363. */
  364. protected function buildFirstString()
  365. {
  366. return '';
  367. }
  368. /**
  369. * Builds the custom string that's appended to column definition.
  370. * @return string custom string to append.
  371. * @since 2.0.9
  372. */
  373. protected function buildAppendString()
  374. {
  375. return $this->append !== null ? ' ' . $this->append : '';
  376. }
  377. /**
  378. * Returns the category of the column type.
  379. * @return string a string containing the column type category name.
  380. * @since 2.0.8
  381. */
  382. protected function getTypeCategory()
  383. {
  384. return isset($this->categoryMap[$this->type]) ? $this->categoryMap[$this->type] : null;
  385. }
  386. /**
  387. * Builds the comment specification for the column.
  388. * @return string a string containing the COMMENT keyword and the comment itself
  389. * @since 2.0.8
  390. */
  391. protected function buildCommentString()
  392. {
  393. return '';
  394. }
  395. /**
  396. * Returns the complete column definition from input format
  397. * @param string $format the format of the definition.
  398. * @return string a string containing the complete column definition.
  399. * @since 2.0.8
  400. */
  401. protected function buildCompleteString($format)
  402. {
  403. $placeholderValues = [
  404. '{type}' => $this->type,
  405. '{length}' => $this->buildLengthString(),
  406. '{unsigned}' => $this->buildUnsignedString(),
  407. '{notnull}' => $this->buildNotNullString(),
  408. '{unique}' => $this->buildUniqueString(),
  409. '{default}' => $this->buildDefaultString(),
  410. '{check}' => $this->buildCheckString(),
  411. '{comment}' => $this->buildCommentString(),
  412. '{pos}' => $this->isFirst ? $this->buildFirstString() : $this->buildAfterString(),
  413. '{append}' => $this->buildAppendString(),
  414. ];
  415. return strtr($format, $placeholderValues);
  416. }
  417. }