Here is a design of the persistence of a simple Social Media Platform. Currently, there are these tables:
Here are the commands to create the tables
CREATE TABLE users(
id SERIAL PRIMARY KEY,
name VARCHAR (50) NOT NULL,
username VARCHAR (50) UNIQUE NOT NULL,
password VARCHAR (255) NOT NULL,
email VARCHAR (255) NOT NULL,
bio VARCHAR (255) NOT NULL,
followers INTEGER NOT NULL,
following INTEGER NOT NULL,
picture VARCHAR (255) NOT NULL
)
CREATE TABLE posts(
id SERIAL PRIMARY KEY,
title VARCHAR (255) NOT NULL,
picture VARCHAR (255) NOT NULL,
description VARCHAR (255) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
likes INTEGER NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
)
CREATE TABLE posts_liked_users(
post_id INTEGER NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
)
CREATE TABLE follows(
following_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
followed_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
)
And here is the diagram:
Are the diagram and the overall design right or is there something missing?
As an answer to anyone having a similar problem like the one from the question I refactored the design based on some suggestions and research:
I updated the VARCHAR
fields to be TEXT
which is the general guidance.
Because of normalization I removed the followers
and following
from the users
and likes
from the post
in order to reduce data redundancy and improve data integrity.
I added a created_at
field on the follows
and posts_liked_users
to keep the time when a user followed another or liked a post.
CREATE TABLE users(
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
email TEXT NOT NULL,
bio TEXT NOT NULL,
picture TEXT NOT NULL
)
CREATE TABLE posts(
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
picture TEXT NOT NULL,
description TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
)
CREATE TABLE posts_liked_users(
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
post_id INTEGER NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
)
CREATE TABLE follows(
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
following_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
followed_user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
)
references: