Skip to content

Commit

Permalink
feat: schema 增加 defaultNullable 选项,控制是否默认为 null
Browse files Browse the repository at this point in the history
  • Loading branch information
twinh committed Apr 12, 2020
1 parent 1472874 commit 4a10c4b
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
25 changes: 24 additions & 1 deletion lib/Schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ class Schema extends Base
*/
protected $autoUnsigned = true;

/**
* @var bool
*/
protected $defaultNullable = false;

/**
* @var string
*/
Expand Down Expand Up @@ -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
Expand All @@ -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) {
Expand Down
23 changes: 23 additions & 0 deletions tests/unit/SchemaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down

0 comments on commit 4a10c4b

Please sign in to comment.