sqldatabasepostgresqldatabase-designdatabase-diagram

Is this Social Media Platform PostgreSQL Database design right?


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:

enter image description here

Are the diagram and the overall design right or is there something missing?


Solution

  • 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:

    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: