Repository: tortoise/aerich (language: python)

Issue:
NonExistentKey when running `aerich init`
```
# aerich init -t project.settings.DATABASE 
...
  File "/usr/local/lib/python3.11/site-packages/aerich/cli.py", line 205, in init
    doc["tool"]["aerich"] = table
    ~~~^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/tomlkit/container.py", line 650, in __getitem__
    raise NonExistentKey(key)
tomlkit.exceptions.NonExistentKey: 'Key "tool" does not exist.'
```

My `pyproject.toml`:

```toml
[project]
name = "project"
classifiers = ["Private :: Do Not Upload"]
version = "0"
dependencies = [
    "fastapi ~= 0.89.1",

    # DB
    "tortoise-orm[accel,asyncpg] ~= 0.19.2",
    "aerich ~= 0.7.1",
]

[project.optional-dependencies]
dev = [
    "pytest ~= 7.2.1",
    "isort ~= 5.11.4",
    "flake8 ~= 5.0.4",
    "ipython",
]
```


Discussion / hints:
I've just had the same issue. This is because `aerich init` assumes the `[tool]` section exists in `pyproject.toml`. You can work around that by creating the section yourself, but `aerich` should check if it exists first...
I also have faced this issue. Is there any solution?
Solution is:

Create a file in your root project `pyproject.toml`

Here is my toml file. Please customize this as you needed

```
[project]
name = "project_name"
classifiers = ["Private :: Do Not Upload"]
version = "1"
dependencies = [
    "blacksheep==2.0.7",

    # DB
    "tortoise-orm[asyncpg] ~= 0.21.3",
    "aerich ~= 0.7.2",
]

[project.optional-dependencies]
dev = [
]
[tool.setuptools.packages] // this is important. If you don't add this link, you will get an error
find = {}  # Scanning implicit namespaces is active by default

```
I tried to run `aerich init` and received the same error.

Probably unrelated, but for reference here is my full command
`docker compose exec server uv run aerich init -t app.db.TORTOISE_ORM`

In my case I already had `pyproject.toml` in the project root directory.

I manually added an empty `[tool.aerich]` table at the end of the file:

```pyproject.toml
[project]
name = "project"
version = "0.1.0"
# ...

[tool.aerich]
```

Rerun the command and initialization completed successfully.

In my case it added the following:
```pyproject.toml
# ...

[tool.aerich]
tortoise_orm = "app.db.TORTOISE_ORM"
location = "./migrations"
src_folder = "./."
```

Fix patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1ff66ca..7c7f91d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@
 ### [0.8.1](Unreleased)
 
 #### Fixed
+- Fix NonExistentKey when running `aerich init` without `[tool]` section in config file. (#284)
 - Fix configuration file reading error when containing Chinese characters. (#286)
 - sqlite: failed to create/drop index. (#302)
 - PostgreSQL: Cannot drop constraint after deleting or rename FK on a model. (#378)
diff --git a/aerich/cli.py b/aerich/cli.py
index 25aeb8c..b5d446d 100644
--- a/aerich/cli.py
+++ b/aerich/cli.py
@@ -190,7 +190,10 @@ async def init(ctx: Context, tortoise_orm, location, src_folder) -> None:
     table["tortoise_orm"] = tortoise_orm
     table["location"] = location
     table["src_folder"] = src_folder
-    doc["tool"]["aerich"] = table
+    try:
+        doc["tool"]["aerich"] = table
+    except KeyError:
+        doc["tool"] = {"aerich": table}
 
     config_path.write_text(tomlkit.dumps(doc))
 


Test patch:
diff --git a/tests/test_sqlite_migrate.py b/tests/test_sqlite_migrate.py
index e1478a0..568f273 100644
--- a/tests/test_sqlite_migrate.py
+++ b/tests/test_sqlite_migrate.py
@@ -230,3 +230,9 @@ def test_sqlite_migrate(tmp_path: Path) -> None:
                 p.unlink()
         run_aerich("aerich init-db")
         assert db_file.exists()
+
+        # init without '[tool]' section in pyproject.toml
+        config_file = Path("pyproject.toml")
+        config_file.write_text('[project]\nname = "project"')
+        run_aerich("init -t settings.TORTOISE_ORM")
+        assert "[tool.aerich]" in config_file.read_text()