Skip to content

Instantly share code, notes, and snippets.

@groue
Last active September 7, 2023 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save groue/fe8be1230966e7225a96d980b254d974 to your computer and use it in GitHub Desktop.
Save groue/fe8be1230966e7225a96d980b254d974 to your computer and use it in GitHub Desktop.
Swift key paths are not coding keys, JSON keys, or SQLite columns

Swift key paths are not coding keys, JSON keys, or SQLite columns

(Copy-pasted from groue/GRDB.swift#1423 (comment), edited for clarity)

And if I remember correctly, you had some good reasons for not using key paths in the GRDB query builder

My reluctance about key paths is based on the fact that record types do frequently, but not always, exactly reflect their database representation. The reality is that record types are a Swift interface to their inner database representation. And it's the same for "json records" as well.

That's how people use them. They'll replace a text database value with a Swift string-based enum value. They'll publicly expose a price: Decimal property instead of the priceCents database integer. They'll publicly expose a location: CLLocationCoordinate2D property instead of two latitude and longitude database doubles.

And that's totally natural. It helps users avoiding an extra layer of "behind the front line" models when they want to hide intimate database details. It's good to be able to deal with a single layer of record types (some of them acting as a facade when needed).

And this explains why key paths are not our friends: they only have access to the Swift application-facing side of the record types, not to the inner, private, database-facing side made of columns or json keys. Key paths are not columns or JSON keys.

Some people think that a properly-designed app should define two types (one "proper" model that feeds from a "data transfer object" that feeds from the database). Well GRDB does not prevent those people from doing as they like. The rest of us can have their record types hide intimate database details when they feel like it. People should be free to choose their level of over-engineering, and GRDB tries to be architecture-agnostic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment