OK - I'll be rude. I do not see the significance of this. If you really want this, this is what you will need to do.
First, create the org_max_post (org_id, post_id) table org_max_post (org_id, post_id) . Fill it when adding a new organization (I would use a database trigger).
Then, when adding a new message, you need to:
BEGIN TransactionSELECT FOR UPDATE this line of the organization for its blocking- Increase
post_id by one, refresh the line. - Use this value to create a message.
COMMIT transaction to complete your updates and block release.
You want all this to happen within a single transaction, and with the corresponding row locked in org_max_post. You want to make sure that the new post_id gets allocated to one and only one post, and also if the message cannot fix that you are not wasting post_id time.
If you want to get smart and shorten SQL in your application code, you can do one of:
- Wrap the portion of the hole above in the user-defined function insert_post ().
- Paste through a view that does not have post_id and exposes it using a rule / trigger.
- Add a trigger that overwrites everything specified in the post_id column with a correctly updated value.
Deleting a message obviously does not affect your org_max_post table, so it will not interrupt your numbering.
Prevent any database-level message updates with a trigger. Check for any changes to OLD vs NEW post_id and select an exception, if any.
Then delete the existing redundant id column in the message table and use (org_id, post_id) as the primary key. If you encounter this problem, you can use it as your button.
Oh - and post_num or post_index is probably better than post_id as it is not an identifier.
I do not know how much of this will play well with rails. I am afraid that the last time I looked at it, database processing was ridiculously primitive.
source share