removed db/ dir, has been moved to another repo

This commit is contained in:
Evan
2025-04-03 16:21:35 -07:00
parent 3db2b4f5f3
commit 3b5853ccbc
4 changed files with 0 additions and 238 deletions
-89
View File
@@ -1,89 +0,0 @@
import { Pool } from "pg";
export interface SessionData {
discord_id: string;
session_id: string;
metadata?: Record<string, any>;
created_at?: Date;
last_active?: Date;
}
export class Database {
private pool: Pool;
constructor(pool: Pool) {
this.pool = pool;
}
/**
* Creates or updates a session
*/
async upsertSession(data: {
discord_id: string;
session_id: string;
metadata?: Record<string, any>;
}): Promise<SessionData> {
const { discord_id, session_id, metadata = {} } = data;
try {
const result = await this.pool.query(
`INSERT INTO player_sessions (discord_id, session_id, metadata)
VALUES ($1, $2, $3)
ON CONFLICT (session_id)
DO UPDATE SET
last_active = CURRENT_TIMESTAMP,
metadata = player_sessions.metadata || $3::jsonb
RETURNING *`,
[discord_id, session_id, metadata],
);
return result.rows[0];
} catch (error) {
throw new Error(`Failed to create/update session: ${error}`);
}
}
/**
* Retrieves a session by its ID
*/
async getSession(sessionId: string): Promise<SessionData | null> {
try {
const result = await this.pool.query(
"SELECT * FROM player_sessions WHERE session_id = $1",
[sessionId],
);
return result.rows[0] || null;
} catch (error) {
throw new Error(`Failed to fetch session: ${error}`);
}
}
/**
* Retrieves all sessions for a Discord user
*/
async getUserSessions(discordId: string): Promise<SessionData[]> {
try {
const result = await this.pool.query(
"SELECT * FROM player_sessions WHERE discord_id = $1 ORDER BY last_active DESC",
[discordId],
);
return result.rows;
} catch (error) {
throw new Error(`Failed to fetch user sessions: ${error}`);
}
}
/**
* Deletes a session by its ID
*/
async deleteSession(sessionId: string): Promise<boolean> {
try {
const result = await this.pool.query(
"DELETE FROM player_sessions WHERE session_id = $1 RETURNING *",
[sessionId],
);
return result.rows.length > 0;
} catch (error) {
throw new Error(`Failed to delete session: ${error}`);
}
}
}
-120
View File
@@ -1,120 +0,0 @@
import dotenv from "dotenv";
import { Pool, PoolClient } from "pg";
import { schemas } from "./Schema";
dotenv.config();
// Environment variable interface for type safety
interface DBConfig {
user: string;
host: string;
database: string;
password: string;
port: number;
ssl?: {
rejectUnauthorized: boolean;
};
}
// Create the config from environment variables
const createDBConfig = (): DBConfig => {
const config: DBConfig = {
user: process.env.DB_USER || "",
host: process.env.DB_HOST || "",
database: process.env.DB_NAME || "",
password: process.env.DB_PASSWORD || "",
port: parseInt(process.env.DB_PORT || "5432"),
};
// Add SSL if enabled
if (process.env.DB_SSL === "true") {
config.ssl = { rejectUnauthorized: false };
}
return config;
};
const pool = new Pool(createDBConfig());
// Error handling for the pool
pool.on("error", (err: Error) => {
console.error("Unexpected error on idle client", err);
process.exit(-1);
});
// Initialize database
export const initDB = async (): Promise<void> => {
let client: PoolClient | null = null;
try {
client = await pool.connect();
console.log("Connected to database, initializing schemas...");
// Execute all schema creation queries
await client.query(schemas.playerSessions);
console.log("Database initialization completed");
} catch (error) {
console.error("Error initializing database:", error);
throw error;
} finally {
if (client) {
client.release();
}
}
};
// Helper function to get a client from the pool
export const getClient = async (): Promise<PoolClient> => {
const client = await pool.connect();
return client;
};
// Query helper with automatic client release
export const query = async (text: string, params?: any[]) => {
const client = await pool.connect();
try {
return await client.query(text, params);
} finally {
client.release();
}
};
// Transaction helper
export const transaction = async <T>(
callback: (client: PoolClient) => Promise<T>,
): Promise<T> => {
const client = await pool.connect();
try {
await client.query("BEGIN");
const result = await callback(client);
await client.query("COMMIT");
return result;
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
};
// Health check function
export const checkConnection = async (): Promise<boolean> => {
try {
const client = await pool.connect();
try {
await client.query("SELECT 1");
return true;
} finally {
client.release();
}
} catch (error) {
console.error("Database connection check failed:", error);
return false;
}
};
// Clean up function for graceful shutdown
export const closePool = async (): Promise<void> => {
await pool.end();
};
export default pool;
-22
View File
@@ -1,22 +0,0 @@
// src/db/schema.ts
export const TABLES = {
PLAYER_SESSIONS: "player_sessions",
} as const;
export const schemas = {
playerSessions: `
CREATE TABLE IF NOT EXISTS ${TABLES.PLAYER_SESSIONS} (
id SERIAL PRIMARY KEY,
discord_id TEXT NOT NULL,
session_id TEXT NOT NULL UNIQUE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
last_active TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
metadata JSONB DEFAULT '{}'::jsonb
);
CREATE INDEX IF NOT EXISTS idx_discord_id
ON ${TABLES.PLAYER_SESSIONS}(discord_id);
CREATE INDEX IF NOT EXISTS idx_session_id
ON ${TABLES.PLAYER_SESSIONS}(session_id);
`,
};
-7
View File
@@ -1,7 +0,0 @@
export interface PlayerSession {
discord_id: string;
session_id: string;
created_at?: Date;
last_active?: Date;
metadata?: Record<string, any>;
}