├── README.md ├── create-index.ts ├── create-table.ts ├── delete-data.ts ├── get-data.ts ├── insert-data.ts ├── joins ├── advance-1.ts ├── advance-2.ts ├── advance-3.ts └── basic.ts ├── update-data.ts └── utils.ts /README.md: -------------------------------------------------------------------------------- 1 | # SQL With Typescript 2 | -------------------------------------------------------------------------------- /create-index.ts: -------------------------------------------------------------------------------- 1 | import { getClient } from "./utils"; 2 | 3 | async function addIndex() { 4 | const client = await getClient(); 5 | 6 | const createIndexQuery = 'CREATE INDEX idx_todos_user_id ON todos(user_id)'; 7 | await client.query(createIndexQuery); 8 | 9 | console.log("Index added successfully on user_id column of todos table!"); 10 | } 11 | 12 | addIndex(); 13 | -------------------------------------------------------------------------------- /create-table.ts: -------------------------------------------------------------------------------- 1 | import { getClient } from "./utils"; 2 | 3 | async function createTable() { 4 | const createUserTableQuery = ` 5 | CREATE TABLE users ( 6 | id SERIAL PRIMARY KEY, 7 | email VARCHAR(255) UNIQUE NOT NULL, 8 | password VARCHAR(255) NOT NULL 9 | ); 10 | `; 11 | 12 | const client = await getClient(); 13 | 14 | await client.query(createUserTableQuery); 15 | 16 | const createTodosQuery = ` 17 | CREATE TABLE todos ( 18 | id SERIAL PRIMARY KEY, 19 | title TEXT NOT NULL, 20 | description TEXT, 21 | user_id INTEGER REFERENCES users(id), 22 | done BOOLEAN DEFAULT FALSE 23 | ); 24 | `; 25 | 26 | 27 | await client.query(createTodosQuery); 28 | 29 | console.log("Table created successfully!"); 30 | } 31 | 32 | 33 | 34 | createTable(); -------------------------------------------------------------------------------- /delete-data.ts: -------------------------------------------------------------------------------- 1 | import { getClient } from "./utils"; 2 | 3 | async function deleteTodo(todoId: number) { 4 | const client = await getClient(); 5 | 6 | const deleteTodoText = 'DELETE FROM todos WHERE id = $1'; 7 | await client.query(deleteTodoText, [todoId]); 8 | 9 | console.log(`Todo with ID ${todoId} deleted!`); 10 | } 11 | 12 | const todoIdToDelete = 1; 13 | deleteTodo(todoIdToDelete); 14 | -------------------------------------------------------------------------------- /get-data.ts: -------------------------------------------------------------------------------- 1 | import { getClient } from "./utils"; 2 | 3 | async function getUsers() { 4 | 5 | const client = await getClient(); 6 | 7 | const selectUsersText = "SELECT * FROM users"; 8 | const userRes = await client.query(selectUsersText); 9 | 10 | console.log("Users:"); 11 | for (let user of userRes.rows) { 12 | console.log(`ID: ${user.id}, Email: ${user.email}`); 13 | } 14 | 15 | } 16 | 17 | async function getUserFromEmail(email: string) { 18 | const client = await getClient(); 19 | 20 | const selectUserText = "SELECT * FROM users WHERE email = $1"; 21 | const userRes = await client.query(selectUserText, [email]); 22 | 23 | console.log("Single User detail:"); 24 | for (let user of userRes.rows) { 25 | console.log(`ID: ${user.id}, Email: ${user.email}`); 26 | } 27 | } 28 | 29 | async function getTodosForUser(userId: number) { 30 | const client = await getClient(); 31 | 32 | const selectTodosText = "SELECT * FROM todos WHERE user_id = $1"; 33 | const todoRes = await client.query(selectTodosText, [userId]); 34 | 35 | console.log(`Todos for User ID ${userId}:`); 36 | for (let todo of todoRes.rows) { 37 | console.log( 38 | `ID: ${todo.id}, Title: ${todo.title}, Description: ${todo.description}, Done: ${todo.done}` 39 | ); 40 | } 41 | } 42 | 43 | getUsers(); 44 | 45 | getUserFromEmail("john.do11e@gmail2.com"); 46 | 47 | const userIdToFetch = 1; 48 | getTodosForUser(userIdToFetch); 49 | -------------------------------------------------------------------------------- /insert-data.ts: -------------------------------------------------------------------------------- 1 | import { getClient } from "./utils"; 2 | 3 | async function createEntries() { 4 | const client = await getClient(); 5 | const insertUserText = 6 | "INSERT INTO users (email, password) VALUES ($1, $2) RETURNING id"; 7 | const userValues = ["john.do11e@gmail2.com", "hashed_password_here"]; 8 | 9 | let response = await client.query(insertUserText, userValues); 10 | const insertTodoText = 11 | "INSERT INTO todos (title, description, user_id, done) VALUES ($1, $2, $3, $4) RETURNING id"; 12 | const todoValues = [ 13 | "Buy groceries", 14 | "Milk, bread, and eggs", 15 | response.rows[0].id, 16 | false, 17 | ]; 18 | await client.query(insertTodoText, todoValues); 19 | 20 | console.log("Entries created!"); 21 | } 22 | 23 | createEntries(); 24 | -------------------------------------------------------------------------------- /joins/advance-1.ts: -------------------------------------------------------------------------------- 1 | import { getClient } from "../utils"; 2 | 3 | // Get all todos for a give user 4 | // This needs to ensure that every user comes atleast once 5 | async function getUserAndTodosWithJoin(userId: number) { 6 | const client = await getClient(); 7 | 8 | const joinQuery = ` 9 | SELECT users.*, todos.title, todos.description, todos.done 10 | FROM users 11 | LEFT JOIN todos ON users.id = todos.user_id 12 | WHERE users.id = $1; 13 | `; 14 | 15 | const res = await client.query(joinQuery, [userId]); 16 | const results = res.rows; 17 | 18 | console.log("User and Todos:", results); 19 | } 20 | 21 | getUserAndTodosWithJoin(1) -------------------------------------------------------------------------------- /joins/advance-2.ts: -------------------------------------------------------------------------------- 1 | import { getClient } from "../utils"; 2 | 3 | // Get all todos for a give user 4 | // This shouldnt return a row if no todos exist for the user 5 | async function getUserAndTodosWithJoin(userId: number) { 6 | const client = await getClient(); 7 | 8 | const joinQuery = ` 9 | SELECT users.*, todos.title, todos.description, todos.done 10 | FROM users 11 | JOIN todos ON users.id = todos.user_id 12 | WHERE users.id = $1; 13 | `; 14 | 15 | const res = await client.query(joinQuery, [userId]); 16 | const results = res.rows; 17 | 18 | console.log("User and Todos:", results); 19 | } 20 | 21 | getUserAndTodosWithJoin(5) -------------------------------------------------------------------------------- /joins/advance-3.ts: -------------------------------------------------------------------------------- 1 | import { getClient } from "../utils"; 2 | 3 | async function getAllTodosWithUserDetails() { 4 | const client = await getClient(); 5 | 6 | const joinQuery = ` 7 | SELECT todos.*, users.email, users.password 8 | FROM todos 9 | JOIN users ON todos.user_id = users.id; 10 | `; 11 | 12 | const res = await client.query(joinQuery); 13 | const results = res.rows; 14 | 15 | console.log("Todos with User Details:", results); 16 | } 17 | 18 | getAllTodosWithUserDetails(); 19 | -------------------------------------------------------------------------------- /joins/basic.ts: -------------------------------------------------------------------------------- 1 | import { getClient } from "../utils"; 2 | 3 | async function getUserAndTodosSeparateQueries(userId: number) { 4 | const client = await getClient(); 5 | 6 | // Fetch user details 7 | const userQuery = 'SELECT * FROM users WHERE id = $1'; 8 | const userRes = await client.query(userQuery, [userId]); 9 | const user = userRes.rows[0]; 10 | 11 | // Fetch todos for the user 12 | const todosQuery = 'SELECT * FROM todos WHERE user_id = $1'; 13 | const todosRes = await client.query(todosQuery, [userId]); 14 | const todos = todosRes.rows; 15 | 16 | console.log("User Details:", user); 17 | console.log("Todos:", todos); 18 | } 19 | 20 | getUserAndTodosSeparateQueries(1); -------------------------------------------------------------------------------- /update-data.ts: -------------------------------------------------------------------------------- 1 | import { getClient } from "./utils"; 2 | 3 | async function updateTodo(todoId: number) { 4 | const client = await getClient(); 5 | 6 | const updateTodoText = "UPDATE todos SET done = $1 WHERE id = $2"; 7 | await client.query(updateTodoText, [true, todoId]); 8 | 9 | console.log(`Todo with ID ${todoId} updated to done!`); 10 | } 11 | 12 | const todoIdToUpdate = 1; 13 | updateTodo(todoIdToUpdate); 14 | -------------------------------------------------------------------------------- /utils.ts: -------------------------------------------------------------------------------- 1 | import { Client } from "pg"; 2 | 3 | export async function getClient() { 4 | const client = new Client( 5 | "postgresql://k3vq3i:xau_fvG9w8F6enAamJ8yvP9N3@us-east-1.sql.xata.sh/practice:main?sslmode=require" 6 | ); 7 | await client.connect(); 8 | return client; 9 | } 10 | --------------------------------------------------------------------------------