Implemented database schema #1

Open
farnam_jhn wants to merge 1 commits from develop into main
15 changed files with 653 additions and 175 deletions
+46 -111
View File
@@ -1,141 +1,76 @@
-- Restaurant Database Management System
--
-- Instructions:
-- 1. Create all required tables.
-- 2. Design appropriate PRIMARY KEY and FOREIGN KEY relationships.
-- 3. Add suitable constraints based on the requirements.
-- 4. Insert initial mock data.
-- 5. Insert at least 3 menu items.
-- 6. The script should be executable from start to finish without errors.
-- =======================================================
-- USER TABLE
-- =======================================================
--
-- Represents customers using the system.
--
-- Required information:
-- - Unique identifier
-- - Username
-- - Password
-- - Email (optional)
--
-- Requirements:
-- - Each user must have a unique identifier.
-- - Usernames must be unique.
-- - Username and password are required.
-- - Passwords should not be stored in plain text.
--
-- CREATE TABLE ...
CREATE TABLE users(
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
email VARCHAR(250)
);
-- =======================================================
-- MENU ITEM TABLE
-- =======================================================
--
-- Represents available food and drink items.
--
-- Required information:
-- - Unique identifier
-- - Name
-- - Description (optional)
-- - Price
-- - Category (optional)
--
-- Requirements:
-- - Each menu item must have a unique identifier.
-- - Name is required.
-- - Price must always be positive.
--
-- CREATE TABLE ...
CREATE TABLE menu(
id SERIAL PRIMARY KEY,
name VARCHAR(250) NOT NULL,
description TEXT,
price NUMERIC NOT NULL CHECK (price > 0),
category VARCHAR(50)
);
-- =======================================================
-- ORDER TABLE
-- =======================================================
--
-- Represents orders placed by customers.
--
-- Required information:
-- - Unique identifier
-- - Reference to customer
-- - Creation date and time
-- - Total price
--
-- Requirements:
-- - Each order must belong to exactly one user.
-- - A user can have multiple orders.
-- - The relationship between User and Order must be implemented.
--
-- Note:
-- Avoid using reserved SQL keywords as table names.
-- Consider using a name such as "orders" or "customer_orders".
--
-- CREATE TABLE ...
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INT NOT NULL,
created_at TIMESTAMP NOT NULL,
total_price NUMERIC NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
);
-- =======================================================
-- ORDER DETAIL TABLE
-- =======================================================
--
-- Represents items inside an order.
--
-- Required information:
-- - Unique identifier
-- - Reference to an order
-- - Reference to a menu item
-- - Quantity
-- - Item price at purchase time
--
-- Requirements:
-- - Each detail record must belong to one order.
-- - Each detail record must reference one menu item.
-- - Quantity must always be greater than zero.
-- - Store the item's price at the moment of purchase.
--
-- CREATE TABLE ...
CREATE TABLE order_details(
id SERIAL PRIMARY KEY,
order_id INT NOT NULL,
menu_id INT NOT NULL,
quantity NUMERIC NOT NULL CHECK (quantity > 0),
item_price NUMERIC NOT NULL CHECK (item_price > 0),
FOREIGN KEY (order_id) REFERENCES orders(id),
FOREIGN KEY (menu_id) REFERENCES menu(id)
);
-- =======================================================
-- INITIAL MENU DATA
-- =======================================================
--
-- Insert at least 3 food or drink items.
--
-- Example categories:
-- - Pizza
-- - Burger
-- - Pasta
-- - Drink
--
-- INSERT INTO ...
-- =======================================================
-- OPTIONAL TEST DATA
-- =======================================================
--
-- You may insert sample users and orders for testing.
-- This section is optional.
--
-- INSERT INTO ...
insert into menu (name, description, price, category) values ('Margherita Pizza', 'Classic pizza with tomato sauce, mozzarella, and basil.', 12.99, 'Pizza');
insert into menu (name, description, price, category) values ('Pepperoni Pizza', null, 14.49, 'Pizza');
insert into menu (name, description, price, category) values ('Cheeseburger', 'Beef patty with cheddar cheese, lettuce, and tomato.', 10.99, 'Burger');
insert into menu (name, description, price, category) values ('Chicken Burger', null, 11.49, 'Burger');
insert into menu (name, description, price, category) values ('Caesar Salad', 'Romaine lettuce, croutons, parmesan, and Caesar dressing.', 8.99, 'Salad');
insert into menu (name, description, price, category) values ('Greek Salad', null, 9.49, 'Salad');
insert into menu (name, description, price, category) values ('French Fries', 'Crispy golden potato fries.', 4.99, 'Side');
insert into menu (name, description, price, category) values ('Onion Rings', null, 5.49, 'Side');
insert into menu (name, description, price, category) values ('Espresso', null, 2.99, 'Drink');
insert into menu (name, description, price, category) values ('Cappuccino', 'Espresso with steamed milk and milk foam.', 4.49, 'Drink');
insert into menu (name, description, price, category) values ('Chocolate Cake', null, 6.99, 'Dessert');
insert into menu (name, description, price, category) values ('Cheesecake', 'Creamy cheesecake served with berry sauce.', 7.49, 'Dessert');
-- =======================================================
-- VERIFICATION QUERIES
-- =======================================================
--
-- Uncomment these queries to verify your database.
--
-- SELECT * FROM ...;
-- SELECT * FROM ...;
-- SELECT * FROM ...;
-- SELECT * FROM ...;
SELECT * FROM users;
SELECT * FROM menu;
SELECT * FROM orders;
SELECT * FROM order_details;
+48 -6
View File
@@ -1,25 +1,67 @@
package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.MenuItem;
import javax.xml.crypto.Data;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MenuItemDao {
public List<MenuItem> findAll() {
String sql = "SELECT * FROM menu";
List<MenuItem> result = new ArrayList<>();
// TODO:
// Retrieve all menu items
try {
PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
return null;
while (rs.next()){
result.add(new MenuItem(
rs.getInt("id"),
rs.getString("name"),
rs.getString("description"),
rs.getDouble("price"),
rs.getString("category")
));
}
} catch (SQLException e) {
System.err.println("Unable to fetch menu: " + e.getMessage());
}
return result;
}
public MenuItem findById(int id) {
// TODO:
// Find menu item by id
MenuItem item = null;
String sql = "SELECT * FROM menu WHERE id=?";
return null;
try {
PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(sql);
stmt.setInt(1,id);
ResultSet rs = stmt.executeQuery();
if (rs.next()){
item = new MenuItem(
rs.getInt("id"),
rs.getString("name"),
rs.getString("description"),
rs.getDouble("price"),
rs.getString("category")
);
}
} catch (SQLException e) {
System.err.println("Unable to fetch item: " + e.getMessage());
}
return item;
}
}
+45 -5
View File
@@ -1,25 +1,65 @@
package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.Order;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class OrderDao {
public int save(Order order) {
String sql = "INSERT INTO orders(user_id,created_at,total_price) VALUES(?,?,?)";
// TODO:
// Insert order and return generated id
try {
PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, order.getUserId());
stmt.setTimestamp(2, Timestamp.valueOf(order.getCreatedAt()));
stmt.setDouble(3, order.getTotalPrice());
stmt.executeUpdate();
ResultSet keys = stmt.getGeneratedKeys();
if (keys.next()){
int orderId = keys.getInt(1);
order.setId(orderId);
return orderId;
}
} catch (SQLException e) {
System.err.println("Unable to add order: " + e.getMessage());
}
return -1;
}
public List<Order> findByUserId(int userId) {
// TODO:
// Retrieve all orders of a user
List<Order> result = new ArrayList<>();
String sql = "SELECT * FROM orders WHERE user_id=?";
return null;
try {
PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(sql);
stmt.setInt(1,userId);
ResultSet rs = stmt.executeQuery();
while (rs.next()){
result.add(new Order(
rs.getInt("id"),
rs.getInt("user_id"),
rs.getTimestamp("created_at").toLocalDateTime(),
rs.getDouble("total_price")
));
}
} catch (SQLException e) {
System.err.println("Unable to find user: " + e.getMessage());
}
return result;
}
}
+39 -6
View File
@@ -1,24 +1,57 @@
package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.OrderDetail;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class OrderDetailDao {
public void save(OrderDetail detail) {
String sql = "INSERT INTO order_details (order_id, menu_id, quantity, item_price) VALUES (?,?,?,?)";
// TODO:
// Insert order detail
try {
PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(sql);
stmt.setInt(1, detail.getOrderId());
stmt.setInt(2, detail.getMenuItemId());
stmt.setInt(3, detail.getQuantity());
stmt.setDouble(4, detail.getPrice());
stmt.executeUpdate();
} catch (SQLException e) {
System.err.println("Error writing order details: " + e.getMessage());
}
}
public List<OrderDetail> findByOrderId(int orderId) {
// TODO:
// Retrieve order details
List<OrderDetail> result = new ArrayList<>();
return null;
String sql = "SELECT * FROM order_details WHERE order_id=?";
try {
PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(sql);
stmt.setInt(1,orderId);
ResultSet rs = stmt.executeQuery();
while (rs.next()){
result.add(new OrderDetail(
rs.getInt("id"),
rs.getInt("order_id"),
rs.getInt("menu_id"),
rs.getInt("quantity"),
rs.getDouble("item_price")
)
);
}
} catch (SQLException e) {
System.err.println("Error retrieving order details: " + e.getMessage());
}
return result;
}
}
+38 -6
View File
@@ -1,23 +1,55 @@
package dev.dao;
import dev.database.DatabaseConnection;
import dev.model.User;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
public boolean save(User user) {
public boolean save(User user){
String sql = "INSERT INTO users (username, password_hash, email) VALUES (?, ?, ?)";
// TODO:
// Insert user into database
try {
PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(sql);
stmt.setString(1, user.getUsername());
stmt.setString(2, user.getPasswordHash());
stmt.setString(3, user.getEmail());
stmt.executeUpdate();
return true;
} catch (SQLException e) {
System.err.println("failed to save user: " + e.getMessage());
}
return false;
}
public User findByUsername(String username) {
// TODO:
// Find a user by username
String sql = "SELECT * FROM users WHERE username=?";
User result = null;
try {
PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(sql);
stmt.setString(1, username);
return null;
ResultSet rs = stmt.executeQuery();
if (rs.next()){
result = new User(
rs.getInt("id"),
rs.getString("username"),
rs.getString("password_hash"),
rs.getString("email")
);
}
} catch (SQLException e) {
System.err.println("Unable to find user: " + e.getMessage());
}
return result;
}
}
@@ -1,15 +1,16 @@
package dev.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String URL = "jdbc:postgresql://localhost:5432/restaurant_db"; // DB Server
private static final String URL = "jdbc:postgresql://localhost:5432/restaurant"; // DB Server
private static final String USER = "postgres"; // Your Username
private static final String USER = "farnam"; // Your Username
private static final String PASSWORD = "password"; // Your Password
private static final String PASSWORD = "1234"; // Your Password
private DatabaseConnection() {
@@ -17,11 +18,7 @@ public class DatabaseConnection {
public static Connection getConnection()
throws SQLException {
// TODO:
// Return a valid PostgreSQL connection
return null;
return DriverManager.getConnection(URL,USER,PASSWORD);
}
}
+20
View File
@@ -0,0 +1,20 @@
package dev.model;
public class CartItem {
private MenuItem item;
private int quantity;
public CartItem(MenuItem item, int quantity) {
this.item = item;
this.quantity = quantity;
}
public MenuItem getItem() {
return item;
}
public int getQuantity() {
return quantity;
}
}
+32
View File
@@ -12,4 +12,36 @@ public class MenuItem {
private String category;
public MenuItem(int id, String name, String description, double price, String category) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
this.category = category;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public double getPrice() {
return price;
}
public String getCategory() {
return category;
}
@Override
public String toString() {
return String.format("[%d] %s - $%.2f\n%s\nCategory: %s", id, name, price, description, category);
}
}
+44
View File
@@ -12,4 +12,48 @@ public class Order {
private double totalPrice;
public Order(int id, int userId, LocalDateTime createdAt, double totalPrice) {
this.id = id;
this.userId = userId;
this.createdAt = createdAt;
this.totalPrice = totalPrice;
}
public Order(int userId, LocalDateTime createdAt, double totalPrice) {
this.userId = userId;
this.createdAt = createdAt;
this.totalPrice = totalPrice;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
}
+38
View File
@@ -12,4 +12,42 @@ public class OrderDetail {
private double price;
public OrderDetail(int id, int orderId, int menuItemId, int quantity, double price) {
this.id = id;
this.orderId = orderId;
this.menuItemId = menuItemId;
this.quantity = quantity;
this.price = price;
}
public OrderDetail(int orderId, int menuItemId, int quantity, double price) {
this.orderId = orderId;
this.menuItemId = menuItemId;
this.quantity = quantity;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getOrderId() {
return orderId;
}
public int getMenuItemId() {
return menuItemId;
}
public int getQuantity() {
return quantity;
}
public double getPrice() {
return price;
}
}
+35 -1
View File
@@ -6,8 +6,42 @@ public class User {
private String username;
private String password;
private String passwordHash;
private String email;
public User(int id, String username, String passwordHash, String email) {
this.id = id;
this.username = username;
this.passwordHash = passwordHash;
this.email = email;
}
public User(String username, String passwordHash, String email) {
this.username = username;
this.passwordHash = passwordHash;
this.email = email;
}
public void setId(int id){
this.id = id;
}
public String getPasswordHash(){
return passwordHash;
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getEmail() {
return email;
}
}
+43 -4
View File
@@ -1,23 +1,62 @@
package dev.service;
import dev.dao.UserDao;
import dev.model.User;
import java.util.Objects;
public class AuthService {
private final UserDao userDao = new UserDao();
public boolean register(String username, String password, String email) {
// TODO:
// Validate and register user
if (!isValidEmail(email)){
System.err.println("Invalid email address.");
return false;
}
User user = new User(
username,
String.valueOf(password.hashCode()),
email
);
if (userDao.save(user)){
System.out.println("Successfully registered user");
return true;
}
return false;
}
public User login(String username, String password) {
// TODO:
// Authenticate user
User dbUser = userDao.findByUsername(username);
if (dbUser == null){
return null;
}
String dbUserPasswordHash = dbUser.getPasswordHash();
if (Objects.equals(dbUserPasswordHash,
String.valueOf(password.hashCode()))){
return dbUser;
}
return null;
}
public boolean isValidEmail(String email) {
if (email == null || email.isBlank()) {
return true;
}
int atIndex = email.indexOf('@');
if (atIndex <= 0) return false;
int dotIndex = email.lastIndexOf('.');
if (dotIndex <= atIndex + 1) return false;
if (dotIndex == email.length() - 1) return false;
return true;
}
}
+49 -2
View File
@@ -1,12 +1,59 @@
package dev.service;
import dev.dao.MenuItemDao;
import dev.model.MenuItem;
import dev.model.User;
import java.util.List;
import java.util.Scanner;
public class MenuService {
public static final MenuItemDao menuItemDao = new MenuItemDao();
public void showMenu() {
List<MenuItem> items = menuItemDao.findAll();
for (MenuItem item : items){
System.out.println(item.toString());
}
}
// TODO:
// Display menu items
public void userPanel(User user) {
OrderService orderService;
while (true) {
System.out.println();
System.out.println("===== " + user.getUsername().toUpperCase() + " =====");
System.out.println("1. Place Order");
System.out.println("2. Order History");
System.out.println("3. Logout");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
{
OrderService.placeOrder(user.getId());
break;
}
case 2: {
OrderService.showOrderHistory(user.getId());
break;
}
case 3:
System.out.println("Goodbye, " + user.getUsername() + "!");
return;
default:
System.out.println("Invalid choice.");
}
}
}
}
+125 -9
View File
@@ -1,26 +1,142 @@
package dev.service;
import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
import dev.model.CartItem;
import dev.model.MenuItem;
import dev.model.Order;
import dev.model.OrderDetail;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class OrderService {
public void placeOrder(int userId) {
private final static OrderDetailDao orderDetailDao = new OrderDetailDao();
private final static OrderDao orderDao = new OrderDao();
private final static MenuService menuService = new MenuService();
private final static Scanner scanner = new Scanner(System.in);
// TODO:
// Create order
public static void placeOrder(int userId) {
List<CartItem> cart = new ArrayList<>();
double total = 0;
while (true){
System.out.println("==========Menu==========");
menuService.showMenu();
System.out.println("[0] finish.");
System.out.print("Select an item :");
int selectedId = scanner.nextInt();
if (selectedId == 0) {
if (cart.isEmpty()) {
System.err.println("Cart is empty.");
continue;
}
break;
}
MenuItem item = MenuService.menuItemDao.findById(selectedId);
if (item == null) {
System.err.println("Invalid item, please try again.");
continue;
}
System.out.println("Enter quantity: ");
int quantity = scanner.nextInt();
if (quantity <= 0){
System.err.println("Invalid quantity.");
}
else {
cart.add(new CartItem(
item,
quantity
));
total += item.getPrice() * quantity;
System.out.println(quantity + "x " + item.getName() + " Added to cart.");
}
}
Order order = new Order(
userId,
LocalDateTime.now(),
total
);
int orderId = orderDao.save(order);
if (orderId == -1) {
System.err.println("Order could not be placed.");
return;
}
for (CartItem cartItem : cart){
OrderDetail orderDetail = new OrderDetail(
orderId,
cartItem.getItem().getId(),
cartItem.getQuantity(),
cartItem.getItem().getPrice()
);
orderDetailDao.save(orderDetail);
}
System.out.printf("Order placed, total: $%.2f%n", total);
}
public void printReceipt(int orderId) {
public static void printReceipt(int orderId) {
List<OrderDetail> orderDetails = orderDetailDao.findByOrderId(orderId);
// TODO:
// Print order receipt
System.out.println("==========Receipt==========");
System.out.println("Order ID: " + orderId);
System.out.println("---------------------------");
if (orderDetails.isEmpty()) {
System.out.println("No order items found.");
System.out.println("===========================\n");
return;
}
public void showOrderHistory(int userId) {
double total = 0;
for (OrderDetail detail : orderDetails) {
double subtotal = detail.getPrice() * detail.getQuantity();
total += subtotal;
System.out.printf("%-20s %dx $%.2f%n",
MenuService.menuItemDao.findById(detail.getMenuItemId()).getName(),
detail.getQuantity(),
subtotal
);
}
// TODO:
// Display user's order history
System.out.println("---------------------------");
System.out.printf("Total: $%.2f%n", total);
System.out.println("===========================\n");
}
public static void showOrderHistory(int userId) {
List<Order> orders = orderDao.findByUserId(userId);
if (orders.isEmpty()){
System.err.println("No orders found.");
return;
}
System.out.println("===========Order history===========");
for (Order order : orders){
System.out.println("Order ID: " + order.getId());
System.out.println("Date: " + order.getCreatedAt());
System.out.printf("Total: $%.2f%n", order.getTotalPrice());
System.out.println("---------------------------------");
printReceipt(order.getId());
}
}
}
+42 -13
View File
@@ -1,16 +1,19 @@
package dev.ui;
import dev.model.User;
import dev.service.AuthService;
import dev.service.MenuService;
import java.util.Scanner;
public class ConsoleMenu {
private final Scanner scanner =
new Scanner(System.in);
private final Scanner scanner = new Scanner(System.in);
private final AuthService authService = new AuthService();
public void start() {
while (true) {
System.out.println();
System.out.println("===== JAVA PIZZERIA =====");
System.out.println("1. Login");
@@ -18,27 +21,53 @@ public class ConsoleMenu {
System.out.println("3. Exit");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
// TODO
break;
case 1: {
System.out.print("Enter your username: ");
String username = scanner.nextLine();
System.out.print("Enter your password: ");
String password = scanner.nextLine();
case 2:
// TODO
User user = authService.login(username, password);
if (user == null) {
System.err.println("Unable to login.");
continue;
}
System.out.println("Welcome, " + user.getUsername() + "!");
MenuService menuService = new MenuService();
menuService.userPanel(user);
break;
}
case 2: {
System.out.print("Enter your username: ");
String username = scanner.nextLine();
System.out.print("Enter your password: ");
String password = scanner.nextLine();
System.out.print("Enter your email (optional): ");
String tmp = scanner.nextLine();
String email = tmp.isEmpty() ? null : tmp;
if (!authService.register(username, password, email)) {
System.err.println("Registration failed.");
continue;
}
System.out.println("Registration successful!");
break;
}
case 3:
return;
default:
System.out.println("Invalid choice");
System.out.println("Invalid choice.");
}
}
}
}