From 4a10c4b50d389b7353a9124d72e0fc7116575cd0 Mon Sep 17 00:00:00 2001 From: twinh Date: Sun, 12 Apr 2020 18:39:56 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20schema=20=E5=A2=9E=E5=8A=A0=20defaultNu?= =?UTF-8?q?llable=20=E9=80=89=E9=A1=B9=EF=BC=8C=E6=8E=A7=E5=88=B6=E6=98=AF?= =?UTF-8?q?=E5=90=A6=E9=BB=98=E8=AE=A4=E4=B8=BA=20null?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/Schema.php | 25 ++++++++++++++++++++++++- tests/unit/SchemaTest.php | 23 +++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/lib/Schema.php b/lib/Schema.php index 233a36f0a..6152918ad 100644 --- a/lib/Schema.php +++ b/lib/Schema.php @@ -76,6 +76,11 @@ class Schema extends Base */ protected $autoUnsigned = true; + /** + * @var bool + */ + protected $defaultNullable = false; + /** * @var string */ @@ -398,6 +403,24 @@ protected function getColumnSql($column, array $options) return $sql . $this->buildColumnSql($column, $options); } + /** + * @param bool $defaultNullable + * @return $this + */ + public function setDefaultNullable($defaultNullable) + { + $this->defaultNullable = (bool) $defaultNullable; + return $this; + } + + /** + * @return bool + */ + public function getDefaultNullable() + { + return $this->defaultNullable; + } + /** * @param string $column * @param array $options @@ -407,7 +430,7 @@ protected function buildColumnSql($column, array $options) { $sql = $column . ' ' . $this->getTypeSql($options) . ' '; $sql .= $this->getUnsignedSql($options); - $sql .= $this->getNullSql(isset($options['nullable']) ? $options['nullable'] : false); + $sql .= $this->getNullSql(isset($options['nullable']) ? $options['nullable'] : $this->defaultNullable); // Auto increment do not have default value if ($this->autoIncrement == $column) { diff --git a/tests/unit/SchemaTest.php b/tests/unit/SchemaTest.php index b12551134..a5f239f98 100644 --- a/tests/unit/SchemaTest.php +++ b/tests/unit/SchemaTest.php @@ -185,6 +185,29 @@ public function testNullable() ) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", $sql); } + public function testDefaultNullable() + { + $schema = wei()->schema; + + $schema->setDefaultNullable(true); + + $sql = $schema->table('test') + ->string('id') + ->getSql(); + $this->assertEquals("CREATE TABLE test ( + id varchar(255) NULL DEFAULT '' +) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", $sql); + + $schema->setDefaultNullable(false); + + $sql = $schema->table('test') + ->string('id') + ->getSql(); + $this->assertEquals("CREATE TABLE test ( + id varchar(255) NOT NULL DEFAULT '' +) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", $sql); + } + protected function createTestTable() { $this->schema->dropIfExists('test_products');