Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correct imports and improve generation logic in SQLModelGenerator #352

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ jobs:
cache-dependency-path: pyproject.toml
- name: Install dependencies
run: pip install -e .[test]
- name: Install sqlmodel dependency
run: pip install -e .[sqlmodel]
- name: Test with pytest
run: coverage run -m pytest
- name: Upload Coverage
Expand Down
24 changes: 21 additions & 3 deletions src/sqlacodegen/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,8 +292,21 @@ def group_imports(self) -> list[list[str]]:
stdlib_imports: list[str] = []
thirdparty_imports: list[str] = []

has_imports: set[str] = set()
for package in sorted(self.imports):
imports = ", ".join(sorted(self.imports[package]))
if duplicate_import := self.imports[package] & has_imports:
print(
f"WARN: Duplicate imports `{duplicate_import}` are detected "
f"from the package `{package}` and will be filtered, "
f"which may cause abnormal behavior."
)

current_import = sorted(
name for name in self.imports[package] if name not in duplicate_import
)
has_imports = has_imports | set(current_import)

imports = ", ".join(current_import)
collection = thirdparty_imports
if package == "__future__":
collection = future_imports
Expand Down Expand Up @@ -448,7 +461,11 @@ def render_column(
kwargs["key"] = column.key
if is_primary:
kwargs["primary_key"] = True
if not column.nullable and not is_sole_pk and is_table:
if (
not column.nullable
and not is_sole_pk
and (is_table or isinstance(self, SQLModelGenerator))
):
kwargs["nullable"] = False

if is_unique:
Expand Down Expand Up @@ -482,10 +499,11 @@ def render_column(
if comment:
kwargs["comment"] = repr(comment)

if is_table:
if is_table or isinstance(self, SQLModelGenerator):
self.add_import(Column)
return render_callable("Column", *args, kwargs=kwargs)
else:
self.add_literal_import("sqlalchemy.orm", "mapped_column")
return render_callable("mapped_column", *args, kwargs=kwargs)

def render_column_type(self, coltype: object) -> str:
Expand Down
Loading