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
|
|
@ -272,16 +272,24 @@ def test_add_foreign_key(db_path, args, assert_message):
|
|||
table="books", column="author_id", other_table="authors", other_column="id"
|
||||
)
|
||||
] == db["books"].foreign_keys
|
||||
|
||||
# Error if we try to add it twice:
|
||||
result = CliRunner().invoke(
|
||||
cli.cli, ["add-foreign-key", db_path, "books", "author_id", "authors", "id"]
|
||||
)
|
||||
|
||||
assert 0 != result.exit_code
|
||||
assert (
|
||||
"Error: Foreign key already exists for author_id => authors.id"
|
||||
== result.output.strip()
|
||||
)
|
||||
|
||||
# No error if we add it twice with --ignore
|
||||
result = CliRunner().invoke(
|
||||
cli.cli,
|
||||
["add-foreign-key", db_path, "books", "author_id", "authors", "id", "--ignore"],
|
||||
)
|
||||
assert 0 == result.exit_code
|
||||
|
||||
# Error if we try against an invalid column
|
||||
result = CliRunner().invoke(
|
||||
cli.cli, ["add-foreign-key", db_path, "books", "author_id", "authors", "bad"]
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ from sqlite_utils.db import (
|
|||
AlterError,
|
||||
NoObviousTable,
|
||||
ForeignKey,
|
||||
Table,
|
||||
)
|
||||
from sqlite_utils.utils import sqlite3
|
||||
import collections
|
||||
|
|
@ -348,7 +349,9 @@ def test_add_foreign_key(fresh_db):
|
|||
]
|
||||
)
|
||||
assert [] == fresh_db["books"].foreign_keys
|
||||
fresh_db["books"].add_foreign_key("author_id", "authors", "id")
|
||||
t = fresh_db["books"].add_foreign_key("author_id", "authors", "id")
|
||||
# Ensure it returned self:
|
||||
assert isinstance(t, Table) and t.name == "books"
|
||||
assert [
|
||||
ForeignKey(
|
||||
table="books", column="author_id", other_table="authors", other_column="id"
|
||||
|
|
@ -379,6 +382,13 @@ def test_add_foreign_key_error_if_already_exists(fresh_db):
|
|||
assert "Foreign key already exists for author_id => authors.id" == ex.value.args[0]
|
||||
|
||||
|
||||
def test_add_foreign_key_no_error_if_exists_and_ignore_true(fresh_db):
|
||||
fresh_db["books"].insert({"title": "Hedgehogs of the world", "author_id": 1})
|
||||
fresh_db["authors"].insert({"id": 1, "name": "Sally"}, pk="id")
|
||||
fresh_db["books"].add_foreign_key("author_id", "authors", "id")
|
||||
fresh_db["books"].add_foreign_key("author_id", "authors", "id", ignore=True)
|
||||
|
||||
|
||||
def test_add_foreign_keys(fresh_db):
|
||||
fresh_db["authors"].insert_all(
|
||||
[{"id": 1, "name": "Sally"}, {"id": 2, "name": "Asheesh"}], pk="id"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue