Re: Tracking mutations in table data

From: Mark Kelly <pgsql(at)wastedtimes(dot)net>
To: pgsql-novice(at)lists(dot)postgresql(dot)org
Subject: Re: Tracking mutations in table data
Date: 2020-04-06 17:49:03
Message-ID: 67124df7-a9da-ca42-e736-cc39c32c4cda@wastedtimes.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Hi Chris.

On 05/04/2020 23:06, Chris Coutinho wrote:

> In addition to the IoT events themselves, I want to log the mutations
> in the metadata of each device. The metadata of each device changes
> much less frequently than the rate at which events are inserted,
> that's why I've opted to place the data into the devices table.

I've done something similar a few times. If the application that is
creating the device records can generate a UUID for each one I'd do all
of that in the devices table.

create table devices (
id serial primary key,
meta1 int,
meta2 text,
identifier UUID NOT NULL,
deleted BOOLEAN DEFAULT false,
update_time TIMESTAMP DEFAULT now()
)

Give each device a UUID when it is added, then instead of updating or
deleting records just create a new row with the same UUID that reflects
the changes.

Current record for the device is:

SELECT * FROM device
WHERE identifier = [whatever]
ORDER BY update_time DESC LIMIT 1;

Device history is just

SELECT * FROM device
WHERE identifier = [whatever]
ORDER BY update_time;"

Deletion is just flipping a boolean, and you retain the complete history
for the device no matter what, just because all the records are still there.

You can use triggers to block UPDATE or DELETE queries, they are core
and won't need any additional stuff on your server. Or you can just
trust your application :)

I've no idea how this might work at ridiculous scale, the biggest table
I've built using this approach tops out about a million records, so bear
that in mind.

Hope this helps,

Mark

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Pól Ua Laoínecháin 2020-04-12 16:42:39 Inserting a constant along with field values.
Previous Message Valentin Czisch 2020-04-06 11:38:39 PQencryptPasswordConn called using PostgreSQL9.6.