lab2: PostgreSQL, Flyway migrations, Basic->Bearer sessions, evidence
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
altngg
2026-11-12 17:43:40 +03:00
parent 65003b6119
commit 12a3496bc6
23 changed files with 931 additions and 34 deletions
+302
View File
@@ -0,0 +1,302 @@
package ru.mtusi;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.javalin.Javalin;
import io.javalin.http.Context;
import io.javalin.http.HttpStatus;
import ru.mtusi.model.Chat;
import ru.mtusi.model.CursorResponse;
import ru.mtusi.model.Message;
import ru.mtusi.model.Session;
import ru.mtusi.model.User;
import ru.mtusi.store.PostgresStore;
public class Main {
private static PostgresStore store;
private static final ObjectMapper mapper = new ObjectMapper()
.registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
private static final Pattern USERNAME_PATTERN = Pattern.compile("^[a-z0-9_]{3,32}$");
public static void main(String[] args) {
String jdbcUrl = System.getenv().getOrDefault("DATABASE_URL", "jdbc:postgresql://localhost:5432/messenger");
String dbUser = System.getenv().getOrDefault("DATABASE_USER", "postgres");
String dbPassword = System.getenv().getOrDefault("DATABASE_PASSWORD", "postgres");
long sessionTtl = Long.parseLong(System.getenv().getOrDefault("SESSION_TTL_SECONDS", "3600"));
int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080"));
org.flywaydb.core.Flyway.configure()
.dataSource(jdbcUrl, dbUser, dbPassword)
.locations("classpath:db/migration")
.load()
.migrate();
store = new PostgresStore(jdbcUrl, dbUser, dbPassword, sessionTtl);
Javalin app = Javalin.create(config -> {
config.http.defaultContentType = "application/json";
config.jsonMapper(new JavalinJackson(mapper));
}).start("0.0.0.0", port);
app.before(ctx -> {
String requestId = ctx.header("X-Request-Id");
if (requestId == null || requestId.isBlank()) {
requestId = UUID.randomUUID().toString();
}
ctx.header("X-Request-Id", requestId);
ctx.attribute("request_id", requestId);
});
app.exception(Exception.class, (e, ctx) -> {
e.printStackTrace();
String requestId = (String) ctx.attribute("request_id");
if (requestId == null || requestId.isBlank()) requestId = UUID.randomUUID().toString();
String code = "internal_error";
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
if (e instanceof IllegalArgumentException ex) {
String msg = ex.getMessage();
if ("conflict".equals(msg)) {
code = "conflict"; status = HttpStatus.CONFLICT;
} else if ("not_found".equals(msg)) {
code = "not_found"; status = HttpStatus.NOT_FOUND;
} else if ("unauthorized".equals(msg)) {
code = "unauthorized"; status = HttpStatus.UNAUTHORIZED;
if (ctx.path().equals("/api/v1/auth/sessions") && ctx.method().name().equals("POST")) {
ctx.res().setHeader("WWW-Authenticate", "Basic realm=\"messenger\", charset=\"UTF-8\"");
} else {
ctx.res().setHeader("WWW-Authenticate", "Bearer realm=\"messenger\"");
}
} else {
code = "invalid_request"; status = HttpStatus.BAD_REQUEST;
}
}
String msg = (status == HttpStatus.INTERNAL_SERVER_ERROR)
? "Internal Server Error"
: (e.getMessage() != null ? e.getMessage() : "Error");
ctx.status(status).json(new ErrorResponseWrapper(new ApiError(code, msg, requestId)));
});
app.get("/health/live", ctx -> ctx.json(new HealthStatus("ok")));
app.get("/health/ready", ctx -> {
if (store.ping()) {
ctx.json(new HealthStatus("ok"));
} else {
String requestId = (String) ctx.attribute("request_id");
ctx.status(HttpStatus.SERVICE_UNAVAILABLE)
.json(new ErrorResponseWrapper(new ApiError("unavailable", "database unavailable", requestId)));
}
});
app.post("/api/v1/auth/sessions", ctx -> {
String authHeader = ctx.header("Authorization");
if (authHeader == null || !authHeader.startsWith("Basic ")) {
ctx.res().setHeader("WWW-Authenticate", "Basic realm=\"messenger\", charset=\"UTF-8\"");
throw new IllegalArgumentException("unauthorized");
}
String decoded;
try {
decoded = new String(Base64.getDecoder().decode(authHeader.substring(6)), StandardCharsets.UTF_8);
} catch (IllegalArgumentException ex) {
ctx.res().setHeader("WWW-Authenticate", "Basic realm=\"messenger\", charset=\"UTF-8\"");
throw new IllegalArgumentException("unauthorized");
}
int colonIndex = decoded.indexOf(':');
if (colonIndex == -1) {
ctx.res().setHeader("WWW-Authenticate", "Basic realm=\"messenger\", charset=\"UTF-8\"");
throw new IllegalArgumentException("unauthorized");
}
String username = decoded.substring(0, colonIndex);
String password = decoded.substring(colonIndex + 1);
PostgresStore.SessionData sessionData = store.createSession(username, password);
ctx.status(HttpStatus.CREATED).json(new Session(sessionData.token(), "Bearer", sessionData.expiresAt(), sessionData.user()));
});
app.delete("/api/v1/auth/sessions/current", ctx -> {
String token = requireBearerToken(ctx);
if (store.getUserByToken(token) == null) {
ctx.res().setHeader("WWW-Authenticate", "Bearer realm=\"messenger\"");
throw new IllegalArgumentException("unauthorized");
}
store.revokeSession(token);
ctx.status(HttpStatus.NO_CONTENT);
});
app.get("/api/v1/users/me", ctx -> ctx.json(requireUser(ctx)));
app.post("/api/v1/users", ctx -> {
UserRequest req = ctx.bodyAsClass(UserRequest.class);
if (req.username() == null || !USERNAME_PATTERN.matcher(req.username()).matches()) {
throw new IllegalArgumentException("invalid_request");
}
if (req.display_name() == null || req.display_name().isBlank() || req.display_name().length() > 100) {
throw new IllegalArgumentException("invalid_request");
}
if (req.password() == null || req.password().length() < 12 || req.password().length() > 128) {
throw new IllegalArgumentException("invalid_request");
}
ctx.status(HttpStatus.CREATED).json(store.registerUser(req.username(), req.display_name(), req.password()));
});
app.get("/api/v1/chats", ctx -> {
User user = requireUser(ctx);
String limitParam = ctx.queryParam("limit");
int limit;
try {
limit = (limitParam != null) ? Integer.parseInt(limitParam) : 50;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("invalid_request");
}
String cursor = ctx.queryParam("cursor");
if (limit < 1 || limit > 100) throw new IllegalArgumentException("invalid_request");
List<Chat> chats = store.getChats(user.id(), limit, cursor);
String nextCursor = (chats.size() > limit) ? chats.get(limit - 1).id() : null;
if (nextCursor != null) chats = chats.subList(0, limit);
ctx.json(new CursorResponse<>(chats, nextCursor));
});
app.get("/api/v1/chats/{chat_id}", ctx -> {
User user = requireUser(ctx);
String chatId = ctx.pathParam("chat_id");
Chat chat;
try {
chat = store.getChat(chatId);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("not_found");
}
if (chat == null || !chat.member_ids().contains(user.id())) throw new IllegalArgumentException("not_found");
ctx.json(chat);
});
app.post("/api/v1/chats", ctx -> {
User user = requireUser(ctx);
ChatRequest req = ctx.bodyAsClass(ChatRequest.class);
if (req.title() == null || req.title().isBlank() || req.title().length() > 100) {
throw new IllegalArgumentException("invalid_request");
}
if (req.member_ids() == null || req.member_ids().isEmpty() || !req.member_ids().contains(user.id())) {
throw new IllegalArgumentException("invalid_request");
}
Set<String> uniqueMembers = new HashSet<>(req.member_ids());
if (uniqueMembers.size() != req.member_ids().size() || req.member_ids().size() > 100) {
throw new IllegalArgumentException("invalid_request");
}
ctx.status(HttpStatus.CREATED).json(store.createChat(req.title(), req.member_ids()));
});
app.post("/api/v1/chats/{chat_id}/messages", ctx -> {
User user = requireUser(ctx);
String chatId = ctx.pathParam("chat_id");
MessageRequest req = ctx.bodyAsClass(MessageRequest.class);
if (req.text() == null || req.text().trim().isEmpty() || req.text().length() > 4000) {
throw new IllegalArgumentException("invalid_request");
}
Chat chat;
try {
chat = store.getChat(chatId);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("not_found");
}
if (chat == null || !chat.member_ids().contains(user.id())) throw new IllegalArgumentException("not_found");
ctx.status(HttpStatus.CREATED).json(store.addMessage(chatId, user.id(), req.text()));
});
app.get("/api/v1/chats/{chat_id}/messages", ctx -> {
User user = requireUser(ctx);
String chatId = ctx.pathParam("chat_id");
String limitParam = ctx.queryParam("limit");
int limit;
try {
limit = (limitParam != null) ? Integer.parseInt(limitParam) : 50;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("invalid_request");
}
String cursor = ctx.queryParam("cursor");
if (limit < 1 || limit > 100) throw new IllegalArgumentException("invalid_request");
Chat chat;
try {
chat = store.getChat(chatId);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("not_found");
}
if (chat == null || !chat.member_ids().contains(user.id())) throw new IllegalArgumentException("not_found");
List<Message> messages = store.getMessages(chatId, limit, cursor);
String nextCursor = (messages.size() > limit) ? messages.get(limit - 1).id() : null;
if (nextCursor != null) messages = messages.subList(0, limit);
ctx.json(new CursorResponse<>(messages, nextCursor));
});
}
private static String requireBearerToken(Context ctx) {
String authHeader = ctx.header("Authorization");
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
ctx.res().setHeader("WWW-Authenticate", "Bearer realm=\"messenger\"");
throw new IllegalArgumentException("unauthorized");
}
return authHeader.substring(7);
}
private static User requireUser(Context ctx) {
User user = store.getUserByToken(requireBearerToken(ctx));
if (user == null) {
ctx.res().setHeader("WWW-Authenticate", "Bearer realm=\"messenger\"");
throw new IllegalArgumentException("unauthorized");
}
return user;
}
public record UserRequest(
@com.fasterxml.jackson.annotation.JsonProperty("username") String username,
@com.fasterxml.jackson.annotation.JsonProperty("display_name") String display_name,
@com.fasterxml.jackson.annotation.JsonProperty("password") String password) {}
public record ChatRequest(
@com.fasterxml.jackson.annotation.JsonProperty("title") String title,
@com.fasterxml.jackson.annotation.JsonProperty("member_ids") java.util.List<String> member_ids) {}
public record MessageRequest(
@com.fasterxml.jackson.annotation.JsonProperty("text") String text) {}
public record HealthStatus(String status) {}
public record ApiError(String code, String message, String request_id) {}
public record ErrorResponseWrapper(ApiError error) {}
static class JavalinJackson implements io.javalin.json.JsonMapper {
private final ObjectMapper mapper;
JavalinJackson(ObjectMapper mapper) { this.mapper = mapper; }
public String toJsonString(Object obj, java.lang.reflect.Type type) {
try { return mapper.writeValueAsString(obj); } catch (Exception e) { throw new RuntimeException(e); }
}
public <T> T fromJsonString(String json, java.lang.reflect.Type targetType) {
try { return mapper.readValue(json, mapper.constructType(targetType)); }
catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("invalid_request");
}
}
}
}
+6
View File
@@ -0,0 +1,6 @@
package ru.mtusi.model;
import java.time.Instant;
import java.util.List;
public record Chat(String id, String title, List<String> member_ids, Instant created_at) {}
@@ -0,0 +1,5 @@
package ru.mtusi.model;
import java.util.List;
public record CursorResponse<T>(List<T> items, String next_cursor) {}
@@ -0,0 +1,3 @@
package ru.mtusi.model;
public record ErrorResponse(String code, String message, String request_id) {}
@@ -0,0 +1,5 @@
package ru.mtusi.model;
import java.time.Instant;
public record Message(String id, String chat_id, String sender_id, String text, Instant created_at) {}
@@ -0,0 +1,5 @@
package ru.mtusi.model;
import java.time.Instant;
public record Session(String token, String token_type, Instant expires_at, User user) {}
+3
View File
@@ -0,0 +1,3 @@
package ru.mtusi.model;
import java.time.Instant;
public record User(String id, String username, String display_name, Instant created_at) {}
@@ -0,0 +1,289 @@
package ru.mtusi.store;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import ru.mtusi.model.Chat;
import ru.mtusi.model.Message;
import ru.mtusi.model.User;
public class PostgresStore {
private final HikariDataSource dataSource;
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
private final long sessionTtlSeconds;
public PostgresStore(String jdbcUrl, String user, String password, long sessionTtlSeconds) {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(jdbcUrl);
config.setUsername(user);
config.setPassword(password);
config.setMaximumPoolSize(10);
config.setConnectionTimeout(5000);
config.setValidationTimeout(3000);
this.dataSource = new HikariDataSource(config);
this.sessionTtlSeconds = sessionTtlSeconds;
}
public boolean ping() {
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT 1")) {
try (ResultSet rs = ps.executeQuery()) {
return rs.next();
}
} catch (SQLException e) {
return false;
}
}
public User registerUser(String username, String displayName, String plainPassword) {
String hash = passwordEncoder.encode(plainPassword);
String sql = "INSERT INTO users (username, display_name, password_hash) VALUES (?, ?, ?) RETURNING id, created_at";
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, username);
ps.setString(2, displayName);
ps.setString(3, hash);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return new User(rs.getString("id"), username, displayName, rs.getTimestamp("created_at").toInstant());
}
}
} catch (SQLException e) {
if ("23505".equals(e.getSQLState())) throw new IllegalArgumentException("conflict");
throw new RuntimeException(e);
}
throw new RuntimeException("Failed to create user");
}
public record SessionData(String token, Instant expiresAt, User user) {}
public SessionData createSession(String username, String plainPassword) {
String sql = "SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, username);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next() || !passwordEncoder.matches(plainPassword, rs.getString("password_hash"))) {
throw new IllegalArgumentException("unauthorized");
}
User user = new User(rs.getString("id"), rs.getString("username"), rs.getString("display_name"), rs.getTimestamp("created_at").toInstant());
String token = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
Instant expiresAt = Instant.now().plusSeconds(sessionTtlSeconds);
String insertSql = "INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)";
try (PreparedStatement insertPs = conn.prepareStatement(insertSql)) {
insertPs.setString(1, token);
insertPs.setObject(2, UUID.fromString(user.id()));
insertPs.setObject(3, java.time.OffsetDateTime.ofInstant(expiresAt, java.time.ZoneOffset.UTC));
insertPs.executeUpdate();
}
return new SessionData(token, expiresAt, user);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public User getUserByToken(String token) {
String sql = "SELECT u.id, u.username, u.display_name, u.created_at FROM users u JOIN sessions s ON u.id = s.user_id WHERE s.token = ? AND s.expires_at > NOW()";
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, token);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return new User(rs.getString("id"), rs.getString("username"), rs.getString("display_name"), rs.getTimestamp("created_at").toInstant());
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return null;
}
public void revokeSession(String token) {
String sql = "DELETE FROM sessions WHERE token = ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, token);
ps.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Chat createChat(String title, List<String> memberIds) {
String chatSql = "INSERT INTO chats (title) VALUES (?) RETURNING id, created_at";
String memberSql = "INSERT INTO chat_members (chat_id, user_id) VALUES (?, ?)";
String checkUserSql = "SELECT 1 FROM users WHERE id = ?";
try (Connection conn = dataSource.getConnection()) {
conn.setAutoCommit(false);
try {
for (String memberId : memberIds) {
try (PreparedStatement ps = conn.prepareStatement(checkUserSql)) {
ps.setObject(1, UUID.fromString(memberId));
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
throw new IllegalArgumentException("invalid_request");
}
}
}
}
String chatId;
Instant createdAt;
try (PreparedStatement ps = conn.prepareStatement(chatSql)) {
ps.setString(1, title);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) throw new SQLException("Failed to create chat");
chatId = rs.getString("id");
createdAt = rs.getTimestamp("created_at").toInstant();
}
}
try (PreparedStatement ps = conn.prepareStatement(memberSql)) {
for (String memberId : memberIds) {
ps.setObject(1, UUID.fromString(chatId));
ps.setObject(2, UUID.fromString(memberId));
ps.addBatch();
}
ps.executeBatch();
}
conn.commit();
return new Chat(chatId, title, memberIds, createdAt);
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException ignore) {
}
if (e instanceof IllegalArgumentException iae) throw iae;
if (e instanceof SQLException se) throw new RuntimeException(se);
throw new RuntimeException(e);
} finally {
try {
conn.setAutoCommit(true);
} catch (SQLException ignore) {
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Chat getChat(String chatId) {
String sql = "SELECT id, title, created_at FROM chats WHERE id = ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setObject(1, UUID.fromString(chatId));
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return null;
String title = rs.getString("title");
Instant createdAt = rs.getTimestamp("created_at").toInstant();
List<String> members = new ArrayList<>();
String memSql = "SELECT user_id FROM chat_members WHERE chat_id = ?";
try (PreparedStatement memPs = conn.prepareStatement(memSql)) {
memPs.setObject(1, UUID.fromString(chatId));
try (ResultSet memRs = memPs.executeQuery()) {
while (memRs.next()) members.add(memRs.getString("user_id"));
}
}
return new Chat(chatId, title, members, createdAt);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public List<Chat> getChats(String userId, int limit, String cursor) {
int fetchLimit = limit + 1;
String keysetSql = "SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members cm ON c.id = cm.chat_id WHERE cm.user_id = ? AND (c.created_at, c.id) > (SELECT created_at, id FROM chats WHERE id = ?) ORDER BY c.created_at, c.id ASC LIMIT ?";
String noCursorSql = "SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members cm ON c.id = cm.chat_id WHERE cm.user_id = ? ORDER BY c.created_at, c.id ASC LIMIT ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(cursor != null ? keysetSql : noCursorSql)) {
ps.setObject(1, UUID.fromString(userId));
if (cursor != null) {
ps.setObject(2, UUID.fromString(cursor));
ps.setInt(3, fetchLimit);
} else {
ps.setInt(2, fetchLimit);
}
List<Chat> result = new ArrayList<>();
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String cid = rs.getString("id");
String title = rs.getString("title");
Instant createdAt = rs.getTimestamp("created_at").toInstant();
List<String> members = new ArrayList<>();
try (PreparedStatement memPs = conn.prepareStatement("SELECT user_id FROM chat_members WHERE chat_id = ?")) {
memPs.setObject(1, UUID.fromString(cid));
try (ResultSet memRs = memPs.executeQuery()) {
while (memRs.next()) members.add(memRs.getString("user_id"));
}
}
result.add(new Chat(cid, title, members, createdAt));
}
}
return result;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Message addMessage(String chatId, String senderId, String text) {
String sql = "INSERT INTO messages (chat_id, sender_id, text) VALUES (?, ?, ?) RETURNING id, created_at";
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setObject(1, UUID.fromString(chatId));
ps.setObject(2, UUID.fromString(senderId));
ps.setString(3, text);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return new Message(rs.getString("id"), chatId, senderId, text, rs.getTimestamp("created_at").toInstant());
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
throw new RuntimeException("Failed to add message");
}
public List<Message> getMessages(String chatId, int limit, String cursor) {
int fetchLimit = limit + 1;
String keysetSql = "SELECT id, sender_id, text, created_at FROM messages WHERE chat_id = ? AND (created_at, id) > (SELECT created_at, id FROM messages WHERE id = ?) ORDER BY created_at, id ASC LIMIT ?";
String noCursorSql = "SELECT id, sender_id, text, created_at FROM messages WHERE chat_id = ? ORDER BY created_at, id ASC LIMIT ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(cursor != null ? keysetSql : noCursorSql)) {
ps.setObject(1, UUID.fromString(chatId));
if (cursor != null) {
ps.setObject(2, UUID.fromString(cursor));
ps.setInt(3, fetchLimit);
} else {
ps.setInt(2, fetchLimit);
}
List<Message> result = new ArrayList<>();
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
result.add(new Message(rs.getString("id"), chatId, rs.getString("sender_id"), rs.getString("text"), rs.getTimestamp("created_at").toInstant()));
}
}
return result;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,40 @@
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
username VARCHAR(32) NOT NULL UNIQUE,
display_name VARCHAR(100) NOT NULL,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
CREATE TABLE chats (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title VARCHAR(100) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
CREATE TABLE chat_members (
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (chat_id, user_id)
);
CREATE TABLE messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
text TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
CREATE TABLE sessions (
token VARCHAR(255) PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_messages_chat_created ON messages(chat_id, created_at, id);
CREATE INDEX idx_chat_members_user ON chat_members(user_id);
CREATE INDEX idx_sessions_expires ON sessions(expires_at);