3

So I am learning FastAPI and want to get more experience with relational databases. I am using SQLAlchemy ORM, Pydantic and Alembic. Database is Postgres. One thing that I am running into however, is when I want to add a single column to a table I need to change a model, a schema and alembic in order to reflect this change. Isn't this a huge violation of DRY, error prone and very hard to maintain in the long run?

jarlh
  • 42,561
  • 8
  • 45
  • 63
RogerKint
  • 454
  • 5
  • 13
  • 2
    Well, yes. A layered architecture provides isolation for changes limited to one layer. A typical business change (as adding a column) is orthogonal and must be applied in each layer. This will be probably closed as opinion based. – Marmite Bomber Sep 09 '22 at 09:44
  • Thanks for the response! What do you mean by orthogonal – RogerKint Sep 09 '22 at 09:53
  • Orthogonal to the layers, the change goes from the bottom to the top through all layers. – Marmite Bomber Sep 09 '22 at 10:12

1 Answers1

2

Check out SQLModel. It attempts to tackle this exact issue. Instead of defining a database model (SQLAlchemy) and a corresponding Pydantic model, you only define one SQLModel that combines both.

It doesn't change the fact that you need to verify that your Alembic migrations work as intended thought.

The project is still in its early stages, but I find it very promising.

In general, I don't see any benefit in defining the schema twice, when you are developing an API. There is however, the obvious downside of making the entire application much more error prone, when you have to repeat yourself for every change in the schema.

With SQLModel you will probably see a substantial reduction in the lines of code, unless you have very special requirements (such as exotic types, multiple layers of validation/conversion, highly complex/nested relationships).

Daniil Fajnberg
  • 12,753
  • 2
  • 10
  • 41
  • Totally agree with the no real benefit in defining the schema twice part. I did this and it's quite confusing in my current project lol. Still possible, but I wish SQLModel was more developed. The only thing is that as an abstraction over SQLAlchemy (which, there's a lot there) I believe it'll be hard to maintain. But if they do it well I'd love to work with it. – Zack Plauché Aug 27 '23 at 08:16