Type constraints in 65 lines of SQL
supabase.com
supabase.com
- Composite types are useful for data validation. Money types and unit-based types are good for composite types.
- Avoid over-using composite types. Most of the time, regular columns are better. Not many tools interact well with composite types, like reporting tools or database libraries.
- Like the article notes, avoid using composite types for data types that may change.
- A JSONB domain type is a good alternative for data types that change often. Note that if you put the validation into a helper function, Postgres will not revalidate the domain if the function definition changes.
- Using composite types is mildly annoying since you must wrap the composite column in parenthesis to access the field.
-- Bad
SELECT package_semver.major FROM package_version;
-- Errors with `missing FROM-clause entry for table "package_semver"`
-- Good
SELECT (package_semver).major FROM package_version;
- When defining a domain type, separate checks into named constraints with ALTER DOMAIN. The Postgres error message for check validation failures is lackluster and provides little beyond "it failed." CREATE DOMAIN item_delta_node AS jsonb NOT NULL;
ALTER DOMAIN item_delta_node
ADD CONSTRAINT item_delta_node_is_object
CHECK (coalesce(jsonb_typeof(value), '') = 'object');
ALTER DOMAIN item_delta_node
ADD CONSTRAINT item_delta_node_item_delta_id_null_or_num
CHECK (coalesce(jsonb_typeof(value['item_delta_id']), 'number') IN ('null', 'number'));""Using composite types is mildly annoying since you must wrap the composite column in parenthesis to access the field"""
^ yeah that is frustrating
--
if you create domains over jsonb frequently, check out pg_jsonschema[1] as a way to express the constraints more concisely
This is one data type feature which would be great to have. I know you can create separate tables for each option in the type and use an id, but is a direct type implementation possible?
Dont need polymorphism(say a = String). Even a non recursive tagged union would be helpful.
I had this issue when trying to implement an AST type for pg_graphql[1] back when it was written in SQL [2]. In the end we used a JSON type which was much less constrained. That might be solvable using pg_jsonschema [3] if you really wanted to have a good time though
[1] https://github.com/supabase/pg_graphql
[2] https://github.com/supabase/pg_graphql/blob/34cc266da972d356...
Can https://www.postgresql.org/docs/15/functions-conditional.htm... be used to do it?
I have saved some links about this
https://github.com/solidsnack/pg-sql-variants
https://thelyfsoshort.io/variant-types-in-postgresql-c63725f...
https://www.parsonsmatt.org/2019/03/19/sum_types_in_sql.html
https://typeable.io/blog/2019-11-21-sql-sum-types.html
Right now I think the ideal is a jsonb column (with a field that stores the tag) plus https://github.com/supabase/pg_jsonschema. But this is only usable if your language translates to/from JSON and generates json schema for you.
Rust can do this with https://serde.rs/ and https://docs.rs/schemars/latest/schemars/
For example, SemVer requires that two version that differ only in metadata e.g. `1.0.0+metaA` and `1.0.0+metaB` should be considered equal. It would be error prone and tedious to push that logic onto every query that wanted to sort the table, but with a type we can define the logic once and have it work everywhere.
In most cases, a single invoice, order, deal, etc. is unlikely to be generated using multiple currencies. Therefore, a single currency_type field in the invoice table would be sufficient.
If we used a composite currency type, the currency_type field would be highly redundant.
It can help prevent the bug in which someone adds up multiple currencies without conversion.
“25 USD + 25 EUR” will either fail or work via some currency conversion routine.
“25 + 25” will produce a meaningless and useless wrong answer.
another approach that works great is to use `create type`[1] with an `input_function` and `output_function` to build on top of an existing scalar type. For example, using that method would allow semver to be persisted as a string natively. The only downside to that is you have to be superuser.
[1] https://www.postgresql.org/docs/current/sql-createtype.html
Then, instead of informing them of best practices and giving them time to re-work the code, you'd just fire them?
Interesting strategy.
A relational database isn't always fronted by the same tech. You have RESTful APIs, GraphQL APIs, Low Code/No Code Solutions (like Retool), reporting tools, ETL systems, etc.
You have company mergers where that one familiar ORM is now five to six unfamiliar ORMs.
Ensuring data integrity is key and easiest way to do that is to push constraints as close to the persistence layer as possible.
Putting logic directly in the database is much faster at runtime, doesn’t require redundant entity definitions, is substantially more likely to detect schema problems, and is way easier to test.
And it removes the dependency on a specific language and toolchain. Your logic is accessible by everyone.
Unfortunately, the tooling around managing this stuff is not great. The language is a bit boring; idiomatic upper case is the first thing I get rid of.
But it’s the best tool for the job. Far from being “way easier” in application code, plpgsql reduces LOC, improves performance and removes dependencies.
If someone on my team ignored all of these benefits, well, I’d explain it to them and show them examples until they “got it”.
Way easier than firing them.
It’s not particularly annoying to debug - there are logging, and even single step debugging tools available - and it’s so much easier to test than writing unit tests to do the same thing.
I agree it’s painful to deploy, but as I’ve discovered this is a tooling problem; it’s not at all intrinsic to the medium.
It’s certainly possible to create tooling to make it easier, and who knows? Maybe I’ll have something to show HN one day.
> Many developers today barely know SQL.
If true - a very big if - it’s an inditement of the industry and the incentives we use, not a reason to avoid something that makes code faster, safer and smaller.
Objections to using these languages are a lot more about willingness to learn and try new (old) things, than they are about the capabilities of the platform.
1) Its only been a few years since the trend of testing on sqlite locally and running postgres in production went away in favor of postgres everywhere (probably thanks to docker). That prevented using any feature that wasn't equally supported by both.
2) There's definitely a knowledge gap, and not just among developers. The features are most useful for building rich applications, so even DBAs didn't have much incentive to use them prior to tools like supabase using the database as the data model source-of-truth.
3) Companies are increasingly deciding that data is their competitive advantage and interest in data integrity is growing. Database constraints are unparalleled at that because they can't be sidestepped
But there are far fewer tutorials and best practices on how to, say, maintain a library of Postgres functions, types, and stored procedures that can be iterated on. I'd venture that most people have no idea how powerful their databases can be.
Bad support for testing, for version controlled schemas, language types, etc.
This is the reason for the spread of ORMs and similar abstractions to hide this lack of support.
If space abuse is a vector under consideration, given there doesn't seem to be a restriction on the number of entries (if I somehow missed one my apologies) you could easily stuff it with a really big array of 255 character entries so I wonder if 2048 plus some sort of reasonably generous limit on the number of elements might not achieve the goal better and provide a better UX/DX as an added bonus.
(I'm currently working on a design in a somewhat related area so I've been doing a fair bit of thinking about this - I may of course still be completely wrong, but if so I can at least claim I put effort into ending up wrong ;)
Is that true?
Is that true?