mirror of
https://github.com/simonw/sqlite-utils.git
synced 2026-07-23 09:24:31 +02:00
ignore=True argument for add_foreign_key, closes #112
Also --ignore for add-foreign-key command Plus table.add_foreign_key(...) now returns self, allowing more chaining
This commit is contained in:
parent
ecb50c8f76
commit
e23eedb4ce
6 changed files with 48 additions and 9 deletions
|
|
@ -308,7 +308,12 @@ def add_column(path, table, col_name, col_type, fk, fk_col, not_null_default):
|
|||
@click.argument("column")
|
||||
@click.argument("other_table", required=False)
|
||||
@click.argument("other_column", required=False)
|
||||
def add_foreign_key(path, table, column, other_table, other_column):
|
||||
@click.option(
|
||||
"--ignore",
|
||||
is_flag=True,
|
||||
help="If foreign key already exists, do nothing",
|
||||
)
|
||||
def add_foreign_key(path, table, column, other_table, other_column, ignore):
|
||||
"""
|
||||
Add a new foreign key constraint to an existing table. Example usage:
|
||||
|
||||
|
|
@ -318,7 +323,7 @@ def add_foreign_key(path, table, column, other_table, other_column):
|
|||
"""
|
||||
db = sqlite_utils.Database(path)
|
||||
try:
|
||||
db[table].add_foreign_key(column, other_table, other_column)
|
||||
db[table].add_foreign_key(column, other_table, other_column, ignore=ignore)
|
||||
except AlterError as e:
|
||||
raise click.ClickException(e)
|
||||
|
||||
|
|
|
|||
|
|
@ -781,7 +781,9 @@ class Table(Queryable):
|
|||
else:
|
||||
return pks[0].name
|
||||
|
||||
def add_foreign_key(self, column, other_table=None, other_column=None):
|
||||
def add_foreign_key(
|
||||
self, column, other_table=None, other_column=None, ignore=False
|
||||
):
|
||||
# Ensure column exists
|
||||
if column not in self.columns_dict:
|
||||
raise AlterError("No such column: {}".format(column))
|
||||
|
|
@ -806,12 +808,16 @@ class Table(Queryable):
|
|||
and fk.other_table == other_table
|
||||
and fk.other_column == other_column
|
||||
):
|
||||
raise AlterError(
|
||||
"Foreign key already exists for {} => {}.{}".format(
|
||||
column, other_table, other_column
|
||||
if ignore:
|
||||
return self
|
||||
else:
|
||||
raise AlterError(
|
||||
"Foreign key already exists for {} => {}.{}".format(
|
||||
column, other_table, other_column
|
||||
)
|
||||
)
|
||||
)
|
||||
self.db.add_foreign_keys([(self.name, column, other_table, other_column)])
|
||||
return self
|
||||
|
||||
def enable_fts(
|
||||
self,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue