How to properly delete data from a table and chain the deletion

I’m new to postgreSQL and I’m trying to delete a row from a table and then also delete the relevant data from another table and then the linking table; Im trying to learn while doing so im pretty sure what im doing is way wrong.

Its giving me an error:

update or delete on table "users" violates foreign key constraint "usertopantry_user_id_fkey" on table "usertopantry"

The userstopantry table looks like:

user_id : integer : NOT NULL true : Primary KEY: true DEFAULT nextval('usertopantry_user_id_seq'::regclass)

pantry_id: integer : NOT NULL true : Primary KEY: true DEFAULT 
nextval('usertopantry_pantry_id_seq'::regclass)

This is the code im running to try and DELETE from all sources when a user DELETES a user:

const deleteUser = (request, response) => {
  const id = parseInt(request.params.id)

  pool.query('DELETE FROM users WHERE user_id = $1', [id], (error, userResults) => {
    if (error) {
      throw error
    }
    if(response) {
      pool.query('SELECT pantry_id FROM userstopantry WHERE user_id = $1', [id], (error, pantryResults) => {
        if (error) {
          throw error
        }

        pool.query('DELETE FROM pantries WHERE pantry_id = $1', [pantryResults.rows[0].pantry_id], (error, deletionResults) => {
          if (error) {
            throw error
          }
          pool.query('DELETE FROM userstopantry WHERE user_id = $1', [id], (error, results) => {
            if (error) {
              throw error
            }
            response.status(200).send(`User deleted with ID: ${id}`)
          })
        })
      })
    }
  })
}

Im using Node.js with pg.pool

1

The error you’re encountering is due to a foreign key constraint in PostgreSQL that prevents you from deleting a user while there are still references to that user in the userstopantry table. To resolve this issue, you need to delete the related rows from the userstopantry table first before deleting the user.
`const deleteUser = (request, response) => {
const id = parseInt(request.params.id)

// Start a transaction
pool.query(‘BEGIN’, (error) => {
if (error) throw error;

// First, delete from userstopantry to avoid the foreign key constraint violation
pool.query('DELETE FROM userstopantry WHERE user_id = $1 RETURNING pantry_id', [id], (error, pantryResults) => {
  if (error) {
    pool.query('ROLLBACK', () => {
      throw error;
    });
  }

  // Delete the related pantries using the returned pantry_ids (if needed)
  if (pantryResults.rows.length > 0) {
    const pantryIds = pantryResults.rows.map(row => row.pantry_id);

    pool.query('DELETE FROM pantries WHERE pantry_id = ANY($1)', [pantryIds], (error) => {
      if (error) {
        pool.query('ROLLBACK', () => {
          throw error;
        });
      }

      // After the related records are deleted, delete the user
      pool.query('DELETE FROM users WHERE user_id = $1', [id], (error) => {
        if (error) {
          pool.query('ROLLBACK', () => {
            throw error;
          });
        }

        // Commit the transaction if everything is successful
        pool.query('COMMIT', (error) => {
          if (error) {
            pool.query('ROLLBACK', () => {
              throw error;
            });
          }

          response.status(200).send(`User deleted with ID: ${id}`);
        });
      });
    });
  } else {
    // If no pantries to delete, just delete the user
    pool.query('DELETE FROM users WHERE user_id = $1', [id], (error) => {
      if (error) {
        pool.query('ROLLBACK', () => {
          throw error;
        });
      }

      pool.query('COMMIT', (error) => {
        if (error) {
          pool.query('ROLLBACK', () => {
            throw error;
          });
        }

        response.status(200).send(`User deleted with ID: ${id}`);
      });
    });
  }
});

});
};
`

1

I believe DELETE CASCASE is exactly what you’re looking for. It will delete related rows in other tables automatically.

This is a good first article https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-delete-cascade/

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật