Skip to content

Commit

Permalink
Preserve and handle CHECK() constraints with sqlite migrator.
Browse files Browse the repository at this point in the history
Fixes #2343
  • Loading branch information
coleifer committed Feb 7, 2021
1 parent b34e601 commit 7e68c78
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
2 changes: 1 addition & 1 deletion playhouse/migrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,7 @@ def _update_column(self, table, column_to_update, fn):
new_column_defs = []
new_column_names = []
original_column_names = []
constraint_terms = ('foreign ', 'primary ', 'constraint ')
constraint_terms = ('foreign ', 'primary ', 'constraint ', 'check ')

for column_def in column_defs:
column_name, = self.column_name_re.match(column_def).groups()
Expand Down
38 changes: 36 additions & 2 deletions tests/migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -877,11 +877,45 @@ class Meta:
SQL('CONSTRAINT const2 UNIQUE (foreign_data)')]


class HasChecks(TestModel):
key = TextField()
value = IntegerField()
class Meta:
constraints = [
SQL("CHECK (key != '')"),
SQL('CHECK (value > 0)')]


class TestSqliteColumnNameRegression(ModelTestCase):
database = get_in_memory_db()
requires = [BadNames]
requires = [BadNames, HasChecks]

def test_sqlite_check_constraints(self):
HasChecks.create(key='k1', value=1)

migrator = SchemaMigrator.from_database(self.database)
extra = TextField(default='')
migrate(migrator.add_column('has_checks', 'extra', extra))

columns = self.database.get_columns('has_checks')
self.assertEqual([c.name for c in columns],
['id', 'key', 'value', 'extra'])

HC = Table('has_checks', ('id', 'key', 'value', 'extra'))
HC = HC.bind(self.database)

# Sanity-check: ensure we can create a new row.
data = {'key': 'k2', 'value': 2, 'extra': 'x2'}
self.assertTrue(HC.insert(data).execute())

# Check constraints preserved.
data = {'key': 'k0', 'value': 0, 'extra': 'x0'}
self.assertRaises(IntegrityError, HC.insert(data).execute)

data = {'key': '', 'value': 3, 'extra': 'x3'}
self.assertRaises(IntegrityError, HC.insert(data).execute)

def test_sqlite_column_name_regression(self):
def test_sqlite_column_name_constraint_regression(self):
BadNames.create(primary_data='pd', foreign_data='fd', data='d')

migrator = SchemaMigrator.from_database(self.database)
Expand Down

0 comments on commit 7e68c78

Please sign in to comment.