Postgres data types you should consider using
citusdata.com
citusdata.com
Suppose you have a table of fruits:
create table fruits (
name text primary key,
color text references colors,
season text references seasons
);
(There are other tables at play, colors and seasons). Anyway, now if you make a function to find you some fruits in season: create function get_fruits_in_season(season text)
returns fruits as
'select * from fruits where season = $1'
language sql;
Do you see that I just made a function whose return type is "fruits"? In this example, it's a bit overkill, because all you would really probably want is the name, and so would return "text." But it has been useful for me in real-life examples that are too complicated right now for me to spell out.Documentation: https://www.postgresql.org/docs/current/static/sql-createfun...
create function get_fruits_in_season(season text)
returns setof fruits as
'select * from fruits where season = $1'
language sql;* Singular is much friendlier to find/replace, due to the inconsistency of pluralization.
* A good practice is to name association tables by concatenation of the tables being associated (when the association doesn't correspond to a previously named entity). teacher_class is a much better name than teachers_classes, and definitely avoid teacher_classes.
* As you move up the stack, structs, interfaces and classes have strong singular conventions. If you spend much time at higher levels, the habits you develop can lead to little bugs when working deeper in the stack.
Am I missing something?
Again, not saying you're doing something wrong, just sharing a thought.
If its becoming a new table because you now want to associate metadata with it, then you'll have to rewrite queries in either case: previously it was just for data validation (so only relevant on insert, and never really referenced); now information is required so queries will have to join to it where they weren't before.
And if the enum existed in multiple places, and now you have to go around hunting them down to construct the FKs.. then it probably should have just been a table in the first place (otherwise any change to the enum requires finding and syncing each instance of it)
If it'll eventually want to become its own table, then at least while its still small we can claim the benefit of not having to name the thing. And that alone seems sufficiently beneficial to accept having to convert to a table later (unless, ofc, you expect to have to convert by like, tomorrow)
> In comparison, writing a validation on the application side is easy
But then you went there. I was going to say, instead of enums I always end up just make a table of the choices, because invariably I will want to store one or more columns of information about the choice. Anyway, a foreign key, as opposed to an enum.Writing validation on the application side is easy up front, but over the years I have been moving more and more smarts to the database:
- it's often less typing in SQL than your procedural language of choice
- some constraints are easy in a database but 1,000 times harder in a procedural middle layer (uniqueness, ACID transactions, etc.)
- it's more efficient, because it saves the transit of data that your application-layer validation often needs from the database to do its own thing anyway
The DB is a gigantic bag of data: if its got anything useful in it, then everyone will eventually want to put their grubby little hands all over it
Much better to just tell your DBMS the rules you want enforced, such that when that ne'er-do-well (which might be, say, future you) attempts to insert crazy data, it just doesn't work.
But if you have multiple apps sharing the same data, or the app is a bunch of different things from many years glued together, etc., then there is no longer "the" application side. You'd have to write validation on multiple application sides, and make sure they all agree. The data is at this point often more important than a single app.
Even with single-app data stores, if you ever have to use the SQL prompt directly (say, to do a one-off change that it doesn't make sense to write an app feature for, or time doesn't permit doing so) it's nice to have all the constraints specified in the database.
I have had to push for leveraging postgres for data validation (including typing columns with enums where applicable), and sometimes it's hard to convince people, but all you have to do is (a) poke around your existing data and find cases where you have junk because of some out-of-band process that created data without using your main app's validation, and (b) do a couple out-of-band things like an ETL or two and see how it saves you from creating junk.
I don't know where I picked this adage up, but it's also something I constantly think about:
Your data will outlive your application code.
IME, if you value the data's integrity, it's not really a question whether you should be pushing validations down to the db layer.
Yes, you are using your company's practices to discount the general benefit of typed data stores. You are also trading safety and usefulness at use/read time for ease at write time which is almost never correct. If your schema mutates frequently, you need to cope. Fearing schema alterations, because of your migration setup is bad IMO (there are plenty of other reasons to fear them though of course). This is how schemas become stale and data analysts (or just other devs) have no clue what they're doing with a schema because developers short-sightedly refuse to improve/refactor schema because of business processes.
It's literally 3 lines of work, if you use a tool that does most of the work for you. [Here](https://github.com/fake-name/ReadableWebProxy/blob/510cc41ae...) is a migration I have for one of my hobby projects.
Tthe process is
`alembic revision --autogenerate` Add two lines to the migration skeleton (4 if you care about downgrades). `alembic migrate +1`.
I may have the alembic migration commands slightly wrong. It's been a while since I've done them without having bash scrollback handy.
In one approach, enum columns were integer columns in db & we relied on ActiveRecord's (RoR) enum definition to map string values their integer representation. This created issues for our (separate & independent) internal application which was feeding off the read-replica.
In second approach, enums were defined as db-types. This solved most of issues seen with the first approach, but again sql-migration for maintaining the enum-values was another pain-point. Though it was not as painful as i thought, as the enums didn't change very frequently.
In third approach, used a separate table to maintain enum definition. If the column has a wider presence then, additional join might prove relatively costly compared to second approach.
Currently, we follow a mix of last two approaches.
And I use dbmate which puts all migrations in transactions.
But I agree - removing or renaming - safely - is an arse since you have to create a new enum, add it to every table with the old enum, update old to new column, drop enum, drop old columns, rename new columns to the original... yikes!
Yes it can at least be scripted but then all that schema rewriting is a pain on large tables.
The only potentially problematic thing is the fact that it's not transactional.
https://github.com/citusdata/postgresql-hll
This has been a great secret weapon for me in a few big counting problems.
I wonder how hard it would be to write that in PostgreSQL these days using the range types?