add_foreign_key can now detect table and pk, refs #25

This commit is contained in:
Simon Willison 2019-06-12 21:51:09 -07:00
commit d645032cfa
7 changed files with 100 additions and 13 deletions

View file

@ -220,7 +220,18 @@ def test_add_column_not_null_default(db_path):
)
def test_add_foreign_key(db_path):
@pytest.mark.parametrize(
"args,assert_message",
(
(
["books", "author_id", "authors", "id"],
"Explicit other_table and other_column",
),
(["books", "author_id", "authors"], "Explicit other_table, guess other_column"),
(["books", "author_id"], "Automatically guess other_table and other_column"),
),
)
def test_add_foreign_key(db_path, args, assert_message):
db = Database(db_path)
db["authors"].insert_all(
[{"id": 1, "name": "Sally"}, {"id": 2, "name": "Asheesh"}], pk="id"
@ -232,13 +243,8 @@ def test_add_foreign_key(db_path):
]
)
assert (
0
== CliRunner()
.invoke(
cli.cli, ["add-foreign-key", db_path, "books", "author_id", "authors", "id"]
)
.exit_code
)
0 == CliRunner().invoke(cli.cli, ["add-foreign-key", db_path] + args).exit_code
), assert_message
assert [
ForeignKey(
table="books", column="author_id", other_table="authors", other_column="id"

View file

@ -228,6 +228,17 @@ def test_add_column_foreign_key(fresh_db):
)
def test_add_foreign_key_guess_table(fresh_db):
fresh_db.create_table("dogs", {"name": str})
fresh_db.create_table("breeds", {"name": str, "id": int}, pk="id")
fresh_db["dogs"].add_column("breed_id", int)
fresh_db["dogs"].add_foreign_key("breed_id")
assert (
"CREATE TABLE [dogs] ( [name] TEXT , [breed_id] INTEGER, FOREIGN KEY(breed_id) REFERENCES breeds(id) )"
== collapse_whitespace(fresh_db["dogs"].schema)
)
@pytest.mark.parametrize(
"extra_data,expected_new_columns",
[

View file

@ -1,4 +1,5 @@
from sqlite_utils.db import Index
import pytest
def test_table_names(existing_db):
@ -79,3 +80,19 @@ def test_indexes(fresh_db):
),
Index(seq=1, name="Gosh_c1", unique=0, origin="c", partial=0, columns=["c1"]),
] == fresh_db["Gosh"].indexes
@pytest.mark.parametrize(
"column,expected_table_guess",
(
("author", "authors"),
("author_id", "authors"),
("authors", "authors"),
("genre", "genre"),
("genre_id", "genre"),
),
)
def test_guess_foreign_table(fresh_db, column, expected_table_guess):
fresh_db.create_table("authors", {"name": str})
fresh_db.create_table("genre", {"name": str})
assert expected_table_guess == fresh_db["books"].guess_foreign_table(column)