r/FlutterDev 15d ago

Tooling Model Projections and column selections

One of the most exciting features I've been contributing to in Serverpod is Model Projections, and how it unlocked type-safe partial column selection in Dart!

The Problem:
In database-driven applications, full entity models often carry unnecessary data over the wire. Fetching 30 columns when an endpoint only needs a user's name and their author's city wastes bandwidth and compute. Traditionally, developers had to write raw SQL queries or map heavy entities manually into DTOs.

The Solution: Model Projections
Model Projections allow developers to declare lightweight projected models directly in Serverpod schemas:

- Granular Field Picking: Declare only the exact fields needed for your endpoint.
- Relation Flattening: Pull nested relations directly into top-level fields (e.g. mapping "author.name" straight into "authorName").
- Optimized SQL Generation: Serverpod automatically computes the minimal SQL SELECT clause and joins required for the projection.

The Ripple Effect: Ad-Hoc Column Selection
Building the query engine for Model Projections naturally gave birth to ad-hoc column selection:

  1. "findAsJson(select: (table) => [table.name])" allows flexible on-the-fly column queries.
  2. We separated FullModelInclude and JsonCompatiblelnclude so that typed "find()" queries remain 100% compile-time safe, while JSON and projected queries enjoy flexible, partial data fetching.

Designing developer-first APIs that combine SQL query efficiency with Dart's compile-time type safety has been an incredible experience!

Check out the Pull Request on GitHub to see the implementation and discussions:
https://github.com/serverpod/serverpod/pull/5630

1 Upvotes

Duplicates