Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update setup.ts #1135

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 48 additions & 22 deletions week-10/1-postgres-simple/src/db/setup.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,56 @@
// src/db/__tests__/setup.js
import { client } from '../index';

export async function createTables() {
await client.query(`
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL
);
`);
const CREATE_USERS_TABLE = `
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL
);
`;

const CREATE_TODOS_TABLE = `
CREATE TABLE IF NOT EXISTS todos (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
title VARCHAR(255) NOT NULL,
description TEXT,
done BOOLEAN DEFAULT false
);
`;

const DROP_TODOS_TABLE = `DROP TABLE IF EXISTS todos;`;
const DROP_USERS_TABLE = `DROP TABLE IF EXISTS users;`;

await client.query(`
CREATE TABLE IF NOT EXISTS todos (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
title VARCHAR(255) NOT NULL,
description TEXT,
done BOOLEAN DEFAULT false
);
`);
export async function createTables() {
const clientConnection = await client.connect();
try {
await clientConnection.query('BEGIN');
await clientConnection.query(CREATE_USERS_TABLE);
await clientConnection.query(CREATE_TODOS_TABLE);
await clientConnection.query('COMMIT');
} catch (error) {
await clientConnection.query('ROLLBACK');
console.error('Error creating tables:', error);
throw error;
} finally {
clientConnection.release();
}
}

export async function dropTables() {
await client.query(`DROP TABLE IF EXISTS todos;`);
await client.query(`DROP TABLE IF EXISTS users;`);
const clientConnection = await client.connect();
try {
await clientConnection.query('BEGIN');
await clientConnection.query(DROP_TODOS_TABLE);
await clientConnection.query(DROP_USERS_TABLE);
await clientConnection.query('COMMIT');
} catch (error) {
await clientConnection.query('ROLLBACK');
console.error('Error dropping tables:', error);
throw error;
} finally {
clientConnection.release();
}
}

module.exports = { createTables, dropTables };