def test_change_unique_key(): db = ItemDB(":memory:") db.ensure_table("persons", "!name") with db: db.put_one("persons", name="Jan", age=30) db.put_one("persons", name="Henk", age=42) assert db.count_all("persons") == 2 # Add a new person, who also happens to be named "Jan" with db: db.put_one("persons", name="Jan", age=72) # Sorry, Jan assert db.count_all("persons") == 2 # Let's fix this, we need a separate id, so we need to re-index. # We cannot simply do this on an existing table. So we need some steps. try: with db: db.ensure_table("persons2") for i, person in enumerate(db.select_all("persons")): person["id"] = i db.put("persons2", person) db.delete_table("persons") raise RuntimeError("Oop! Something goes wrong in the process") db.rename_table("persons2", "persons") except RuntimeError: pass # Our little operation failed, but we did it in a transaction, so its fine! assert db.count_all("persons") == 2 # Try again with db: db.ensure_table("persons2") for i, person in enumerate(db.select_all("persons")): person["id"] = i db.put("persons2", person) db.delete_table("persons") db.rename_table("persons2", "persons") # Now we're good assert db.count_all("persons") == 2 with db: db.put_one("persons", name="Jan", age=72, id=3) assert db.count_all("persons") == 3
def test_delete_table(): db = ItemDB(":memory:") db.ensure_table("persons", "!name") db.ensure_table("animals", "!name") with db: db.put_one("persons", name="Jan", age=30) db.put_one("persons", name="Henk", age=42) db.put_one("animals", name="Takkie", age=30) db.put_one("animals", name="Siepe", age=42) assert db.count_all("persons") == 2 assert db.count_all("animals") == 2 with db: db.delete_table("persons") with raises(KeyError): db.count_all("persons") db.ensure_table("persons", "!name") assert db.count_all("persons") == 0 assert db.count_all("animals") == 2 with db: db.delete_table("animals") with raises(KeyError): db.count_all("animals") db.ensure_table("animals", "!name") assert db.count_all("persons") == 0 assert db.count_all("animals") == 0 # Need a transaction context with raises(IOError): db.delete_table("persons") # This works with db: db.delete_table("persons") # But this not because the table is gone with raises(KeyError): with db: db.delete_table("persons")