agronholm / sqlacodegen

Automatic model code generator for SQLAlchemy
Other
1.87k stars 243 forks source link

SQLModel codegen produces syntax errors #302

Open NixBiks opened 10 months ago

NixBiks commented 10 months ago

Things to check first

Sqlacodegen version

3.0.0rc3

SQLAlchemy version

2.0.23

RDBMS vendor

PostgreSQL

What happened?

The screenshot shows some of the issues.

  1. There are unused imports (can easily be fixed by running ruff after codegen)
  2. Missing imports, i.e. mapped_column.
  3. Syntax error due to a , in line 22.
Screenshot 2023-11-16 at 09 18 05

Database schema for reproducing the bug

CREATE TABLE
  logs (
    timestamp timestamp NOT NULL,
    level text NOT NULL,
    message text NOT NULL,
    schedule_id bigint REFERENCES schedules (id),
    worker_id text,
    run_id text,
    id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY
  );

-- sort by timestamp
CREATE INDEX logs_timestamp_desc_idx ON logs (timestamp DESC);

-- create view of logs
CREATE VIEW logs_view AS
  SELECT
    timestamp,
    level,
    message,
    schedule_id,
    worker_id,
    run_id
  FROM logs
  ORDER BY timestamp DESC;
madsenwattiq commented 10 months ago

I see this as well. In order to fix broken code, I had to manually add the "metadata" variable to all association tables that didn't have primary keys - that's the bug with the double commas. After that, it works in 3.0.0rc3.

agronholm commented 10 months ago

It's not supposed to use mapped_column at all. All the tests expect that it uses Column() and not mapped_column(). The latter is a thing only on SQLAlchemy 2. Before sqlmodel 0.0.12 (released 7 hours ago), it didn't even work with SQLAlchemy 2 at all.

agronholm commented 10 months ago

I'm pretty sure that this was caused by `sqlmodel now supporting SQLAlchemy 2, and sqlacodegen wasn't ready for that.

michelmetran commented 5 months ago

I'm pretty sure that this was caused by `sqlmodel now supporting SQLAlchemy 2, and sqlacodegen wasn't ready for that.

Thank you for the information!

After that, I used an environment with SQLAlchemy < 2 and it worked!

conda create --name sqlacodegen-py39 -c conda-forge python=3.9 sqlacodegen==3.0.0rc3 sqlalchemy==1.4.51 pymssql==2.2.7


Now the mapped_column no longer appears, as it is not yet compatible with SQLModel

yaoguoba commented 1 month ago

This issue still exists in rc5, which still includes mapped_column. I replaced mapped_column with sqlmodel.Column, You can work normally now.

yaoguoba commented 1 month ago

This issue still exists in rc5, which still includes mapped_column. I replaced mapped_column with sqlmodel.Column, You can work normally now.